React Testing Library is a popular testing library for react applications. It fundamentally changed how react applications are tested by advocating for a "deep by default" rendering strategy and asserting and interacting with a component more inline with the way a human does.
While I generally agree with Kent C. Dodds that we shouldn't mock every component any more than we should mock every private function in a module, there are times in more complicated applications where rendering complicated child components is impractical and difficult to maintain.
This library compliments @testing-library/react
to make it easy to setup and mock components and assert that those components are holding the correct props.
- We assume that your project is already using @testing-library/react and either Jest or Vitest
- Install this library
npm install --save-dev @sourceallies/rtl-mock-component
-
First, import this library and the component you are mocking in your test:
import {setupMockComponent, getByMockComponent} from '@sourceallies/rtl-mock-component'; import MyChildComponent from './MyChildComponent';
-
Next, mock the module just like any other mock:
jest.mock('./MyChildComponent');
or
vi.mock('./MyChildComponent');
-
In a
beforeEach
method, callsetupMockComponent
and pass it the component you are mocking. This sets up the mock.beforeEach(() => { setupMockComponent(MyChildComponent); });
-
Now, when you call
render
with any ancestor component, the implementation will not be called and a stub element will be rendered in its place. -
If you want to assert the component is in the dom you can do it as so:
expect(getByMockComponent(MyChildComponent)).toBeInTheDocument();
-
getMockComponent
and the other query functions return aMockedComponentElement<T>
that extends fromHTMLElement
and adds aprops
property that can be asserted on. For example, to make sure that the component is currently rendered with the open prop set to true:expect(getByMockComponent(MyChildComponent).props.open).toBe(true);
Note: this way of testing ensures that the component is currently rendered with the provided value.
toHaveBeenCalledWith
would only test that was ever rendered with the expected value.
setupMockComponent
takes an options argument that can change the behavior of the mock.
To change the element used from a div, pass the element name. This is useful when the mock is used in a place where only certain elements are valid (ex. a child of a tbody
must be a tr
)