angular 测试平台 overrideModule 不工作

angular Testbed overrideModule not working

当对测试夹具使用以下配置时,我收到无法找到标签的投诉。直接在 AppModule 中替换 MockSelectionToolComponent 效果很好,所以一定是别的东西......

 // 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:

所以实际上我们并没有把它添加到测试模块的声明中,而是添加到原来的模块中:

// 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();
});

祝你好运,发现任何地方都有记录。

如您所说,直接声明覆盖是不可能的,但可以在链式覆盖方法中进行。 您还可以使用 set 语法,例如在此处的组件中,也适用于模块。

    TestBed.configureTestingModule({
        imports: [RouterTestingModule],
        declarations: [MockProductCardComponent, ProductListComponent]
        })
        .overrideComponent(ProductListComponent, {
            set: {
                providers: [
                    { provide: ActivatedRoute, useValue: { fragment: Observable.of(fragment) }},
                    { provide: PageScrollService, useClass: MockPageScrollService }
                ]
            }
        })