Search code examples
angularangular-testtestbed

angular Testbed overrideModule not working


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:


Solution

  • 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.