我是Jest设置的新手,我已经使用Jest示例https://github.com/vercel/next.js/tree/canary/examples/with-jest基于nextjs设置了Jest
这是我的jest.js.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: './',
});
// Add any custom config to be passed to Jest
const customJestConfig = {
setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
testEnvironment: 'jest-environment-jsdom',
preset: 'ts-jest',
transformIgnorePatterns: ['node_modules/(?!@azure/msal-react|antd)'],
transform: {
'^.+\\.(js|jsx|ts|tsx)?$': 'babel-jest',
'^.+\\.tsx?$': 'ts-jest',
},
moduleNameMapper: {
'@azure/msal-react': '<rootDir>/mocked/module.js',
},
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
字符串
tsconfig.json
{
"ts-node": {
// these options are overrides used only by ts-node
"compilerOptions": {
"module": "commonjs"
}
},
"compilerOptions": {
"target": "es5",
"lib": ["dom", "dom.iterable", "esnext"],
"allowJs": true,
"skipLibCheck": true,
"strict": true,
"forceConsistentCasingInFileNames": true,
"noEmit": true,
"esModuleInterop": true,
"module": "esnext",
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve",
"incremental": true,
"plugins": [
{
"name": "next"
}
],
"baseUrl": ".",
"paths": {
"@/*": ["./*"],
"@/public": ["public/*"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx", ".next/types/**/*.ts"],
"exclude": ["node_modules"]
}
型
这里有一个Jest来检查测试是否可以成功运行
import { render, screen } from '@testing-library/react';
import { Button } from 'antd';
jest.mock('next/navigation', () => ({
useRouter: () => ({
route: '/',
pathname: '/',
query: {},
asPath: '/',
}),
usePathname: jest.fn(),
}));
describe('Login', () => {
it('render page', () => {
render(<Button />);
const heading = 'render';
expect(heading).toEqual('render');
});
});
型
当我运行测试时,我得到了这个错误
\node_modules\antd\es\button\index.js:3 import Button from './button';^
语法错误:无法在模块外部使用导入语句
我目前使用的是NextJS 14.0.3,next-intl,redux工具包,antd 5.11.2
测试在没有库组件的情况下正常运行,因此我不知道是否遗漏了其他内容
我希望有人能帮助我这一点,非常感谢
我试图配置和研究,以解决这个问题,但没有运气
1条答案
按热度按时间hmae6n7t1#
所以我在这篇文章中解决了我的问题,希望这能帮助任何人和我在未来
所以基本上,NextJS在它的github中有一个例子,我已经遵循了它,如果你只需要测试NextJS中的内置元素(没有其他库),遵循这个例子可以帮助你设置Jest而无需进一步配置,你可以看看这个NextJS with jest example
在我的情况下,我的项目包括UI库,redux工具包,下一个intl.所以我做了一些研究,并最终与此setup jest in NextJS 14 with msal, redux tool kit,我已经包括了所有的代码在这篇文章的链接,还有一些事情我不明白,所以感谢它,如果有人可以解释,但现在,配置工作得很好
字符串