I am trying to write a jest test using the newer @testing-library/react library. This newer testing library does not have shallow rendering, so I am trying to mock out the react sub-components my tested component uses as a workaround.
But I am running into a problem using jest.mock, I cant seem to properly mock the 'subComponent.jsx' file properly.
When I use jest.mock('subComponent.jsx', ...) inside my test.js file, it only mocks imports of subComponent.jsx inside the test.js file. When I import subComponent.jsx from inside component.jsx, the mock in test.js no longer applies.
So How do I get an import of subComponent.jsx from inside of component.jsx mocked, without having to butcher the component.jsx file internally?
BTW, I am also naturally open to any other solutions to effectively achieving shallow rendering for @testing-library/react if anyone has good suggestions...
test.js:
import Component from 'component.jsx';
jest.mock('subComponent.jsx', ...doSomething);
component.jsx:
import SubComponent from 'subComponent.jsx;
[SubComponent.jsx is not mocked here!!!!]
jest.mock()
(unlikejest.doMock
) is hoisted and should work as you expect. what jest version do you use? maybe a bug for some old version that has been fixed for newer version. – skyboyer^24.0.0
both24.0.1
and24.0.100
may be installed to you. Actual version can be check atpackage-lock.json
. – skyboyer