I have a react component (CreateForm). The React component depends on a module (Store). The CreateForm has a Cancel button. On clicking the cancel button, the handleCancel function of the Store module should be called.
I wrote a test unsuccessfully using Jest:
test.only('should handle cancel button click', () => {
jest.mock('../../src/store');
const store = require('../../src/store');
const wrapper = shallow(<CreateForm />);
const cancelButton = wrapper.find('button').at(1);
cancelButton.simulate('click');
expect(store.default.handleCancel).toBeCalled();
});
The test failed. The mock function did not get called and the test failed. Does the react component not get this version of the mock? If so, how do I fix the test? Thanks.
My CreateForm component looks something like the below:
import Store from './store';
render() {
return (
<Panel>
<FormControls />
<button onClick={Store.create}>Create</button>
<button onClick={Store.handleCancel}>Cancel</button>
</Panel>
);
}
A second improvised test that works for me is shown below.
test.only('should handle cancel button click', () => {
const store = require('../../src/store').default;
const cancel = store.handleCancel;
store.handleCancel = jest.fn();
const wrapper = shallow(<CreateForm />);
const cancelButton = wrapper.find('button').at(1);
cancelButton.simulate('click');
expect(store.handleCancel).toBeCalled();
store.handleCancel = cancel;
});
The above test works. I am manually mocking the function, doing the test and restoring the function back to its original after the test. Is there a better way or Jest way of writing the above test? Thanks.