23
votes

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?

1
Slightly opinionated but I'm just thinking ahead for you. Your going to be getting many of these types of errors using jest, additionally your going to be running into performance problems when you begin to test anything non-trivial. Take a look at some open issues of jest and evaluate if using mocha or jasmine would be a better choice for testing framework.enjoylife
Otherwise take a look at this question for more guidance.enjoylife
@mattclemens Interesting. I've only really read about testing react components with jest, so that was the default. I will read up a bit... The question you linked to is more around having subcomponents passed to the component you are trying to test, rather than them being imported it seems.Jim
Oops, my bad for leading you an irrelevant question, I guess I picked up on that one in particular for the sub component aspect.enjoylife
What else are you using to run the tests besides Jest? Are you using a transpiler e.g. Babel? And (how) is the sass stuff referenced from the JS?Matt Holland

1 Answers

4
votes

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