I have been facing a challenge while setting up jest and @testing-library/jest-dom for my typescript/react/next.js website.
Each time I try running the tests, an error occurs, and I am struggling to identify the root cause. This issue has been perplexing me for the past 3 days, and I suspect it might be related to a configuration problem.
I have recreated the entire project
I have uninstalled and reinstalled packages
I have experimented with different config settings
No luck so far
Error:
FAIL __tests__/dist/button.test.js
● Test suite failed to run
TypeError: $toString is not a function
> 1 | import '@testing-library/jest-dom'
| ^
at isArguments (node_modules/is-arguments/index.js:12:9)
at node_modules/is-arguments/index.js:28:9
at Object.<anonymous> (node_modules/is-arguments/index.js:29:2)
at Object.<anonymous> (node_modules/deep-equal/index.js:10:19)
at Object.<anonymous> (node_modules/aria-query/lib/elementRoleMap.js:7:41)
at Object.<anonymous> (node_modules/aria-query/lib/index.js:10:46)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/to-be-checked.js:8:18)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/matchers.js:203:20)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/extend-expect.js:3:42)
at Object.<anonymous> (node_modules/@testing-library/jest-dom/dist/index.js:3:1)
at Object.<anonymous> (jest-setup.ts:1:1)
tsconfig.json
{
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"baseUrl": ".",
"noFallthroughCasesInSwitch": true,
"outDir": "./dist",
"paths": {
"@/*": ["./*"]
},
},
"compileOnSave": true,
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", "babel.config.js", "jest-setup.ts", "jest.config.ts"],
"exclude": ["node_modules"]
}
jest.config.ts
import type { Config } from "@jest/types";
const config: Config.InitialOptions = {
preset: "ts-jest",
testEnvironment: "node",
extensionsToTreatAsEsm: ['.ts'],
verbose: true,
automock: true,
transformIgnorePatterns: ['node_modules/', '^.+\\.module\\.(css|sass|scss)$'],
moduleFileExtensions: ["js", "jsx", "ts", "tsx"],
moduleDirectories: ["node_modules", "src"],
moduleNameMapper: {
"\\.(css|less|scss)$": "identity-obj-proxy"
},
transform: {
'^.+\\.(ts|tsx)?$': 'ts-jest',
'^.+\\.(js|jsx)$': 'babel-jest',
},
setupFilesAfterEnv: ['<rootDir>/jest-setup.ts'],
}
export default config;
jest-setup.ts
--> import '@testing-library/jest-dom'
babel.config.js
module.exports = {
presets: [['@babel/preset-env', {targets: {node: 'current'}}]],
};