How to mock out sub-components when unit testing a React component with Jest
I have a React component that I am trying to write some tests around. I have broken it down to the simplest test possible.
jest.dontMock('../Overlay.react.js');
import React from 'react';
import ReactDOM from 'react-dom';
var Overlay = require('../Overlay.react.js'); // this is the culprit!
describe('Overlay', () => {
it('should work', () => {
expect(true).toEqual(true);
});
});
When requiring the component I am trying to test, it seems to not be mocking its subcomponents. At the top of Overlay.react.js
, I have the following import: import LoadingSpinner from 'loadingIndicator/LoadingIndicatorSpin.react';
When running my test, I get the following error:
- SyntaxError: /Users/dev/work/react-prototype/src/components/root/routes/components/subset1/components/Overlay.react.js:
/Users/dev/work/react-prototype/src/components/root/routes/components/loadingIndicator/LoadingIndicatorSpin.react.js:
/Users/dev/work/react-prototype/src/components/root/routes/components/loadingIndicator/sass/style.sass:
Unexpected token ILLEGAL
It seems like instead of mocking the components, it is going right down to the sub-component’s sass file and throwing a fit. My understanding was that Jest mocks everything except for what you tell it to not mock.
What is the right way to formulate these tests so that sub-components do not cause jest to explode when being imported during a test?
If you would require your SASS and LESS and CSS files in the main component instead of in each sub component you would not get this problem as you test the components on their own.
There are some other solutions mentioned in this issue report if you don’t like the one I provided. Issue 334