如何使用 jest 通过 Promise.all 设置多次提取测试

2024-05-14

我在测试中使用 jest。我正在使用 React 和 Redux,并且执行以下操作:

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

我一直在寻找笑话文档如何为此操作设置测试,但我找不到方法。我自己尝试过这样的事情:

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

不成功。那么我应该如何进行呢?


To use Promise.all你可以执行以下操作

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

});
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

如何使用 jest 通过 Promise.all 设置多次提取测试 的相关文章