28

I am having a problem in testing app.component.ts in Angular 2. I am using angular-cli. Whenever I run ng test, my app.component.spec.ts makes the console prompt with the error:

 Failed: Unexpected directive 'HomeModuleComponent' imported by the module 'DynamicTestModule'
 Error: Unexpected directive 'HomeModuleComponent' imported by the module 'DynamicTestModule'

I imported the HomeModuleComponent in TestBed

TestBed.configureTestingModule({
  declarations: [AppComponent],
  imports : [ HomeModuleComponent ]
});

Can anyone help me with this problem?

xiotee
  • 1,519
  • 2
  • 14
  • 23
  • 3
    I think I have found the problem as of now. The HomeModuleComponent must be in the declarations not in the imports. Moreover, can you import a Module in your TestBed? Thanks. – xiotee Oct 13 '16 at 07:27

2 Answers2

29

HomeModuleComponent is Component not the Module, so it has to be in declarations:

TestBed.configureTestingModule({
  declarations: [AppComponent, HomeModuleComponent],
  imports : [ ]
});

and then you can create the component to test as,

TestBed.createComponent(AppComponent);
KernelPanic
  • 2,328
  • 7
  • 47
  • 90
3

In my test spec, by mistake I was importing a service instead of providing it. I was getting the same error.

Adding the service back inside providers array resolved my error.

Amit Chigadani
  • 28,482
  • 13
  • 80
  • 98