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:
__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";
declare module "*.scss";
in globals.d.ts
but nothing works.
Please help.
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"
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With