我正试图使用jest在next.js中运行一个测试,但我一直收到一个错误:The error below may be caused by using the wrong test environment, see https://jestjs.io/docs/configuration#testenvironment-string. Consider using the "jsdom" test environment.
我已经尝试过跟随链接并添加文档块:
/**
* @jest-environment jsdom
*/
我的代码没有成功。
我还尝试过基于next.js测试页面配置我的jest.config.js。这不起作用,我已经尝试了使用和不使用rust编译器的解决方案。两者都不起作用:
Package.JSON:
{
"name": "chat",
"version": "0.1.0",
"private": true,
"scripts": {
"dev": "next dev",
"build": "next build",
"start": "next start",
"lint": "next lint",
"test": "jest --env=node --forceExit --watchAll --coverage"
},
"dependencies": {
"@firebase/testing": "^0.20.11",
"firebase": "^9.9.4",
"kill-port": "^2.0.1",
"next": "12.2.5",
"react": "18.2.0",
"react-dom": "18.2.0",
"react-firebase-hooks": "^5.0.3",
"react-hot-toast": "^2.3.0",
"uuid": "^8.3.2"
},
"devDependencies": {
"@babel/plugin-syntax-jsx": "^7.18.6",
"@babel/preset-react": "^7.18.6",
"@firebase/rules-unit-testing": "^2.0.4",
"@testing-library/jest-dom": "^5.16.5",
"@testing-library/react": "^13.4.0",
"@types/jest": "^29.0.2",
"eslint": "8.23.0",
"eslint-config-next": "12.2.5",
"firebase-admin": "^11.0.1",
"jest": "^29.0.3",
"jest-environment-jsdom": "^29.0.3"
}
}
Jest.config.js:
// 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: './',
});
// Add any custom config to be passed to Jest
/** @type {import('jest').Config} */
const customJestConfig = {
// Add more setup options before each test is run
// setupFilesAfterEnv: ['<rootDir>/jest.setup.js'],
// if using TypeScript with a baseUrl set to the root directory then you need the below for alias' to work
//moduleDirectories: ['node_modules', '<rootDir>/'],
testEnvironment: 'jest-environment-jsdom',
};
// createJestConfig is exported this way to ensure that next/jest can load the Next.js config which is async
module.exports = createJestConfig(customJestConfig);
test/page.test.js
import { render, screen } from '@testing-library/react';
import Home from '../pages/index';
describe('Home', () => {
it('renders a heading', () => {
render(<Home />);
expect(2 + 2).toBe(4);
});
});
如果要覆盖npmtest
脚本中的env
,请删除--env=node
:
"test": "jest --forceExit --watchAll --coverage"