React mockElement
Mock element for capturing props in tests. Provides a middle-ground
towards enzyme's shallow
unit tests when using
react-testing-library
(but can be used with any testing library which renders to a DOM).
The intended use is to mock out specific children of a component under test which have important properties or are otherwise difficult to mock. This should not be used to mock every child component.
Install dependency
npm install --save-dev react-mock-element
Usage with react-testing-library + Jest
// code under test (MyComponent.jsx) ; { return <div> foobar <Child p1="a" /> </div> ;}; // test (MyComponent.test.jsx) ;;;; ; ;
This is also compatible with Jest module mocking:
// code under test (MyComponent.jsx) ;; { return <div> foobar <ChildComponent p1="a" /> </div> ;}; // test (MyComponent.test.jsx) ;;;; jest; ; ;
API
mockElement(tagName)
: returns a React component which renders a tag
with the given tag name (a naming convention such as mock-something
is recommended but not required). Note that as this function name
begins with mock
, it can be used by hoisted jest.mock
calls in
tests (see second demo above).
element.mockProps
: added to the HTMLElement
prototype. This
provides access to the props passed to an element. This is read-only.