在Jest中测试承诺的最佳方法 [英] Best Way to Test Promises in Jest

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

问题描述

除非我误会了某些内容,否则将解决并拒绝( 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.

推荐答案

如今,您也可以用这种方式编写它:

Nowadays you can write it in this way as well: docs

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中测试承诺的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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