Personally I stumbled upon this problem when dealing with Next.js (configured as jsx: 'preserve'
). If this is a problem with jest working in a Next.js like environment you can configure your babel used by Jest in the same way:
Since next.js already includes the next/babel preset dependency you may as well use and have a setup more consistent with your next.js environment.
babel.config.js:
module.exports = {
presets: ['next/babel']
};
Alternatively, if anyone experienced this bug had the problem wherein import React from 'react'
is not necessary, because it is already included globally and doesn't need to be included in every file, then this solution may work for you. This may also just be helpful for you if you ever need to import or define global functions for jest.
I simply configured React to be globally defined in jest.
My jest.config.js
:
module.exports = {
moduleDirectories: ['./node_modules', 'src'],
// other important stuff
setupFilesAfterEnv: ['<rootDir>/src/jest-setup.ts']
}
My src/jest-setup.ts
(or make an equivalent jest-setup.js
):
import '@testing-library/jest-dom';
import React from 'react';
global.React = React; // this also works for other globally available libraries
Now I don't need to worry about each file importing React (even though eslint knows that's unnecessary with Next.js)