I'm trying to mock the react-dom module using Jest
import React from 'react';
import {configure, shallow } from 'enzyme';
import Adapter from 'enzyme-adapter-react-16';
import Link from '../components/DumbComp';
import { shallowToJson } from 'enzyme-to-json';
import { render } from 'react-dom';
configure({ adapter: new Adapter() });
jest.mock('react-dom');
describe('Link',() =>{
it('should render correctly', ()=>{
expect(render).toHaveBeenCalledWith(
<Link title="mockTitle" url="mockUrl" />, 'element-node'
);
expect(render).toHaveBeenCalledTimes(1);
});
});
When I run the test I get the following error:
Link › should render correctly
expect(jest.fn()).toHaveBeenCalledWith(expected)
Expected mock function to have been called with:
[<Link title="mockTitle" url="mockUrl" />, "element-node"]
But it was not called.
It seems that when I mock the render method it doesn't return anything. How can I correctly mock it?
I'm using this tutorial, see under the "The art of mocking" section.
If you want to create a manual mock create in the same file like this:
jest.mock('react-dom', () => ({
render: jest.fn(),
}));
I would recommend to have a look at snapshot and use it togheter with enyzme. It makes testing easier because you can write something like this:
describe ('Link',() =>{
it ('should render correctly', ()=> {
const component = mount(
<Link title="mockTitle" url="mockUrl" />
);
expect(component).toMatchSnapshot();
});
});
Which gives you a snapshot of how the component got rendered exactly. You can also use it with function you test and it will give you a snapshot of all the calls your function got called with and the arguments the function got called with.
You should create a mock file next to your node_modules in __mocks__/react-dom.js
// react-dom.js
export default {
render: jest.fn(),
};
The accepted answer might be a little out of date. To mock react-dom
without side-effects you need to only mock the function you need, which in this case is the render
function.
This can be done using Jest's requireActual
like so:
jest.mock('react-dom', () => ({
...jest.requireActual('react-dom'),
render: jest.fn(),
}))