简体   繁体   中英

Testing With Jest and Enzyme. Spy On a method of a react component

I have a simple react component.

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;

I want to test if i change something in the input field the handleChange method is called.

This is what i have tried:

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

The problem is when i simulate the change it is actually entering in the original handleChange method. The error that i get:

TypeError: this.otherTask is not a function

How can i achieve this simple test? Maybe i have to simulate the change of the instance's input field rather than the wrappers but don't have a clue of how to do it.

I solved it after adding some little changes to my test code :)

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

so i had to add an empty mockImplementation and use

wrapper.instance().forceUpdate();

to make it work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM