I have set up a React custom boilerplate and it uses Webpack 5, TypeScript and other libs. I am trying to set up Jest but I am getting an error when the test runs that Cannot find module 'utils/constants' from 'src/App.tsx.
It is because of Path Aliases, I guess but I am not sure how to fix this. Can anyone please help me here? Thanks
I am using tsconfig-paths-webpack-plugin for Path Aliases.
webpack.config.js
module.exports = {
entry: path.resolve(__dirname, '..', './src/index.tsx'),
resolve: {
plugins: [new TsconfigPathsPlugin()],
.......
}
.......
}
tsconfig.json
{
"compilerOptions": {
.........
"baseUrl": "./src",
"paths": {
"components/*": ["./components/*"],
"styles/*": ["./styles/*"],
"utils/*": ["./utils/*"]
}
}
.........
}
jest.config.js
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy'
}
};
App.tsx
import { APP_NAME } from 'utils/constants';
export const App = () => (
<h1> {APP_NAME} </h1>
);
App.test.tsx
import { screen, render } from '#testing-library/react';
import { App } from './App';
describe('App Component', () => {
it('should have React Project text', () => {
render(<App />);
expect(screen.getByText('React Project')).toBeTruthy();
});
});
Error
FAIL src/App.test.tsx
Test suite failed to run
Cannot find module 'utils/constants' from 'src/App.tsx'
Require stack:
src/App.tsx
src/App.test.tsx
However, Jest was able to find: 'utils/constants.ts'
You might want to include a file extension in your import, or update your 'moduleFileExtensions', which is currently ['js', 'jsx', 'ts', 'tsx', 'json', 'node'].
I added the following configs in jest.config.js and it worked:
/** #type {import('ts-jest/dist/types').InitialOptionsTsJest} */
module.exports = {
preset: 'ts-jest',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['#testing-library/jest-dom/extend-expect'],
moduleNameMapper: {
'\\.(css|less|scss|sss|styl)$': '<rootDir>/node_modules/identity-obj-proxy',
'^components(.*)$': '<rootDir>/src/components$1',
'^styles(.*)$': '<rootDir>/src/styles$1',
'^utils(.*)$': '<rootDir>/src/utils$1'
}
};
Related
Im doing some testing with react testing library to test swiper module in my app but got
export { default as Swiper, default } from './core/core.js';
SyntaxError: Unexpected token 'export'
I tried to apply transformers and add transformIgnorePatterns and none helped me
My jest.config.js
const nextJest = require("next/jest");
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: "./",
});
/** #type {import('jest').Config} */
const customJestConfig = {
verbose: true,
setupFilesAfterEnv: ["<rootDir>/jest.setup.js"],
moduleNameMapper: {
"^components/(.*)$": "<rootDir>/src/components/$1",
"^data/(.*)$": "<rootDir>/src/data/$1",
"^types/(.*)$": "<rootDir>/src/types/$1",
"^theme/(.*)$": "<rootDir>/src/theme/$1",
"^slices/(.*)$": "<rootDir>/src/slices/$1",
"^store/(.*)$": "<rootDir>/src/store/$1",
"^utils/(.*)$": "<rootDir>/src/utils/$1",
"^contexts/(.*)$": "<rootDir>/src/contexts/$1",
"^theme/(.*)$": "<rootDir>/src/theme/$1",
"^helpers/(.*)$": "<rootDir>/src/helpers/$1",
"^pages/(.*)$": "<rootDir>/src/pages/$1",
"^graphql/(.*)$": "<rootDir>/src/graphql/$1",
"^uuid$": require.resolve("uuid"),
"^swiper$": require.resolve("swiper"),
},
testEnvironment: "jest-environment-jsdom",
transform: {
"(js|jsx|ts|tsx)$": ["babel-jest", { presets: ["next/babel"] }],
},
moduleFileExtensions: ["ts", "tsx", "js", "json", "jsx"],
transformIgnorePatterns: ["node_modules/(?!(swiper))"],
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
I'm trying to run some tests in a project that was created using VITE + TS, and I'm getting the following error:
The module typescript-cookie is the only one it's not being found. If remove this module all tests work fine!
My jest.config.ts
module.exports = {
testEnvironment: 'jest-environment-jsdom',
collectCoverageFrom: ['<rootDir>/src/**/*.{ts,tsx}'],
coverageDirectory: 'coverage',
setupFilesAfterEnv: ['<rootDir>/src/config/jest-setup.ts'],
transformIgnorePatterns: ['/node_modules/(?!#element)/'],
transform: {
'^.+\\.[jt]sx?$': 'babel-jest',
},
moduleNameMapper: {
'#hooks': ['<rootDir>/src/commons/hooks'],
'#contexts': ['<rootDir>/src/commons/contexts'],
'#commons': ['<rootDir>/src/commons'],
'#mock': ['<rootDir>/src/commons/mock'],
'#common/components': ['<rootDir>/src/commons/components'],
'#enum': ['<rootDir>/src/commons/enum/'],
'#interfaces': ['<rootDir>/src/commons/interfaces/'],
'#utils': ['<rootDir>/src/commons/utils/'],
'#mainRoutes': ['<rootDir>/src/router'],
'#services': ['<rootDir>/src/commons/services'],
},
};
vite.config.ts
import react from '#vitejs/plugin-react';
import { defineConfig } from 'vite';
// https://vitejs.dev/config/
export default defineConfig({
plugins: [react()],
resolve: {
alias: {
'#hooks': '/src/commons/hooks',
'#enum': '/src/commons/enum',
'#mock': '/src/commons/mock',
'#common/components': '/src/commons/components',
'#services': '/src/commons/services',
'#common': '/src/commons',
'#contexts': '/src/commons/contexts',
'#interfaces': '/src/commons/interfaces',
'#utils': '/src/commons/utils',
'#mainRoutes': '/src/router',
},
},
});
```
I've been experiencing the same error in a project that was created with Create React App. Assuming it's an issue with the library, I filed a bug report.
https://github.com/carhartl/typescript-cookie/issues/110
I am facing an issue with setting up tests for react app with Jest.
I am using workerize-loader! library to import modules into webworkers.
On tests that use the import worker from workerize-loader!./path/to/file are barking on import of the test. I tried with a custom loader, in the jest.condig.js file but that did not work. When I run the default testing script provided by the react app setup it cannot find the imports in the files. But the code when it runs works alright.
I need help with importing the modules inside of the test suite of jest
Basic test
import React from "react";
import {cleanup, fireEvent, render } from "#testing-library/react";
import App from "./App";);
afterEach(cleanup);
test("basic test", () => {
const { container } = render(<App />);
const linkElement = container.firstChild;
expect(linkElement).toBeInTheDocument();
});
Configuration
jest.config.js
module.exports = {
preset: 'ts-jest',
verbose: true,
testEnvironmentOptions: {
url: 'http://localhost/'
},
testEnvironment: 'jsdom',
transform: {
'workerize-loader(\\?.*)?!(.*)': '<rootDir>/workerize-jest.js',
'^.+\\.(js|jsx)$': 'babel-jest',
'^.+\\.(ts|tsx)?$': 'ts-jest',
},
unmockedModulePathPatterns: [
'node_modules',
],
moduleNameMapper: {
'workerize-loader(\\?.*)?!(.*)': 'identity-obj-proxy'
},
};
.babelrc
{
"plugins": [
"syntax-dynamic-import",
"#babel/transform-runtime"
],
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
],
"env": {
"start": {
"presets": [
"react-hmre"
]
},
"test": {
"presets": [
[
"es2015",
{
"modules": true
}
],
"react",
"stage-0"
]
}
}
}
Error message on react-scripts test
Cannot find module 'workerize-loader!./workers/css.worker'
In file
> 2 | import worker from 'workerize-loader!./workers/css.worker';
workerize-jest.js
module.exports = {
process(src, filename) {
return `
async function asyncify() { return this.apply(null, arguments); }
module.exports = function() {
const w = require(${JSON.stringify(filename.replace(/^.+!/, ''))});
const m = {};
for (let i in w) m[i] = asyncify.bind(w[i]);
return m;
};
`;
}
};
I'm trying to configure jest absolute path for my custom test-utils directory (https://testing-library.com/docs/react-testing-library/setup#configuring-jest-with-test-utils), but I get the error Cannot find module 'test-utils' / unable to resolve path
My folder tree
-src/
--utils/
---test-utils/
----test-utils.js
----custom-queries.js
-jest.config.js
-jsconfig.json
My jest.config.js
module.exports = {
transform: {
'^.+\\.jsx?$': 'babel-jest',
},
testEnvironment: 'jsdom',
moduleNameMapper: {
'\\.(css|less)$': 'identity-obj-proxy',
},
moduleDirectories: [
'node_modules',
'src',
'utils',
'test-utils',
],
};
My jsconfig.json
{
"compilerOptions": {
"baseUrl": "src",
"paths": {
"test-utils": ["./utils/test-utils"]
}
},
"include": ["src"],
"exclude": ["node_modules"]
}
My component test
import { render } from 'test-utils';
import React from 'react';
import '#testing-library/jest-dom/extend-expect';
import Alert from './alert';
describe('Alert', () => {
test('Renders Alert component', () => {
const { getByRole } = render(<Alert message="Success!" />);
const alert = getByRole(/alert/);
expect(alert).toHaveTextContent('Success!');
});
});
The test-utils is your custom module for which you specify path alias and how to resolve it in jsconfig.json as follows:
"compilerOptions":{
"baseUrl":"src",
"paths":{
"test-utils": ["./utils/test-utils"]
}
}
The same way you need to tell to Jest how to resolve it with moduleNameMapper option in your jest.config.js as follows:
moduleNameMapper: {
'test-utils/(.*)": "<rootDir>/src/utils/test-utils/$1',
},
For official documentation see: https://jestjs.io/docs/configuration#modulenamemapper-objectstring-string--arraystring
For similar issues see: Jest not finding alias path, React: Jest configuration Issue with Path Aliases and How to use path alias in a react project with Typescript + Jest
I am trying to configure Jest in my Next.js project. In my test file, I have imported my component like import { HamburgerMenu } from './HamburgerMenu.jsx'. In that component, there are so many other imports. Once of them is
import {
checkValidEmail, getNumbers, getFormttedPhoneNo, validateSubscription,
} from 'helpers/utils';
When I run tests, it gives me the following error (which is on above import statement):
Cannot find module 'helpers/utils' from 'components/common/Smart/HamburgerMenu/HamburgerMenu.jsx'
So here are the details.
jest.config.js (at root dir)
module.exports = {
collectCoverageFrom: [
'**/*.{js,jsx,ts,tsx}',
'!**/*.d.ts',
'!**/node_modules/**',
],
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testPathIgnorePatterns: ['/node_modules/', '/.next/'],
transform: {
'^.+\\.(js|jsx|ts|tsx)$': '<rootDir>/node_modules/babel-jest'
},
transformIgnorePatterns: [
'/node_modules/',
'^.+\\.module\\.(css|sass|scss)$',
],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': 'identity-obj-proxy',
},
}
I have added jest: true in the ESLint file.
babel.config.js file (at root dir):
module.exports = {
presets: ["next/babel"],
plugins: [["babel-plugin-styled-components", { ssr: true }]]
};
You can try to add
...
moduleDirectories: ['node_modules', '.'],
...
to your jest.config.js