在 Jest 中测试 Promise 的最佳方式 [英] Best Way to Test Promises in Jest

查看:28
本文介绍了在 Jest 中测试 Promise 的最佳方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

除非我误解了什么,否则解决和拒绝(https://facebook.github.io/jest/docs/expect.html#resolves) 在 vNext 之前不可用.现在/同时使用 Jest 测试承诺的推荐方法是什么?只是把期望放在然后和捕获中吗?

Unless I'm misunderstanding something, the resolves and rejects (https://facebook.github.io/jest/docs/expect.html#resolves) won't be available until vNext. What is the recommended way now/in the meantime to test promises with Jest? Is it just putting expects in the thens and 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 就开始支持这个问题了.我更改了下面接受的答案,以反映当前执行此操作的最佳方法.

UPDATE 15 June 2019: Not too long after I posted this question, Jest started supporting this out of the box. I changed the accepted answer below to reflect the currently best way to do this.

2021 年 12 月 8 日更新:在某个时候,Jest 开始支持 async/await.因此,虽然其他方法注意到了工作,但我已经(在大多数情况下)简单地使用以下内容:

UPDATE 8 Dec 2021: At some point Jest started supporting async/await. So while other methods noted work, I've taken to simply (for most cases) using something like:

it('should do something', async () => {
    const expected = true; 
    expect(await funcToTest()).toEqual(expected);
});

与大多数情况一样,async/await 比替代方案更具可读性.我现在使用 resolvesrejects 的唯一情况是针对简单的情况,例如:

As with most cases, async/await is much more readable than alternatives. The only case I use resolves or rejects now is for simple cases like:

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();
});

推荐答案

现在你也可以这样写:文档

describe('Fetching', () => {
    const filters = {
        startDate: '2015-09-01'
    };
    const api = new TestApiTransport(); 

 it('should reject if no startdate is given', () => {
   expect.assertions(1);
   return expect(MyService.fetch()).rejects.toEqual({
     error: 'Your code message',
   });
 });          


 it('should return expected data', () => {
   expect.assertions(1);
   return expect(MyService.fetch(filters, null, api)).resolves.toEqual(extectedObjectFromApi);
 });            
});

更新 (06.01.2019)

同意接受的答案不能正常工作expect.assertions(1); 完成了所有的魔法.文档链接

Agree that the accepted answer doesn't work correctly as line expect.assertions(1); does all the magic. Link to docs

expect.assertions(number) 验证一定数量的断言在测试期间调用.这在测试时通常很有用异步代码,以确保回调中的断言实际上被调用了.

expect.assertions(number) verifies that a certain number of assertions are called during a test. This is often useful when testing asynchronous code, in order to make sure that assertions in a callback actually got called.

因此将这一行放在顶部将控制在测试运行时做出特定的数量断言.

So putting this line at the top will control that the specific number of assertions are made by the time when the test is run.

这篇关于在 Jest 中测试 Promise 的最佳方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆