我正在尝试测试异步组件方法,我认为我正确使用了 Angular 4 的异步测试功能,但它不起作用。我的问题是,当我运行测试时,它不会等待承诺解决。函数的异步性质似乎导致超时被触发并且测试过早退出。无论如何,测试都会通过,因为whenStable()
中的所有expect()
语句都会被跳过。
如果我省略 async()
包装器函数并切换到传入 done
回调并在 whenStable()
块末尾调用它的 Jasmine 语法,它可以正常工作。谁能告诉我为什么它不适用于 Angular async()
包装器?
我的代码如下所示:
// my.component.ts
ngOnInit() {
this.getResults().then((results) => {
this.results = results;
});
}
// My asynchronous function, which takes 1.5s to load results
getResults() {
let promise = new Promise((resolve) => {
setTimeout(() => {
resolve('foo');
}, 1500);
})
return promise;
}
// my.component.spec.ts (Angular async version which doesn't work)
it('should load results', async(() => {
spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar'));
component.ngOnInit();
fixture.whenStable().then(() => {
// Everything in here gets skipped when I run the test
fixture.detectChanges();
// This should cause the test to fail, but it doesn't because it's not run in time
expect(true).toBe(false)
});
}));
// my.component.spec.ts (Jasmine version that works)
it('should load results', (done) => {
spyOn(component, 'getResults').and.returnValue(Promise.resolve('bar'));
component.ngOnInit();
fixture.whenStable().then(() => {
fixture.detectChanges();
// This should fail and it does because the test works using Jasmine's "done" callback
expect(true).toBe(false);
done();
});
});
感谢@yurzui的 Plunker,我确定我的问题是由我的beforeEach()
方法中的调用fixture.detectChanges()
引起的:
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [AppComponent],
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// The following line is to blame! Removing it makes the test work correctly.
fixture.detectChanges();
});
我在处理这个问题时遇到了一些麻烦,我们通过使用 beforeEach 中的角度/测试异步函数解决了它:
beforeEach(async(() => { // <-- use async
TestBed.configureTestingModule({
declarations: [AppComponent],
});
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
// The following line is to blame! Removing it makes the test work correctly.
fixture.detectChanges();
}));
。正如文档所说:https://angular.io/guide/testing#async-test-with-async。