【问题标题】:React-Redux: Jest failing to test async action (Always pass)React-Redux:Jest 未能测试异步操作(始终通过)
【发布时间】:2018-11-02 11:09:32
【问题描述】:

我正在使用 Jest 为一些 Redux 操作实现单元测试。

但是,由于某种原因,这个测试用例永远不会失败。

该操作的摘要版本如下所示:

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

测试它的笑话代码:

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

记录信息显示值不相等,但是,Jest 始终通过此测试。 我什至尝试添加

fail('Just fail')

但测试仍然通过,即使数据完全不同或强制失败。

我环顾四周看到类似的代码,但我看不出我的代码有任何有意义的差异,例如this one

我还注释掉了 Promise 中的所有代码,并强制它在测试代码上失败...仍然通过。

知道可能出了什么问题吗?

【问题讨论】:

    标签: javascript react-redux jestjs es6-promise


    【解决方案1】:

    一旦您的代码执行完毕,测试就被认为已完成。

    你需要告诉 Jest 等到你的承诺兑现。

    您可以通过向您的test|it 函数传递一个参数(我们称之为done)来做到这一点,这样,Jest 将等到done 被调用。

    所以基本上是这样的:

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

    对于您的示例,请在您的 except 之后调用 done

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

    source

    【讨论】:

    • 哦,简单而好的答案:)谢谢!
    猜你喜欢
    • 1970-01-01
    • 2021-05-26
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 2012-05-20
    • 2021-04-03
    • 2018-04-12
    相关资源
    最近更新 更多