【问题标题】:How to set a test for multiple fetches with Promise.all using jest如何使用 Promise.all 使用 jest 为多个提取设置测试
【发布时间】:2017-12-04 11:47:40
【问题描述】:

我正在使用 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)); }
 };
}

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

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

不成功。那我应该怎么做呢?

【问题讨论】:

    标签: javascript reactjs testing redux jestjs


    【解决方案1】:

    您可以通过在回调中返回 Promise 来告诉 Jest 等待 Promise 解决。有关更多信息,请参阅此部分 here

    it('should fetch some food', () => {
      const fetchItem1 = () => fetchData1().then(data => {
        expect(data).toBe('peanut butter');
      })
      const fetchItem2 = () => fetchData2().then(data => {
        expect(data).toBe('boiled egg');
      })
      const fetchItem3 = () => fetchData3().then(data => {
        expect(data).toBe('fried salad');
      })
    
      return Promise.all([fetchItem1(), fetchItem2(), fetchItem3()])
        .then(() => runOtherTests());
    });
    

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        猜你喜欢
        • 2019-03-18
        • 2020-05-05
        • 1970-01-01
        • 2019-11-20
        • 2017-11-11
        • 2020-06-12
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多