TestBed配置期望注入或导入应用程序中的所有组件和服务

时间:2018-03-26 20:18:07

标签: angular unit-testing karma-jasmine

我的组件有一个构造函数,它接受后端服务

    something = "abc";
constructor(private inspectionService: InspectionService) {//
    this.inspectionService.getMaintenanceOptions().subscribe(maintenanceOptions => {
        this.maintenanceOptions = maintenanceOptions;
    });

尝试为此设置测试我有以下代码。

describe('PI Time Control Comment', () => {
let mockInspectionService = jasmine.createSpyObj('InspectionService', ['getInspectionList']);
let component: InspectionFindingComponent;
let fixture: ComponentFixture<InspectionFindingComponent>;
beforeEach(() => {
    TestBed.configureTestingModule({
        schemas: [NO_ERRORS_SCHEMA],
        imports: [FormsModule,AppRoutingModule, CookieModule.forRoot(), DropDownsModule,
            HttpModule, HttpClientModule, StoreModule.provideStore({ orders })],
        declarations: [InspectionFindingComponent,LoginComponent,HomeComponent,DashboardComponent], // it is expecting all the components to be injected
        providers: [CookieService, AuthenticationService, // it is requiring all the services to be injected 
            HttpHelperService, UserService, {
                provide: HTTP_INTERCEPTORS,
                useClass: AuthInterceptorService,
                multi: true
            }, {
                provide: InspectionService,
                useValue: mockInspectionService
            }]

    }).compileComponents();;
});
beforeEach(() => {
    fixture = TestBed.createComponent(InspectionFindingComponent);
     component = fixture.componentInstance;
     fixture.detectChanges();
    // component.PO = new PurchaseOrder();
  });
it('somethinggggggggg++++++++++++++++++', () => {
    // local arrange

    // act

    // assert
    expect(component.something).toBe("abc");
});

当我添加一个组件时,它会要求另一个组件。并继续给我错误。

&#34;错误:组件BinningListComponent不是任何NgModule的一部分,或者模块尚未导入模块。&#34;

如果我解决这个问题,它会要求另一个组件。那么如何解决这个问题呢?

1 个答案:

答案 0 :(得分:0)

您始终可以通过创建伪造的@NgModule()来抑制错误。

@NgModule({
  imports: [...],
  declarations: [BinningListComponent, ... all the other component],
  exports: [BinningListComponent, ... all the other components],
})
export class TestModule {}

然后在TestBed中导入模块。

TestBed.configureTestingModule({
        schemas: [...],
        imports: [TestModule],
        declarations: [...],
        providers: [...]
    }).compileComponents();