【发布时间】:2017-08-19 15:19:54
【问题描述】:
除非我有什么误解,否则解析和拒绝 (https://facebook.github.io/jest/docs/expect.html#resolves) 将在 vNext 之前可用。现在/同时使用 Jest 测试 Promise 的推荐方法是什么?是否只是将期望放在 thens 和 catchs 中?
例如:
describe('Fetching', () => {
const filters = {
startDate: '2015-09-01'
};
const api = new TestApiTransport();
it('should reject if no startdate is given', () => {
MyService.fetch().catch(e => expect(e).toBeTruthy()); // see rejects/resolves in v20+
});
it('should return expected data', () => {
MyService.fetch(filters, null, api).then(serviceObjects => {
expect(serviceObjects).toHaveLength(2);
}).catch(e => console.log(e));
});
});
2019 年 6 月 15 日更新:在我发布这个问题后不久,Jest 就开始支持这个问题。我更改了下面接受的答案,以反映当前执行此操作的最佳方法。
2021 年 12 月 8 日更新:在某个时候,Jest 开始支持 async/await。因此,虽然其他方法注意到工作,我已经采取简单(在大多数情况下)使用类似的东西:
it('should do something', async () => {
const expected = true;
expect(await funcToTest()).toEqual(expected);
});
与大多数情况一样,async/await 比替代方案更具可读性。我现在使用resolves 或rejects 的唯一情况是针对以下简单情况:
it('should not throw when doing something', async () => {
await expect(funcToTest()).resolves.not.toThrow();
});
it('should throw when something is wrong', async () => {
await expect(funcToTest()).rejects.toThrow();
});
【问题讨论】:
标签: javascript promise jestjs