Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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:

  • using __mocks__/styleMock.js
  • jest.mock("./User.module.scss")
  • jest-transform-css
  • jest-css-modules-transform
  • jest-css-modules
  • import * as styles from "./User.module.scss";
  • added declare module "*.scss"; in globals.d.ts

but nothing works.
Please help.

like image 651
Ol_D Avatar asked Nov 15 '22 12:11

Ol_D


1 Answers

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"
}
like image 170
Mehdi Dehghani Avatar answered Dec 27 '22 08:12

Mehdi Dehghani