0
votes

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!!!!]
1
jest.mock()(unlike jest.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
@skyboyer "jest": "^24.0.0","@testing-library/jest-dom": "^4.1.0","@testing-library/react": "^9.1.3" I upgraded to 24.9.0 jest now, isnt making a differenceuser2765977
it's not actual versions. see, for range ^24.0.0 both 24.0.1 and 24.0.100 may be installed to you. Actual version can be check at package-lock.json.skyboyer
I also know hoisting isnt making a difference tried re-ordering it and using a require on component.jsx after the mock, but did not make a differenceuser2765977
@skyboyer checked lock file, after upgrade it is on exactly: 24.9.0 And isnt making a differenceuser2765977

1 Answers

0
votes

Sorry, turns out this was a casing typo on my side as pointed out by @skyboyer Many thanks.