简体   繁体   English

React-Redux:Jest 未能测试异步操作(始终通过)

[英]React-Redux: Jest failing to test async action (Always pass)

I'm implementing unit tests for some Redux actions using Jest.我正在使用 Jest 为一些 Redux 操作实现单元测试。

However, for some reason, this test case never fails.然而,出于某种原因,这个测试用例永远不会失败。

A summarized version of the action looks like this:该操作的汇总版本如下所示:

export function attachFile(file) {
  return (dispatch, getState) => {
    return new Promise((resolve, reject) => {
      const reader = new FileReader();
      reader.onload = () => {
        dispatch({
          type: actionTypes.ATTACH_FILE_DONE,
          file: {
            content: reader.result,
            size: file.size,
            mimeType: file.type,
            name: file.name,
          },
        });
        resolve();
      };
      reader.onerror = (error) => {
        const errorMessage = `Error reading file: ${file.name}: ${error}`;
        dispatch({
          type: actionTypes.ATTACH_FILE_FAIL,
          errorMessage,
        });
        reject(errorMessage);
      };
      reader.readAsDataURL(file);
    });
  };
}

The jest code testing it:测试它的笑话代码:

store.dispatch(attachFile(file)).then(() => {
  console.log('ACTUAL ACTIONS:', store.getActions());
  console.log('EXPECTED ACTIONS:', expectedActions);
  expect(store.getActions()).toEqual(expectedActions);
})

Logging the information shows me that the values are not equal, however, Jest always pass this test.记录信息显示值不相等,但是, Jest始终通过此测试。 I have even trying adding我什至尝试添加

fail('Just fail')

But the tests still pass, even with the data being totally different or forcing fail.但是测试仍然通过,即使数据完全不同或强制失败。

I have looked around to see similar codes, but I can't see any meaningful difference to my code, like this one我环顾四周以查看类似的代码,但我看不到我的代码有任何有意义的差异,例如这个

I also have commented out all the code inside the Promise and forced it to fail on the test code... still pass.我还注释掉了 Promise 中的所有代码,并强制它在测试代码上失败......仍然通过。

Any idea what might be wrong?知道可能有什么问题吗?

The tests are considered done as soon as your code finish executing.一旦您的代码完成执行,就认为测试已经完成。

You will need to tell Jest to wait until your promise is fulfilled.您需要告诉 Jest 等到您的承诺兑现。

You can do this by passing an argument (let's call it done ) to your test|it function, this way, Jest will wait until done is called.您可以通过将参数(让我们称之为done )传递给您的test|it函数来done这一点,这样,Jest 将等到done被调用。

So basically something like this :所以基本上是这样的:

test('the data is peanut butter', done => {
  function callback(data) {
    expect(data).toBe('peanut butter');
    done();
  }

  fetchData(callback);
});

For your example, call done after your except :对于您的示例,请在您的except之后调用done

{
    ...
    expect(store.getActions()).toEqual(expectedActions);
    done();
}

source来源

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM