Article summary
The documentation on setting up UI tests with Jest and React Testing Library is more than sufficient to get you going. However, when it’s used in a combination of NextJS and Material UI (an open-source React component library that implements Google’s Material Design), there are a few gotchas worth mentioning.
TransformIgnorePatterns – NextJS gotcha
SyntaxError: Cannot use import statement outside a module
One of the most frequent and early errors you might encounter when running the tests with the JavaScript testing framework Jest is related to module imports. A quick search for the top error will yield results in adding some transformIgnorePatterns
. However, NextJS with its own nextJest()
config will override this field with its own default configs. Therefore, the ideal place to put the transform patterns is after the config has been created. Here is a config with the usual needs.
import type { Config } from "jest";
import nextJest from "next/jest";
const createJestConfig = nextJest({
dir: "./",
});
const config: Config = {
preset: "ts-jest",
clearMocks: true,
coverageProvider: "v8",
setupFilesAfterEnv: ["/jest.setup.ts"],
testEnvironment: "jest-environment-jsdom",
moduleNameMapper: {
"^@/mock-data/(.*)$": "/mock-data/$1",
"^@/(.*)$": "/src/$1",
"\\.(css|less|scss|sass)$": "identity-obj-proxy",
},
modulePathIgnorePatterns: [".spec.ts"],
transform: {
"\\.scss$": "jest-scss-transform",
"\\.(ts|tsx)?$": "ts-jest",
"\\.(js|jsx)?$": "babel-jest",
},
};
module.exports = async () => ({
...(await createJestConfig(config)()),
transformIgnorePatterns: ["node_modules\\/(?!(module-name-you-use)\\/)"],
});
MUI Theme issue
When creating test providers according to the React Testing Library docs, most providers work in Jest easily. However, the MUI theme in the theme provider can create multiple issues when it’s trying to compile. Here is a tip to mock out the theme when using ThemeProvider theme={{}}
. By passing in an empty object, MUI will fulfill all the default needs instead of trying to compile the project’s custom theme.
I hope these two tips will save you time and get you to Jest testing faster!