除非我误解了什么,否则解决和拒绝 ( https://facebook.github.io/jest/docs/expect.html#resolves ) 将在 vNext 之前不可用。现在/同时使用 Jest 测试承诺的推荐方法是什么?它只是把期望放在 thens 和 catches 中吗?
例如:
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 在某个时候开始支持异步/等待。因此,虽然其他方法也有效,但我只是(在大多数情况下)使用类似的方法:
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();
});
原文由 Ambrose Little 发布,翻译遵循 CC BY-SA 4.0 许可协议
现在你也可以这样写: docs
更新 (06.01.2019)
同意接受的答案不能正常工作,因为行
expect.assertions(1);
具有所有魔力。 文档链接所以把这一行放在最前面会控制在测试运行的时候进行断言的具体 数量。