我想知道这两种处理Angular框架异步调用的方法在测试时的区别:
- 第一个使用 jasmine 方法 async/await
- 第二个使用 Angular 方法 async/fixture.whenStable
它们相似吗?如果不是,有什么区别,我应该在什么时候使用一个而不是另一个?
最佳答案
async/await
的第一种方法是普通 JavaScript,您可以在其中异步运行函数,并且可以等待 promise,然后再转到下一行。
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 block )。
编辑 ====================
为了处理可观察对象,我使用了两种方法。
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();
});
});
关于angular - Angular 中 async/await 和 async/fixture.whenStable 的区别,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62071276/