【问题标题】:React-Jest Unit test an external module method that affects stateReact-Jest 单元测试影响状态的外部模块方法
【发布时间】:2020-01-22 11:11:47
【问题描述】:

我正在使用 Jest 开发一个 React 应用程序。

我想测试一个导入的模块组件方法(closemodal):

<Modal
  visible={this.state.showModal}
  closemodal={() => this.setState({ showModal: false })} // <= this one
  type="slideInDown"
>

我尝试在我的单元测试中窥探这样的 Modal closemodal 方法:

import Modal from "react-animated-modal";

let spyOnCloseModal;

beforeEach(() => {
  spyOnCloseModal = jest.spyOn(Modal, "closemodal");
  wrapper = shallow(<App />);
});

但是当 UT 运行时我得到这个错误: Cannot spy the closemodal property because it is not a function; undefined given instead

【问题讨论】:

    标签: reactjs unit-testing jestjs


    【解决方案1】:

    尝试传递一个模拟函数。

    test("checks closemodel", () => {
      const props = {
        closemodal: jest.fn()
      };
      const wrapper = shallow(<Modal {...props} />);
    
      // trigger your `closemodal` function here
    
      expect(props.closemodal).toHaveBeenCalledTimes(1);
    });
    

    【讨论】:

      猜你喜欢
      • 2019-04-01
      • 2020-01-21
      • 1970-01-01
      • 2019-11-20
      • 2022-01-06
      • 1970-01-01
      • 2021-03-12
      • 2019-07-20
      • 1970-01-01
      相关资源
      最近更新 更多