I am using Jest v29.7.0 as well as babel-jest v29.7.0.
This is my jest.config.js file
module.exports = {
transform: {
'\.[jt]sx?$': 'babel-jest'
},
rootDir: './',
verbose: true,
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleDirectories: ['node_modules', '<rootDir>/public/js'],
moduleFileExtensions: ['js', 'jsx', 'ts', 'tsx', 'json', 'node'],
moduleNameMapper: {
'^components/(.*)$': '<rootDir>/public/js/components/$1',
},
extensionsToTreatAsEsm: ['.jsx'],
transformIgnorePatterns: ['/node_modules/'],
testEnvironment: 'jsdom',
collectCoverage: true,
coverageDirectory: '<rootDir>/test/output/coverage',
coverageReporters: ['html', 'text-summary'],
testTimeout: 10000,
roots: ['./public/js/components', './test/spec'],
collectCoverageFrom: ['./public/js/**/*.{js,jsx}']
};
When trying to run one particular test: npm run test-jest -- test/spec/components/UserProfile/Account/Payments.spec.js
Error from Jest
Test suite failed to run
Configuration error:
Could not locate module components/UserProfile/Account/Payments mapped as:
/Users/XXXXXXX/repo/public/js/components/$1.
Please check your configuration for these entries:
{
"moduleNameMapper": {
"/^components/(.*)$/": "/Users/XXXXXXX/repo/public/js/components/$1"
},
"resolver": undefined
}
2 | import { render, screen, fireEvent } from '@testing-library/react';
3 | import '@testing-library/jest-dom';
> 4 | import Payments from 'components/UserProfile/Account/Payments';
| ^
5 |
6 | // Mock implementations
7 | const mockGetState = jest.fn();
at createNoMappedModuleFoundError (node_modules/jest-resolve/build/resolver.js:759:17)
at Object.require (test/spec/components/UserProfile/Account/Payments.spec.js:4:1)
at runMicrotasks (<anonymous>)
In my project I don’t use extensions when importing, for example I use import Payments from 'components/UserProfile/Account/Payments';
without having to use .jsx
and my Webpack config understands this.
But I am new to Jest and don’t know how to get it to understand the imports without extensions when using them in tests.
My Simple failing test
import React from 'react';
import { render, screen, fireEvent } from '@testing-library/react';
import '@testing-library/jest-dom';
import Payments from 'components/UserProfile/Account/Payments';
describe('Payments Component', () => {
beforeEach(() => {
jest.clearAllMocks();
});
it('renders without crashing', () => {
render(<Payments />);
});
});
babel.config.js
module.exports = {
presets: ['@babel/preset-env', '@babel/preset-react']
};
jest.setup.js
import '@testing-library/jest-dom';
What am I missing?