业力测试:在其他测试中使用异步时,随机测试失败

时间:2018-11-08 13:20:27

标签: angular karma-jasmine karma-runner

我对业力测试有疑问。运行测试时,有时会出现此错误:

HeadlessChrome 70.0.3538 (Windows 10.0.0) ERROR
  {
    "message": "An error was thrown in afterAll\n[object ErrorEvent] thrown",
    "str": "An error was thrown in afterAll\n[object ErrorEvent] thrown"
  }

如果我不做任何更改并再次运行相同的测试,则测试可能不会失败。

我已经了解到异步测试(https://github.com/karma-runner/karma/issues/2811#issuecomment-407600850)可能是一个错误,因此我删除了所有异步和falseasync测试。但是,这仍然不能解决问题。如果没有异步测试和fakeasync测试,则会出现此错误:

HeadlessChrome 70.0.3538 (Windows 10.0.0) MyComponent should create FAILED
        [object ErrorEvent] thrown
HeadlessChrome 70.0.3538 (Windows 10.0.0): Executed 50 of 55 (1 FAILED) (0 secs / 0 secs)

但是在测试此组件时,我找不到错误:

describe('MyComponent', () => {
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    const zipService = jasmine.createSpyObj('ZipService', {
        search: of([])
    });

    beforeEach(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent, OnOffSwitchComponent, TranslatePipeMock],
            imports: [
                NgbModule.forRoot(),
                FormsModule,
                ReactiveFormsModule
            ],
            providers: [
                {provide: TranslateService, useValue: translateServiceMock()},
                {provide: UtilService, useValue: utilMock()},
                {provide: ZipService, useValue: zipService}
            ]
        }).compileComponents();
        fixture = TestBed.createComponent(MyComponent);
        component = fixture.componentInstance;
        fixture.detectChanges();
    });

    it('should create', () => {
        expect(component).toBeTruthy();
    });
});

有人知道这可能是什么吗?

1 个答案:

答案 0 :(得分:0)

在每个块之前的操作是错误的,因为您试图在编译部分完成之前创建组件MyComponent,因此,如果查看https://angular.io/api/core/testing/TestBed#compileComponents,您会发现TestBed.compileComponents返回了promise。因此,您测试的样板应该发生明显变化。首先,您需要先使每个人意识到它包含一些异步活动,而这样做的方法不只一种,包括本机异步/等待,Angular提供了实用程序async()。这将使您在beforeEach(async( () => {...}))中进行测试,然后第二点是,应在编译组件时进行模拟的创建。 所以所有您的代码都看起来像

beforeEach(async(() => {
TestBed.configureTestingModule({
    declarations: [MyComponent, OnOffSwitchComponent, TranslatePipeMock],
    imports: [
        NgbModule.forRoot(),
        FormsModule,
        ReactiveFormsModule
    ],
    providers: [
        {provide: TranslateService, useValue: translateServiceMock()},
        {provide: UtilService, useValue: utilMock()},
        {provide: ZipService, useValue: zipService}
    ]
}).compileComponents().then(() => {
   fixture = TestBed.createComponent(MyComponent);
   component = fixture.componentInstance;
   fixture.detectChanges();
  });    
}));
相关问题