JEST Cannot find module 'typescript-cookie' - reactjs

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

Related

Jest to vitest migration error; equivalent of moduleNameMapper

I am trying to migrate from jest to vitest.
at some point I get this error :
Syntax Error: Invalid or unexpected token
It seems one of the packages we have in project has this line that causes the issue:
require("./lib/somefont.woff")
I checked jest and jest has this line which resolved the issue:
"moduleNameMapper": {
"\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
"\\.(css|less|scss|sass)$": "identity-obj-proxy"
},
I was wondering how I can resolve the issue in vitest?
is there an equivalent of moduleNameMapper in vitest?
Use import to import the font
import "./lib/somefont.woff"
Try setting alias config in vitest.config.js
import { defineConfig } from 'vite'
export default defineConfig({
test: {
globals: true,
environment: "jsdom",
alias: {
".*\\.(jpg|jpeg|png|gif|eot|otf|webp|svg|ttf|woff|woff2|mp4|webm|wav|mp3|m4a|aac|oga)$": "<rootDir>/__mocks__/fileMock.js",
},
},
});

Configuring Vite with styled-jsx

I want to be able to add classes through styled-jsx which can be nested and have tailwind directives(#apply screen etc.). Right now it's working on imported css files.
Here's my Vite config:
import { defineConfig } from "vite";
import react from "#vitejs/plugin-react";
// https://vitejs.dev/config/
export default defineConfig({
plugins: [
react({
babel: {
parserOpts: {
plugins: [
"styled-jsx/babel",
// {
// plugins: ["styled-jsx-plugin-postcss"],
// },
],
},
},
}),
],
});
As you see plugins: ["styled-jsx-plugin-postcss"] is commented, because it results in an error, but it's essential to use postcss settings.
If somebody interested, here's the postcss.config.cjs(for non Vite it's .js):
module.exports = {
plugins: {
'tailwindcss/nesting': 'postcss-nesting',
'postcss-preset-env': {
stage: 1
},
tailwindcss: {},
autoprefixer: {},
}
}
Is there a way to configure it in Vite.js ( in Next.js it's trivial, so if someone wants to suggest this idea, just don't, it's about Vite!)

React Testing library custom setup import test-utils: module not installed. Unable to resolve path

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

React: Jest configuration Issue with Path Aliases

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'
}
};

Cannot find module error while import using jest in next.js

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

Resources