jest-mock-react-noop
Mock React components to noops with Jest.
⚛️🚧🐐
Remember shallow rendering from enzyme
?
Wish you could have it with @testing-library/react
?
Now you can!
Use jest.mock
to re-define react
as jest-mock-react-noop
, providing it with an argument indicating the component(s) under test.
jest-mock-react-noop
returns a monkeypatched version of React with a modified createElement
function.
When rendering, any component not under test will be replaced with one that returns a placeholder empty div
with a data-jest-mock-react-noop
attribute whose value is that component's name.
You can query for placeholder div
s using the following query functions
(similar to @testing-library
's query functions):
getByNoop
getAllByNoop
queryByNoop
queryAllByNoop
;;;; jest.mock"react",require"jest-mock-react-noop".default'App'; describe"App",;
You can match components by name with string:
require"jest-mock-react-noop".default'App'
Or with regular expression:
require"jest-mock-react-noop".default/App/
Or with a function returning a boolean
(which also gives you access to the component constructor):
require"jest-mock-react-noop".default // `name` is the component name/string // `type` is the function/constructor or tag name stringreturn .includesname
If you prefer to configure queries
manually and use the native render
instead of our renderWithNoop
,
you can import either noopQueries
(with type NoopQueries
) or noopQueriesWithDefaults
(with type and NoopQueriesWithDefaults
, which includes the defaults from @testing-library/react
).
;; describe"App",;
;; describe"App",;
Sometimes jest.mock
as above won't work, e.g., with ts-jest
you might get this error:
TypeError: require(...).default is not a function
If so, you can try this:
jest.mock"react",; React.createElement.mockImplementation // @ts-ignore require'jest-mock-react-noop'.default'App'.createElement;