我想在解析promise之前测试应用程序的状态。我在beforeEach块中创建promise,所以我希望在promise解析之前执行所有测试。但是当测试被执行时,promise已经被解析,代码处于post promise状态。
// jest code
describe("sync beforeEach", () => {
let promise;
let state;
beforeEach(() => {
state = 'pending'
promise = Promise.resolve().then(() => { state = 'resolved'; });
});
test('should run before resolve', async () => {
// the promise is resolved and the bellow line fails.
expect(state).toEqual('pending');
await promise;
expect(state).toEqual('resolved');
});
});
我已经使用Jasmine实现了完全相同的测试,并且正如我所预期的那样。promise在测试之前不会被解析,因此测试通过。
// jasmine code
describe("sync beforeEach", () => {
let promise;
let state;
beforeEach(() => {
state = 'pending'
promise = Promise.resolve().then(() => { state = 'resolved'; });
});
it('should run before resolve', async () => {
// the promise is not resolved yet, so the bellow line pass
expect(state).toEqual('pending');
await promise;
expect(state).toEqual('resolved');
});
});
如何使用jest进行相同的测试?
1条答案
按热度按时间njthzxwz1#
如果只在需要运行Promise的时候才使用await来运行Promise呢?示例: