Learning jest and enzyme to test react apps, bootstrapped with create-react-app.
Mocking add/removeEventListener crashes using unmount
after shallow
and gives warning using unmount
after mount
, see below. Anyone know what I'm doing wrong?
My test:
it('should add and remove resize event handler', () => {
const adder = jest
.spyOn(global, 'addEventListener')
.mockImplementation(() => {});
const remover = jest
.spyOn(global, 'removeEventListener')
.mockImplementation(() => {});
const wrapper = shallow(<App />);
// this seems to work
expect(adder).toHaveBeenCalled();
// causing issues
wrapper.unmount();
expect(remover).toHaveBeenCalled();
});
using unmount
after mount
:
console.error node_modules/fbjs/lib/warning.js:33
Warning: Can only update a mounted or mounting component. This usually means you called setState, replaceState, or forceUpdate on an unmounted component. This is a no-op.
Please check the code for the App component.
using unmount
after shallow
:
/home/nik/projects/learn/jest/node_modules/react-scripts/scripts/test.js:20
throw err;
^
Invariant Violation: ReactShallowRenderer render(): Invalid component element.
at invariant (/home/nik/projects/learn/jest/node_modules/fbjs/lib/invariant.js:42:15)
at ReactShallowRenderer.render (/home/nik/projects/learn/jest/node_modules/enzyme-adapter-react-16/node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:104:38)
at Updater.enqueueSetState (/home/nik/projects/learn/jest/node_modules/enzyme-adapter-react-16/node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:329:20)
at App.Object.<anonymous>.Component.setState (/home/nik/projects/learn/jest/node_modules/react/cjs/react.development.js:237:16)
at loadData.then.results (/home/nik/projects/learn/jest/src/App.js:15:12)
at <anonymous>
at process._tickCallback (internal/process/next_tick.js:188:7)
error An unexpected error occurred: "Command failed.
Exit code: 1
Command: sh
Arguments: -c react-scripts test --env=jsdom
Directory: /home/nik/projects/learn/jest
Output:
".
info If you think this is a bug, please open a bug report with the information provided in "/home/nik/projects/learn/jest/yarn-error.log".
info Visit https://yarnpkg.com/en/docs/cli/run for documentation about this command.
I wrapped the unmount in promise
return Promise.resolve().then(() => {
wrapper.unmount();
expect(remover).toHaveBeenCalled();
});
also missed a clue in the error, 'loadData' - wasn't mocking:
jest.spyOn(App.prototype, 'loadData')
.mockImplementation(() => {
return new Promise(resolve => resolve([topics, subTopics]))
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With