angular Testbed overrideModule不工作

时间:2017-06-26 10:52:18

标签: angular angular-test testbed

对测试夹具使用以下配置时,我抱怨无法找到标签。直接在MockSelectionToolComponent中替换AppModule可以正常工作,所以必须是别的......

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

错误:模板解析错误:' app-selection-tool'不是众所周知的   元素:

2 个答案:

答案 0 :(得分:4)

所以实际上我们不会将它添加到测试模块的声明中,而是添加到原始模块:

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

祝你在任何地方找到记录好运。

答案 1 :(得分:0)

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

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