dimanche 15 septembre 2019

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.

Aucun commentaire:

Enregistrer un commentaire