Spy on React components in Jest
npm install --save-dev spy-on-render
Put this in your setupTests.js
:
import { Matchers } from 'spy-on-render';
expect.extends(Matchers)
Just call it:
import { spyOnRender } from 'spy-on-render';
spyOnRender(Component);
The component will render null
and you can track how many times it has been rendered and with which props.
For functional components, use jest.mock
jest.mock('path/to/component', () => require('spy-on-render').createComponentSpy());
You can also pass a render function if you want to render something specific
// render children
jest.mock('path/to/component', () => require('spy-on-render').createComponentSpy((props) => <div>{props.children}</div>));
// render testId for use with react-testing-library
jest.mock('path/to/component', () => require('spy-on-render').createComponentSpy(() => <div data-testid="my-component"/>));
was the component rendered?
expect(Component).toHaveBeenRendered();
with specific properties?
expect(Component).toHaveBeenRenderedWithProps({
className: 'whatever',
otherProp: 'whocares'
});
what props were rendered last?
getPropsOnLastRender(Component)
what props were rendered at some other point in time?
getPropsOnRenderAt(Component, i)
all props in render order
getPropsByRender(Component)