'React Material UI issue with syled-engine resolution while running tests (Works while serve/building)

I'm using mui.com Material UI components with styled-components instead of emotion which is the default one.

I have updated my tsconfig.json to include

"compilerOptions": {
    ...,
    "paths": {
      ...,
      "@mui/styled-engine": ["./node_modules/@mui/styled-engine-sc"]
    }

Now while I use webpack-dev-server or webpack build it gets resolved correctly

But while I run the tests I get the following error

  ● Test suite failed to run

    Cannot find module '@emotion/styled' from '../../node_modules/@mui/styled-engine/node/index.js'

    Require stack:
      C:/LearningProjects/tech-events-uk/node_modules/@mui/styled-engine/node/index.js
      C:/LearningProjects/tech-events-uk/node_modules/@mui/system/index.js
      C:/LearningProjects/tech-events-uk/node_modules/@mui/material/node/styles/adaptV4Theme.js
      C:/LearningProjects/tech-events-uk/node_modules/@mui/material/node/styles/index.js
      C:/LearningProjects/tech-events-uk/node_modules/@mui/material/node/index.js
      src/lib/event-card/event-card.tsx
      src/lib/event-card/event-card.spec.tsx

      at Resolver.resolveModule (../../node_modules/jest-runtime/node_modules/jest-resolve/build/resolver.js:324:11)
      at Object.<anonymous> (../../node_modules/@mui/styled-engine/node/index.js:45:38)

I think possibly some jest config is missing and not much familiar with jest configurations to be used with npm and not yarn

Reference: https://mui.com/guides/styled-engine/



Solution 1:[1]

Adding this to my jest.config.js did the trick:

module.exports = {
    moduleNameMapper: {
        '^@mui/styled-engine$': '<rootDir>/node_modules/@mui/styled-engine-sc',
    },
};

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Edwin Vargas