Ol_D
Ol_D

Reputation: 313

Jest Cannot find SCSS module

Here's my code (just a very basic setup). All the files are in the same folder.
I am using create-react-app.

User.tsx:

import React from "react";
import styles from "./User.module.scss";

const User: React.FC = () => {
  return <div className={styles.user}>User</div>;
};

export default User;

User.module.scss:

@import "scss/abstracts";

.user {
  color: $dark_theme_color;
}

User.test.tsx:

import React from "react";
import { render, getByText } from "@testing-library/react";
import User from "./User";

it("renders correctly", () => {
  const { asFragment } = render(<User />);
  const fragmentElement = asFragment().firstChild as HTMLElement;
  const root = getByText(fragmentElement, "User");

  expect(root).not.toBe(null);
  expect(root).toMatchSnapshot();
});

When running jest I get this error:

FAIL  src/pages/User/User.test.tsx
   ● Test suite failed to run

src/pages/User/User.tsx:2:20 - error TS2307: Cannot find module './User.module.scss'.

2 import styles from "./User.module.scss";

jest.config.js:

module.exports = {
  roots: ["<rootDir>/src"],
  transform: {
    "^.+\\.tsx?$": "ts-jest"
  },
  setupFilesAfterEnv: [
    "@testing-library/react/cleanup-after-each",
    "@testing-library/jest-dom/extend-expect"
  ],
  testRegex: "(/__tests__/.*|(\\.|/)(test|spec))\\.tsx?$",
  moduleFileExtensions: ["ts", "tsx", "js", "jsx", "json", "node"],
  moduleNameMapper: {
    "^.+\\.module\\.(css|sass|scss)$": "identity-obj-proxy"
  }
};

I have tried almost all solutions from the first 2 pages of google search results, like:

but nothing works.
Please help.

Upvotes: 10

Views: 3219

Answers (2)

Roma N
Roma N

Reputation: 321

I faced same problem and answer from @Mehdi don't work and "globals" deprecated.

But work it:

npm install node-sass --save-dev

Upvotes: 0

Mehdi Dehghani
Mehdi Dehghani

Reputation: 11601

I faced same problem and I could fix it by setting diagnostics to false

"globals": {
    "ts-jest": {
        "diagnostics": false
    }
}

By the way I used babel-jest for moduleNameMapper

"moduleNameMapper": {
    "^.+\\.(css|less|scss)$": "babel-jest"
}

Upvotes: 2

Related Questions