Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.
长话短说,我花了几个小时才找到问题的真正来源。 我使用的是angular2-moment库,其中我使用了一个名为amTimeAgo的管道。这个管道包含一个window.setTimeout(...),它永远不会被移除。 如果我删除amTimeAgo管道,则测试成功,否则测试失败。
以下是一些非常基本的代码来重现此问题:
testcomponent.html:
{{someDate | amTimeAgo}}
testcomponent.ts:
import { Component } from "@angular/core";
import * as moment from "moment";
@Component({
moduleId: module.id,
templateUrl: "testcomponent.html",
providers: [],
})
export class TestComponent{
someDate = moment();
constructor() {
}
}
testmodule.ts
import { NgModule } from "@angular/core";
import {MomentModule} from 'angular2-moment';
import { TestComponent } from './testcomponent';
@NgModule({
imports: [
MomentModule,
],
declarations: [
TestComponent,
]
})
export class TestModule {
}
testcomponent.spec.ts:
import { async, TestBed, ComponentFixture } from "@angular/core/testing";
import { TestComponent } from './testcomponent';
import { TestModule } from './testmodule';
let component: TestComponent;
let fixture: ComponentFixture<TestComponent>;
function createComponent() {
fixture = TestBed.createComponent(TestComponent);
component = fixture.componentInstance;
fixture.detectChanges();
return Promise.resolve();
}
describe("TestComponent", () => {
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
TestModule],
}).compileComponents();
}));
it('should load the TestComponent', async(() => {
createComponent().then(() => {
expect(component).not.toBe(null);
});
}));
});
有没有人知道如何成功地测试这个问题?我能否在afterEach中某种方式杀死所有“剩余”的超时?或者,我能否重置异步代码运行的区域以摆脱这个问题?
有人遇到过这个问题,或者知道如何成功测试吗?任何提示都将不胜感激。
更新: 在@peeskillet提示使用 fixture.destroy()
的解决方案后,我尝试在我的实际测试中使用此方法(这里的示例只是为了重现问题所需的最小代码)。实际测试包含嵌套的promises,否则我不需要async
和detectChanges 方法。
虽然销毁建议很好并且有助于解决简单测试中的问题,但我的实际测试包含以下语句,以确保嵌套的promises被正确解析:
it('should check values after nested promises resolved', async(() => {
createComponent().then(() => {
fixture.whenStable().then(() => {
component.selectedToolAssemblyId = "2ABC100035";
expect(component.selectedToolAssembly).toBeDefined();
expect(component.selectedToolAssembly.id).toBe("2ABC100035");
fixture.destroy();
});
fixture.detectChanges();
});
}));
问题在于,页面中使用了amTimeAgo管道,fixture.whenStable()
承诺从未得到解决,因此我的断言代码从未执行,测试仍然以相同的超时失败。
因此,即使销毁建议在给定的简化测试中起作用,它也不能让我修复实际测试。
谢谢
本