How to test angular 2 component with nested components inside with their own dependencies ? (TestBed.configureTestingModule)

Stefdelec picture Stefdelec · Mar 22, 2017 · Viewed 17.6k times · Source

I have a component A that use a component B,c,D in its template:

###template-compA.html

    <comp-b></comp-b>
    <comp-c [myinput]="obj.myinput"></comp-c>
    <comp-d ></comp-d>

...etc

To simplify, let's say their is only one directive in component A:

 ###template-compA.html

    <comp-b></comp-b>

My comp-b has its own dependencies (services or other comp).

If I want to test comp-a this way:

TestBed.configureTestingModule({
    declarations: [comp-A],
    imports: [ReactiveFormsModule],
}).overrideComponent(FAQListComponent, {
    set: {
    providers: [
        { provide: comp-AService, useValue: comp-AListSVC }
    ]
    }
})
    .compileComponents();

it would not work properly. So I do:

TestBed.configureTestingModule({
    declarations: [comp-A, comp-B],
    imports: [ReactiveFormsModule],
}).overrideComponent(FAQListComponent, {
    set: {
    providers: [
        { provide: comp-AService, useValue: comp-AListSVC }
    ]
    }
})
    .compileComponents();

It doesn't work also because comp-b doesn't have its own dependencies. And here I am confused, how can I do unit test if I have to import and remock all others components every single time ? It looks like a very big amount of work. Is there another way? What would be the best practice to test component with nested componentS that have their own dependencies ?

Thanks a lot,

Stéphane.

Answer

Borquaye picture Borquaye · Mar 22, 2017

If you don't need to reference comp-b in any way in your tests you can add schemas: [NO_ERRORS_SCHEMA] or [CUSTOM_ELEMENTS_SCHEMA] to your TestBed configuration or override the comp-A's template and remove the tag for comp-b

If you do need to reference comp-b you may not need to provide it's dependencies specifically in an override.

Setting providers in overrideComponent is only necessary if the dependency is provided in the component itself. (If you have a providers list in comp-A.ts)

let's say comp-b needs a comp-AService and comp-AService is being provided in your comp-A override, since comp-b is a child of comp-A it will have comp-AService provided for it.

If you are providing these dependencies in your app.module or somewhere higher than the component itself you don't need to override. For example if comp-b needs comp-AService & someOtherService which are both being provided in your app.module your TestBed configuration could look like this:

TestBed.configureTestingModule({
  declarations: [comp-A, comp-B],
  imports: [ReactiveFormsModule],
  providers: [
    { provide: comp-AService, useValue: comp-AListSVC },
    { provide: someOtherService, useValue: someOtherServiceSVC }
  ]
})

Edit:

You can read more about nested component testing here:

https://angular.io/guide/testing-components-scenarios#nested-component-tests