lundi 9 décembre 2019

Testing parent methods in stateless child component in Jest

I currently have a react component with an onChange method.

I want to test the onChange method like if someone were to type in, or paste things in. The problem is the handleChange is dependent on the parent components using it. What's the best way to test for the simulation? Do I need to reference the parent component's handleChange method and simulate that?

class TextBox extends Component {
  render() {
    const { value, type, handleChange } = this.props;
    return (
        <Form.Control
          type={type}
          value={value}
          onChange={handleChange}
        />
    );
  }
}

Current Test:

describe("When user types in textbox", () => {
    let textBox;
    let props;
    beforeEach(() => {
      props = {
        name: "Title",
        label: "Body",
        type: "text",
        value: "",
        handleChange: jest.fn(),
      };
      textBox = mount(<TextBox {...props} />);
    });
    textBox.find("input").simulate("change", { target: { value: "testing input" } });
    it("should replace current message", () => {
      expect(textBox.state().value).to.equal("testing input");
    });
  });

i get the error:

TypeError: Cannot read property 'find' of undefined

Aucun commentaire:

Enregistrer un commentaire