如何使用Jest使用Promise.all为多个访存设置测试 [英] How to set a test for multiple fetches with Promise.all using jest

查看:611
本文介绍了如何使用Jest使用Promise.all为多个访存设置测试的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开玩笑地进行测试.我正在使用react和redux,我有这个动作:

I'm using jest for my tests. I'm using react and redux and I have this action:

function getData(id, notify) {
 return (dispatch, ...) => {
   dispatch(anotherFunction());
   Promise.all(['resource1', 'resource2', 'resource3'])
   .then(([response1,response2,response3]) => {
        ... handle responses
    })
   .catch(error => { dispatch(handleError(error)); }
 };
}

我一直在寻找有趣的文档,以了解如何为此操作设置测试,但我找不到方法.我尝试过这样的事情:

I've been looking for into the jest documentation how to set a test for this action, but I was unable to find a way. I tried myself something like this:

it('test description', (done) => {
  const expectedActions = [{type: {...}, payload: {...}},{type: {...}, payload: {...}},...];
  fetchMock.get('resource1', ...);
  fetchMock.get('resource2', ...);
  fetchMock.get('resource3', ...);
   ... then the rest of the test calls
});

失败.那我该怎么办?

推荐答案

要使用Promise.all,您可以执行以下操作

To use Promise.all you could do the following

test('Testing Stuff', async (done) => {

  const expectedActions = [{ foo: {...}, bar: {...} }, { foo: {...}, bar: {...} }];

  // we pass the index to this function 
  const asyncCall = async (index) => {
    // check some stuff
    expect(somestuff).toBe(someOtherStuff);
    // await the actual stuff
    const response = await doStuff( expectedActions[index] );
    // check the result of our stuff
    expect(response).toBe(awesome);
    return response;
  };

  // we put all the asyncCalls we want into Promise.all 
  const responses = await Promise.all([
    asyncCall(0),
    asyncCall(1),
    ...,
    asyncCall(n),
  ]);

  // this is redundant in this case, but wth
  expect(responses).toEqual(awesome);

  done();

});

这篇关于如何使用Jest使用Promise.all为多个访存设置测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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