Testing event handlers

Consider the following React component, used to render an email. Assuming that this file is saved in the EmailInput.js file, let's test it, as follows:

import React, { Component } from "react";
class EmailInput extends Component {
constructor(props) {
super(props);
this.state = {
value: ""
};
this.handleEmailChange = this.handleEmailChange.bind(this);
}
handleEmailChange(event) {
this.setState({ value: event.target.value });
}
render() {
return (
<div>
<label>Enter Your Email</label>
<input
type="email"
onChange={this.handleEmailChange}
value={this.state.value}
name="email"
/>
</div>
);
}
}
export default EmailInput;

Our test file should be located inside of __tests__/EmailInput-test.js:

import React from "react";
import renderer from "react-test-renderer";
import EmailInput from "../EmailInput";
it("should render correctly", () => {
const component = renderer.create(<EmailInput />);
expect(component.toJSON()).toMatchSnapshot();
const instance = component.getInstance();
expect(instance.state).toMatchSnapshot("initial state");
instance.handleEmailChange({ target: { value: "[email protected]" } });
expect(instance.state).toMatchSnapshot("updated state");
});

In the preceding test script, we created the component using the renderer function, and renderer.create returns an object that has getInstance and update methods. We can get the instance of the component by using the function, and we can access the children props and go deeper into the DOM tree model.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset