javascript - 使用 mapStateToProps Jest 测试 promise 函数

标签 javascript reactjs promise mocking jestjs

我有以下功能代码:

fetchDeviceList 在 mapStateToProps 的帮助下从 redux store 绑定(bind)

  componentDidMount() {
    this.props.fetchDeviceList().then(() => {
      this.saveFirstClassifiedDeviceDetails();
    });
  }

我的测试代码如下所示:

 it('should pass', () => {
    const methodNameFake = jest.spyOn(
      DeviceListContainer.prototype,
      'fetchDeviceList'
    );

    const props = {
       data: []
    };

    const connectedComponent = mount(
      <DeviceListContainer {...props} />
    );

    expect(methodNameFake).toHaveBeenCalledTimes(1);
  });

但出现错误:TypeError: this.props.fetchDeviceList is not a function

TypeError: Cannot read property '_isMockFunction' of undefined

fetchDeviceList 是一个从 redux 直接通过 mapStateToProps

绑定(bind)的函数

我需要了解测试此实现的最佳方法是什么?我是 React 的新手,这是第一次尝试为 promises 编写 Jest 测试用例,请原谅错误。

也试过;

component = shallow(
      <DeviceListContainer
        {...props}
        fetchDeviceList={jest.fn().mockReturnValue(() => {
          return Promise.resolve('yo');
        })}
      />
    );

然后我得到错误:TypeError: this.props.fetchDeviceList(...).then is not a function

我们是否需要在测试时传递 props,这是正确的处理方式吗,因为 props 数据将在组件从 Redux store 挂载后立即生成。最好的方法是什么?

有人知道我做错了什么吗?

最佳答案

Redux 文档中有一节是关于测试 Redux 容器的。

https://redux.js.org/recipes/writing-tests#connected-components

在上面的链接中提到了它,但我建议只测试内部表示组件,而不是尝试测试 Redux 的 connect() 返回的高阶组件。功能。

您对自己编写的单元测试代码感兴趣,即内部表示组件,而不是 Redux 团队编写的代码,后者是调用 connect() 的结果。 .

因此,只要您只测试 DeviceList,您已经拥有的东西应该可以工作。直接,而不是容器:

component = shallow(
  <DeviceList
    data={[]}
    fetchDeviceList={jest.fn().mockReturnValue(() => {
      return Promise.resolve('yo');
    })}
  />
);

关于javascript - 使用 mapStateToProps Jest 测试 promise 函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51550520/

相关文章:

javascript - 在 XSL 转换期间在字符串中保留注释符号

javascript - 如何删除 extjs checkboxmodel 中的 checkall 选项?

javascript - 有条件地提前退出一系列 promise 而不抛出错误

javascript - 使用jQuery promise模拟同步调用

javascript - jQuery 验证等于

javascript - 下载不同名称的html页面

reactjs - 未找到具有指定模式 : D:\a\r1\a\**\*. zip 的包

javascript - 与 Material UI 表分页 react 显示所有条目

javascript - Bootstrap react ./node_modules/bootstrap/dist/js/bootstrap.min.js 找不到模块: Can't resolve 'jquery'

javascript - promise 链中 promise 之间的延迟