我是Angular的新手,我还在试图了解它的工作原理。我目前在测试一个依赖服务的Component时遇到了问题,这个服务会返回一个 "承诺"。Promise
. 我测试的函数结构如下。
success: boolean;
borrowBook() {
this.bookService.borrow(this.selectedBook.id)
.then(() => {
this.success = true;
})
.catch((error: BorrowingError) => {
this.success = false;
});
}
现在,我不太确定像上面的代码是否算是习惯性的, 但我就是这样写的代码。在我的单元测试中,我模仿了 bookService
使用 jasmine.createSpyObj
函数,并将存根定义如下。
mockBookService.borrow.and.returnValue(Promise.resolve(testResult));
然而,我的测试失败了,说 component.success
是未定义的,而我希望它是真实的。我的测试程序如下。
it('test', async(() => {
mockBookService.borrow.and.returnValue(Promise.resolve(testResult));
//setup pre-conditions here...
component.borrowBook(();
expect(component.success).toBeTruthy();
}));
我的印象是,在Promise被相应处理之前,期望值就已经被检查了。
我偶然发现了这个 关于在Angular中测试异步代码的文章其中指出: flushMicrotasks
函数可以用来在检查期望值之前运行所有的异步组件。这仅通过通过 fakeAsync
因此,在我的代码中,我使用了这一点,而不是仅仅使用了 async
.
it('test', fakeAsync(() => { //used fakeAsync instead
mockBookService.borrow.and.returnValue(Promise.resolve(testResult));
//setup pre-conditions here...
component.borrowBook(();
flushMicrotasks(); //added this before checking expectations
expect(component.success).toBeTruthy();
}));