我想了解在 Angular 框架测试中处理异步调用的这两种方法的区别:
- 第一种是使用 Jasmine 方法的 async/await
- 第二种是使用 Angular 方法的 async/fixture.whenStable
它们相似吗?如果不是,它们有什么区别,我应该在什么情况下使用其中一种而不是另一种?
我想了解在 Angular 框架测试中处理异步调用的这两种方法的区别:
它们相似吗?如果不是,它们有什么区别,我应该在什么情况下使用其中一种而不是另一种?
async / await 的第一种方法是使用原始的 JavaScript,您希望以异步方式运行函数,并且可以在继续下一行之前等待承诺。
it('it block in an async await way', async(done) => {
await waitForThisFunctionThatReturnsAPromiseBeforeCarringForward();
// do something, make assertions
const x = await getXFromAPromise(); // wait for getXFromAPromise() function to return the promise
// and assign the results to x
// do something, make assertions
done(); // call done to ensure you have run through the whole it block and tell Jasmine you're done
});
fixture.whenStable
基本上等待堆栈中所有的 Promise 都被解析后才继续执行断言。
it('demonstration of fixture.whenStable', async(done) => {
// do some actions that will fire off promises
await fixture.whenStable(); // wait until all promises in the call stack have been resolved
// do some more assertions
done(); // call done to tell Jasmine you're done with this test.
});
done回调函数是可选的,但我使用它来确保更好的工程质量(确保它遍历整个 it 块)。
编辑====================
要处理可观察对象,我使用两种方法。
async/await
与take
和toPromise
操作符一起使用,其中您接收第一个发射并将其转换为Promise。可以添加其他运算符,如filter
,以忽略在take(1)
之前的某些发射。
import { take } from 'rxjs/operators';
......
it('should do xyz', async done => {
const x = await component.observable$.pipe(take(1)).toPromise();
expect(x).toBe(....);
done();
});
另一种方法是使用 done
回调函数进行订阅。
it('should do xyz', done => {
component.observable$.subscribe(result => {
expect(result).toBe(...);
// call done here to ensure the test made it within the subscribe
// and did the assertions and to let Jasmine know you're done with the tests
done();
});
});