【问题标题】:Testing With Jest and Enzyme. Spy On a method of a react component用 Jest 和 Enzyme 进行测试。窥探一个反应组件的方法
【发布时间】:2019-09-16 05:44:55
【问题描述】:

我有一个简单的反应组件。

import React, { Component } from "react";

class SampleText extends Component {
  handleChange = e => {
    console.log(" perform other task");
    this.otherTask();
  };

  render() {
    return <input type="text" onChange={this.handleChange} id="text1" />;
  }
}

export default SampleText;

我想测试我是否更改了输入字段中的某些内容,调用了 handleChange 方法。

这是我尝试过的:

import React from "react";
import SampleText from "./SampleText";

import Adapter from "enzyme-adapter-react-16";
import { shallow, configure } from "enzyme";

configure({ adapter: new Adapter() });

test("input change handle function", () => {
  const wrapper = shallow(<SampleText />);
  const instance = wrapper.instance();

  jest.spyOn(instance, "handleChange");

  //simulate instance's onChange event here
  wrapper.find('input[id="text1"]').simulate("change", {
    target: { value: "some random text" }
  });

  expect(instance.handleChange).toHaveBeenCalled();
});

问题是当我模拟更改时,它实际上是在原始的 handleChange 方法中输入的。我得到的错误:

TypeError: this.otherTask 不是函数

我怎样才能完成这个简单的测试?也许我必须模拟实例输入字段的变化而不是包装器,但不知道如何去做。

【问题讨论】:

    标签: javascript reactjs testing jestjs enzyme


    【解决方案1】:

    在对我的测试代码添加一些小改动后,我解决了这个问题:)

    test("input change handle function", () => {
      const wrapper = shallow(<SampleText />);
      const instance = wrapper.instance();
    
      //here is the change.
      const spy = jest.spyOn(instance, "handleChange").mockImplementation(() => {});
    
      wrapper.instance().forceUpdate();
    
      //simulate instance's onChange event here
      wrapper.find('input[id="text1"]').simulate("change", {
        target: { value: "some random text" }
      });
    
      expect(spy).toHaveBeenCalled();
    });
    

    所以我不得不添加一个空的 mockImplementation 并使用

    wrapper.instance().forceUpdate();

    让它工作。

    【讨论】:

      猜你喜欢
      • 2018-08-30
      • 2020-02-24
      • 2023-03-27
      • 2020-08-27
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-02-12
      • 2019-05-15
      相关资源
      最近更新 更多