【问题标题】:Testing promise functions in jest with mapStateToProps用 mapStateToProps 开玩笑地测试 Promise 函数
【发布时间】:2019-01-04 03:21:00
【问题描述】:

我有以下功能代码:

fetchDeviceList 在 mapStateToProps 的帮助下从 redux 存储绑定

  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是一个直接通过mapStateToProps从redux绑定的函数

我需要了解测试此实现的最佳方法是什么?我是 React 新手,这是第一次尝试为 Promise 编写 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 存储加载后立即生成。最好的方法是什么?

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

【问题讨论】:

    标签: javascript reactjs promise mocking jestjs


    【解决方案1】:

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

    【讨论】:

    • 感谢@Jed Richards,它对我有用,我试过了,但是道具是从mapStateToProps 生成的,将它从​​ UT 直接传递给组件是正确的方法还是我们需要模拟间谍电话的道具。如何做到这一点是我的问题。同样在这个问题得到解决之后,当我尝试处理类似于 fetchDeviceList 时,有一个保存函数返回到 redux this.props.saveDeviceDetails(firstClassifedDevice);,jasmine 超时错误。
    • 我的目的是测试高阶组件和演示组件,尽管这对我的旅程来说很痛苦。需要学习并确保测试是端到端的
    猜你喜欢
    • 2019-07-23
    • 2018-09-25
    • 2020-08-24
    • 1970-01-01
    • 2022-01-01
    • 1970-01-01
    • 2017-02-11
    • 2018-06-03
    • 1970-01-01
    相关资源
    最近更新 更多