Sometimes, we want to test React component methods with Jest.
In this article, we’ll look at how to test React component methods with Jest.
Test a React Component Function with Jest
We can mock functions that our component depend on so that we can do testing with it.
For instance, we can write:
import React, { Component } from 'react';
class Child extends Component {
constructor (props) {
super(props);
};
render() {
const { onSubmit, label} = this.props;
return(
<form onSubmit={onSubmit}>
<Button type='submit'>{label}</Button>
</form >
);
};
};
export default class App extends Component {
constructor (props) {
super(props);
this.label = “foo”;
};
onSubmit = (option) => {
console.log('submitted');
};
render () {
return(
<div className="container">
<Child label={this.label} onSubmit={this.onSubmit} />
</div>
);
};
};
We can then mock the onSubmit
function when we test the child by writing:
import React from 'react';
import { shallow } from 'enzyme';
import Child from '../Child';
const onSubmitSpy = jest.fn();
const onSubmit = onSubmitSpy;
const wrapper = shallow(<Child onSubmit={onSubmitSpy} />);
let container, containerButton;
describe("Child", () => {
beforeEach(() => {
container = wrapper.find("div");
containerButton = container.find(“Button”);
onSumbitSpy.mockClear();
});
describe("<Button> behavior", () => {
it("should call onSubmit", () => {
expect(onSubmitSpy).not.toHaveBeenCalled();
containerButton.simulate(‘click’);
expect(onSubmitSpy).toHaveBeenCalled();
});
});
});
We mount the component with the onSubmit
prop populated by the onSubmitSpy
, which is a mock function.
We tested by simulating a click event on the button of the Child
component.
Then we check if the mocked function is called with toHaveBeenCalled
.
Conclusion
We can mock functions that our component depend on so that we can do testing with it.