27

I've created a fresh new component via:

ng g mytest1

Then I changed the constructor line to this:

constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }

, and added the required import:

import { MatDialogRef } from '@angular/material';

After that I ran the Karma unit test project via:

ng test

The test failed. I got this error message:

Error: StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!

To fix that I added the Import statement in the beforeEach section:

import { MatDialogRef } from '@angular/material';

//...

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ Mytest1Component ],
        imports: [MatDialogRef],
    })
    .compileComponents();
}));

Now I got this new error, which I am not able to fix:

Failed: Unexpected value 'MatDialogRef' imported by the module 'DynamicTestModule'. Please add a @NgModule annotation.

Can someone clarify where I should be adding the @NgModule annotation, or if I had done something completely wrong?

Thank you.

Gregor Albert
  • 819
  • 1
  • 11
  • 23
MrProgrammer
  • 589
  • 1
  • 7
  • 17
  • Does this answer your question? [Angular error: Please add a @NgModule annotation](https://stackoverflow.com/questions/52417373/angular-error-please-add-a-ngmodule-annotation) – Liam Mar 10 '22 at 14:46

2 Answers2

38

You are injecting MatDialogRef in component:

constructor(private dialogRef: MatDialogRef<Mytest1Component>) { }

So the testBed expects the same to be injected as provider to the TestBed. Or you can also provide a MockDialogueService to it.

beforeEach(async(() => {
    TestBed.configureTestingModule({
        declarations: [ Mytest1Component ],
        providers: [ MatDialogRef ],
    })
    .compileComponents();
}));
nircraft
  • 8,242
  • 5
  • 30
  • 46
  • 2
    Thank you. That was the first mistake on my part. Now I'm getting another problem, and would appreciate it if you could help out... Is says, "Failed: Can't resolve all parameters for MatDialogRef: (?, ?, ?, ?)." – MrProgrammer Feb 19 '19 at 19:03
  • 1
    Update: I had to follow the recommendation here: https://stackoverflow.com/questions/48058457/failed-cant-resolve-all-parameters-for-matdialogref-unit-testing-a – MrProgrammer Feb 19 '19 at 19:38
5

use:

imports: [MatDialogModule],

instead

Normunds Kalnberzins
  • 1,213
  • 10
  • 20
  • Thank you. I got still got the message, "Error: StaticInjectorError(DynamicTestModule)[Mytest1Component -> MatDialogRef]: StaticInjectorError(Platform: core)[Mytest1Component -> MatDialogRef]: NullInjectorError: No provider for MatDialogRef!" – MrProgrammer Feb 19 '19 at 19:16
  • 1
    Update: That line was useful. What was still missing was the recommendation made by nircraft: 'providers: [ MatDialogRef ],' Thank you for the help. – MrProgrammer Feb 19 '19 at 19:45