Emotion with Jest: Cannot find module 'react'

Viewed 466

I just set up @emotion/react with create-react-app. The UI works fine, but when running jest, I'm getting this error:

Cannot find module 'react' from '../node_modules/@emotion/react/dist/emotion-react.cjs.dev.js'

I've tried:

  • Make sure react package is in package.json
  • Delete node-modules and re-run yarn
  • Update file directive to /** @jsxImportSource @emotion/react */
  • Install @testing-library/react
  • Install react-test-renderer
  • Install @emotion/jest

No luck. Any idea why this might be happening?

Just importing from Emotion throws this error, but only with the JSX directive and import statements together. Just one or the other does not throw the error. Changing { jsx } to { css } also causes the issue not to reproduce.

/** @jsx jsx */
import { jsx } from "@emotion/react";
1 Answers

It turned out the dependencies were in the wrong project - we have a server project and a child project which is the React app. I had some Emotion dependencies in the top-level project which made the app work correctly but Jest fail for some reason.

Moving all Emotion dependencies to the correct location - the Create React App project - fixed the issue.

Related