-
Notifications
You must be signed in to change notification settings - Fork 27.5k
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Nextjs with jest example will not work if there is an esm dependency in node_modules #40183
Comments
I ran into this issue once I installed preact in to my project. |
Same issue for me. module.exports = async () => ({
...(await createJestConfig(customJestConfig)()),
transformIgnorePatterns: ["node_modules/(?!(package1|package2)/)", "^.+\\.module\\.(css|sass|scss)$"],
}); In my case packages are: |
I had the same. The cause of this issue is that I cannot include any module under node_modules in Jest's trasform target. Specifically,
This is the relevant part of next/jest. The solution offered by @dariolongo is adequate. const esModules = ['package1', 'package2']
const customConfig = {
// Dependency packages must also be included in this list
transformIgnorePatterns: [`/node_modules/(?!(${esModules.join('|')})/)`],
// And other custom config...
}
module.exports = async () => {
const jestConfig = await _createJestConfig(customConfig)()
return {
...jestConfig,
transformIgnorePatterns: jestConfig.transformIgnorePatterns.filter(
(ptn) => ptn !== '/node_modules/'
), // ['^.+\\.module\\.(css|sass|scss)$', '/node_modules/(?!(package1|package2)/']
}
} I would like to suggest that the documentation be supplemented with "config cannot be completely overwritten". |
I've been trying to look into the next.js configuration, and from what I can see, |
This toggles whether or not the `node_modules` directory will be ignored via the `transformIgnorePatterns`, which appears to be all that's required to correctly load ESM dependencies in your app's tests when working with Next.js & Jest when using Typescript. fixes vercel#38368, vercel#40183
This toggles whether or not the `node_modules` directory will be ignored via the `transformIgnorePatterns`, which appears to be all that's required to correctly load ESM dependencies in your app's tests when working with Next.js & Jest when using Typescript. fixes vercel#38368, vercel#40183
Solution from @nora worked perfectly. I believe this is a bug, but at the very least the docs should be updated to show how |
When using Next.js 13.1 transpilePackages, this solution seems not working by another regex next/jest added. But now just put all module.exports = {
transpilePackages: ['package1', 'package2'],
} |
fyi i fixed this issue by removing the default paths in tsconfig "paths": { |
As mentioned by @oosawy, with the use of Next.js 13.1's transpilePackages, the regex has changed and will generate these
In this case, we don't need to add
|
This workaround seems to be broken with the release of 13.4. Has anyone else had luck upgrading to that release? |
Also encountering this issue. Wondering if next jest config could take into account |
I am experiencing the same issue with an ESM node_module causing Jest errors in v.13.4.1 and ended up downgrading to v.13.2.3. Tried different combinations of |
I just ran into this bug for the transpilePackages: [
"query-string",
"decode-uri-component",
"filter-obj",
"split-on-first",
], Then I didn't need to modify
was correct. This might just be the way it has to be if using npm. Switching to pnpm might allow you to only include the top-level package, |
Has this been resolved? I am still unable to use Jest with nextjs in 13.4 due to esm issues in node_modules. |
Dittoing @AlfredMadere, I'm also still unable to use Jest with Next.JS in 13.5.4 due to esm issues. |
i tried everything in this issue and i`m stuck forever here |
@leandroruel try converting your ESM dependencies to CJS for Jest:
Then update your
|
|
This works for me! using next.js 13.5.6
But the error a changed to:
|
Above suggestion worked for me with Nextjs 14.0.3. |
I am on NextJS 14.0.3 and the |
It work in 14.0.3 using // next.config.js
{
transpilePackages: [
'axios',
'react-dnd-html5-backend',
'supports-webp',
'ramda',
'react-firebase-hooks/auth',
]
}
// jest.config.ts
import type { Config } from 'jest';
import nextJest from 'next/jest.js';
const createJestConfig = nextJest({
// Provide the path to your Next.js app to load next.config.js and .env files in your test environment
dir: './',
});
// Add any custom config to be passed to Jest
const config: Config = {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
moduleNameMapper: {
'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
'^@/(.*)$': '<rootDir>/$1',
},
testPathIgnorePatterns: ['/tests/'],
resetMocks: false,
clearMocks: true,
};
export default createJestConfig(config); and here is the produced config: {
coverageProvider: 'v8',
testEnvironment: 'jsdom',
setupFilesAfterEnv: [ '<rootDir>/jest.setup.js' ],
moduleNameMapper: {
'^.+\\.module\\.(css|sass|scss)$': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/object-proxy.js',
'^.+\\.(css|sass|scss)$': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/styleMock.js',
'^.+\\.(png|jpg|jpeg|gif|webp|avif|ico|bmp)$': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/fileMock.js',
'^.+\\.(svg)$': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/fileMock.js',
'@next/font/(.*)': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/nextFontMock.js',
'next/font/(.*)': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/nextFontMock.js',
'server-only': '/Users/user/src/demo-app/node_modules/next/dist/build/jest/__mocks__/empty.js',
'react-markdown': '<rootDir>/node_modules/react-markdown/react-markdown.min.js',
'^@/(.*)$': '<rootDir>/$1'
},
testPathIgnorePatterns: [ '/node_modules/', '/.next/', '/tests/' ],
resetMocks: false,
clearMocks: true,
transform: {
'^.+\\.(js|jsx|ts|tsx|mjs)$': [
'/Users/user/src/demo-app/node_modules/next/dist/build/swc/jest-transformer.js',
[Object]
]
},
transformIgnorePatterns: [
'/node_modules/(?!.pnpm)(?!(axios|react-dnd-html5-backend|supports-webp|ramda|react-firebase-hooks/auth)/)',
'/node_modules/.pnpm/(?!(axios|react-dnd-html5-backend|supports-webp|ramda|react-firebase-hooks\\+auth)@)',
'^.+\\.module\\.(css|sass|scss)$'
],
watchPathIgnorePatterns: [ '/.next/' ]
} |
* fix(deps): update dependency next to v14 * fix(nextjs): rectify antd-related modularize imports See vercel/next.js#40183 and vercel/next.js#58817. --------- Co-authored-by: renovate[bot] <29139614+renovate[bot]@users.noreply.github.com> Co-authored-by: sabertazimi <[email protected]>
I have similar issue. I just upgraded to nextjs 14 from nextjs 12. And i get the following error:
Inside my jsconfig.js i have It works fine when i run the app, but jest throws errors when i run the test. |
I'm getting this issue with Next 14.1.0, even when using create-next-app. It looks like ESLINT and JEST/Cypress are not working together. It is possible to quickly reproduce it following the steps below: Run Then, follow the step to add config Jest Then, try to run the I have tried to use |
if it helps someone here's my config file: const nextJest = require('next/jest')
const swiperMocks = require('./src/__mocks__/misc/swiper.ts')
const createJestConfig = nextJest({
// Path to Next.js app to load next.config.js
dir: './',
})
/** @type {import('@jest/types').Config.InitialOptions} */
const customJestConfig = {
testEnvironment: 'jest-environment-jsdom',
setupFilesAfterEnv: ['<rootDir>/jest.setup.ts'],
maxWorkers: 4,
/**
* Custom config goes here, I am not adding it to keep this example simple.
* See next/jest examples for more information.
*/
moduleNameMapper: {
'^@/components/(.*)$': '<rootDir>/components/$1',
'^components/(.*)$': '<rootDir>/src/components/$1',
'^helpers/(.*)$': '<rootDir>/src/helpers/$1',
'^generated/(.*)$': '<rootDir>/src/generated/$1',
'^mixins/(.*)$': '<rootDir>/src/mixins/$1',
'^hooks/(.*)$': '<rootDir>/src/hooks/$1',
'^mocks/(.*)$': '<rootDir>/src/__mocks__/$1',
...swiperMocks.moduleNameMapper,
},
transform: {
...swiperMocks.transform,
},
modulePaths: ['<rootDir>/src/'],
collectCoverage: true,
collectCoverageFrom: [
'<rootDir>/src/components/**/*.tsx',
'!<rootDir>/src/pages/**',
'!<rootDir>/src/components/**/stories.tsx',
'!<rootDir>/src/components/**/index.ts',
],
coveragePathIgnorePatterns: ['.*__snapshots__/.*'],
}
const esModules = [
'ccount',
'react-markdown',
'vfile',
'unist-.+',
'unified',
'bail',
'is-plain-obj',
'trough',
'remark',
'remark-.+',
'mdast-util-.+',
'micromark',
'parse-entities',
'character-entities',
'property-information',
'comma-separated-tokens',
'hast-util-whitespace',
'hast-util-to-html',
'hast-util-sanitize',
'html-void-elements',
'space-separated-tokens',
'decode-named-character-reference',
'zwitch',
'longest-streak',
'stringify-entities',
'trim-lines',
'swiper',
'swiper/react',
'ssr-window',
'dom7',
].join('|')
module.exports = async () => ({
/**
* Using ...(await createJestConfig(customJestConfig)()) to override transformIgnorePatterns
* provided byt next/jest.
*
* @link https://github.com/vercel/next.js/issues/36077#issuecomment-1096635363
*/
...(await createJestConfig(customJestConfig)()),
/**
* Swiper uses ECMAScript Modules (ESM) and Jest provides some experimental support for it
* but "node_modules" are not transpiled by next/jest yet.
*
* @link https://github.com/vercel/next.js/issues/36077#issuecomment-1096698456
* @link https://jestjs.io/docs/ecmascript-modules
*/
transformIgnorePatterns: [`<rootDir>/node_modules/(?!${esModules})/`],
}) |
I was able to fix that by adding
in my Make sure you do |
@AtanasChachev That works; thanks for sharing this alternative solution 💯 |
@leandroruel thank you for your config but this still does not work for me. Here are my deps:
For example, I get this error when using ESM in my test component: I even get it when mocking it in jest.setup.ts with simply The only solution I found so far is to create the manual Very confusing I think I'm going to give a try to Vitest instead. |
@rafal-r Yeah, i stopped using jest and I'm using vitest from now on. less headaches. |
I spent half a day trying to fix the ERR_REQUIRE_ESM error. In the end, everything worked for me after adding
My
|
This solution from @leandroruel worked for me in |
On transform: {
// Use SWC to compile tests
"^.+\\.(js|jsx|ts|tsx|mjs)$": [
require.resolve("../swc/jest-transformer"),
jestTransformerConfig
],
// Allow for appending/overriding the default transforms
...resolvedJestConfig.transform || {}
}, Removing the import nextJest from "next/jest.js";
const createJestConfig = nextJest({
dir: "./",
});
const config = {
// ...
}
function removeEsmFromTransforms(config: JestConfig.Config.InitialOptions): JestConfig.Config.InitialOptions {
const transform = config.transform || {};
const key = "^.+\\.(js|jsx|ts|tsx|mjs)$";
if (transform.hasOwnProperty(key)){
const v = transform[key] || '';
delete transform[key];
transform[key.replace(/\|mjs/, '')] = v;
}
return {
...config,
transform,
};
}
export default () => createJestConfig(config)().then(removeEsmFromTransforms); A bit awkward, but it's the only thing that worked for me. |
Verify canary release
Provide environment information
Which example does this report relate to?
https://nextjs.org/docs/testing
What browser are you using? (if relevant)
No response
How are you deploying your application? (if relevant)
No response
Describe the Bug
If you have a project with a dependency that is published as an es modules in node_modules, running jest will not work..even though nextjs works with it e.g. running the project normally with npm run dev.
Test does not run even if ignoring the package. Please check this repo that reproduce the problem:
https://github.com/wmira/banana/
if you run npm run dev here..works fine.. npm run test here does not and this follow the jest example.
Expected Behavior
running test via jest works as per the docs
To Reproduce
repo is below:
https://github.com/wmira/banana/
The text was updated successfully, but these errors were encountered: