Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Karma unit testing error: Unexpected value imported by the module. Please add a @NgModule annotation

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.

like image 752
MrProgrammer Avatar asked Feb 19 '19 18:02

MrProgrammer


2 Answers

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();
}));
like image 81
nircraft Avatar answered Nov 06 '22 15:11

nircraft


use:

imports: [MatDialogModule],

instead

like image 5
Normunds Kalnberzins Avatar answered Nov 06 '22 15:11

Normunds Kalnberzins