angular Testbed overrideModule not working
Asked Answered
S

2

7

When using the following configuration for a test fixture, I get complaints that the tag cannot be found. Substituting the MockSelectionToolComponent directly in AppModule works fine, so must be something else...

 // Add the imported module to the imports array in beforeEach
    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [MockSelectionToolComponent],
            imports: [

                AppModule
            ]
        }).overrideModule(AppModule, {
            remove: {
                declarations: [SelectionToolComponent]
            }
        }).compileComponents();

        fixture = TestBed.createComponent(MappingComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
        component.initialiseMap();
    });

Error: Template parse errors: 'app-selection-tool' is not a known element:

Scutcheon answered 26/6, 2017 at 10:52 Comment(0)
S
15

So in fact we don't add it to the test module's declaration, but to the original Module:

// Add the imported module to the imports array in beforeEach
beforeEach(() => {
    TestBed.configureTestingModule({
        declarations: [],
        imports: [

            AppModule
        ]
    }).overrideModule(AppModule, {
        remove: {
                declarations: [SelectionToolComponent]
            },
        add: {
                declarations: [MockSelectionToolComponent]
        }
    }).compileComponents();

    fixture = TestBed.createComponent(MappingComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
    component.initialiseMap();
});

Good luck finding that documented anywhere.

Scutcheon answered 26/6, 2017 at 11:3 Comment(1)
Would there be a way to override the TestBed.configureTestingModule({...}) module to add entryComponents ?Delphina
D
3

As you stated, it's not possible to directly declare the overrides, but do it in a chained overriding Method. You can also use the set syntax, in component here for example, applies also for module.

    TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        declarations: [MockProductCardComponent, ProductListComponent]
        })
        .overrideComponent(ProductListComponent, {
            set: {
                providers: [
                    { provide: ActivatedRoute, useValue: { fragment: Observable.of(fragment) }},
                    { provide: PageScrollService, useClass: MockPageScrollService }
                ]
            }
        })
Dall answered 26/6, 2017 at 11:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.