rtl-mock-component 1.0.0
Install from the command line:
Learn more about npm packages
$ npm install @sourceallies/rtl-mock-component@1.0.0
Install via package.json:
"@sourceallies/rtl-mock-component": "1.0.0"
About this version
React Testing Library is a popular testing library for react applications. It fundamentally changed how react applicatios 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 difficualt 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 [Jest] and [@testing-library/react]
- 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, getMockComponent} from '@sourceallies/rtl-mock-component'; import MyChildComponent from './MyChildComponent';
-
Next, mock the module just like any other mock:
jest.mock('./MyChildComponent');
-
In a
beforeEachmethod, callsetupMockComponentand pass it the component you are mocking. This sets up the jest mock.beforeEach(() => { setupMockComponent(MyChildComponent); });
-
Now, when you call
renderwith 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(getMockComponent(MyChildComponent)).toBeInTheDocument();
-
getMockComponentand the other query functions return aMockedComponentElement<T>that extends fromHTMLElementand adds apropsproperty that can be asserted on. For example, to make sure that the compnent is currently rendered with the open prop set to true:expect(getMockComponent(MyChildComponent).props.open).toBe(true);
Note: this way of testing ensures that the component is currently rendered with the provided value. Jest's
toHaveBeenCalledWithwould only test that was ever rendered with the expected value.
Details
- rtl-mock-component
-
sourceallies
- almost 4 years ago
- MIT
- 13 dependencies
Assets
- rtl-mock-component-1.0.0-npm.tgz
Download activity
- Total downloads 0
- Last 30 days 0
- Last week 0
- Today 0