运行Jest测试时遭遇「Cannot use import statement outside a module」错误的解决求助
运行Jest测试时遭遇「Cannot use import statement outside a module」错误的解决求助
我在尝试用Jest运行以下测试用例时,遇到了「SyntaxError: Cannot use import statement outside a module」的报错,折腾了好几种方法还是没解决,想请大家帮忙看看我的配置哪里出问题了?
我的测试代码(get-questions.test.ts)
import request from "supertest"; import app from '../../src/app'; import QuestionService from "../../src/api/services/questionService"; import { mockDBQuestions } from './get-question-utils'; // Mock the QuestionService function properly jest.mock("../../src/api/services/questionService", () => ({ __esModule: true, // Ensure ESM compatibility default: { getQuestionsAndAnswers: jest.fn(), }, })); describe("fetchAllQuestionsController", () => { it("should return questions with status 200", async () => { // Mock DB response const mockQuestions = mockDBQuestions; jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockResolvedValue(mockQuestions); const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "Onboarding" }); expect(response.status).toBe(200); expect(response.body).toEqual(mockQuestions); expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding"); }); it("should return empty set with status 200", async () => { jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockResolvedValue([]); const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "abcdef" }); expect(response.status).toBe(200); expect(response.body).toEqual([]); expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding"); }); it("should return status 500 on error", async () => { jest.spyOn(QuestionService, "getQuestionsAndAnswers").mockRejectedValue(new Error("Internal Server Error")); const response = await request(app).get("/questions/fetchQuestions").query({ questionType: "Onboarding" }); expect(response.status).toBe(500); expect(QuestionService.getQuestionsAndAnswers).toHaveBeenCalledWith("Onboarding"); }); });
我的Babel配置(babel.config.js)
export default { presets: [ ['@babel/preset-env', { targets: { node: 'current' }, modules: false}], '@babel/preset-typescript', ], plugins: [ ['@babel/plugin-proposal-decorators', { legacy: true }], ['@babel/plugin-transform-flow-strip-types'], ['@babel/plugin-proposal-class-properties', { loose: true }], ], };
Jest配置(test.config.js)
export default { preset: 'ts-jest/presets/default-esm', testEnvironment: 'node', testMatch: ['**/tests/**/*.test.ts'], moduleFileExtensions: ['ts', 'js', 'json', 'node', 'mjs', 'cjs'], transform: { '^.+\\.ts$': [ 'ts-jest', { useESM: true, // Ensuring Jest treats TS as ESM }, ], }, extensionsToTreatAsEsm: ['.ts'], transformIgnorePatterns: ['node_modules/(?!supertest/)'], // Transpile 'supertest' if needed globals: { 'ts-jest': { tsconfig: 'tsconfig.json', useESM: true, }, }, setupFilesAfterEnv: ['./jest.setup.ts'], // Ensure Jest setup is working };
package.json 片段
{ "name": "backendtemplate", "version": "1.0.0", "main": "index.js", "type": "module", "jest": { "transform": {} } }
tsconfig.json 配置
{ "compilerOptions": { "target": "ESNext", "module": "ESNext", "outDir": "./dist", "rootDir": "./src", "esModuleInterop": true, "moduleResolution": "node", "resolveJsonModule": true, "experimentalDecorators": true, "emitDecoratorMetadata": true, "useDefineForClassFields": false, "allowSyntheticDefaultImports": true, "forceConsistentCasingInFileNames": true, "noEmit": true, "allowImportingTsExtensions": true, "strict": true, "noImplicitAny": true, "strictNullChecks": true, "skipLibCheck": true, "sourceMap": true, "removeComments": true, "noEmitOnError": true, "noUnusedLocals": true, "noUnusedParameters": true, "noImplicitReturns": true, "types": ["node"], "strictPropertyInitialization": false, }, "include": ["src/**/*"], "exclude": ["node_modules", "dist"] }
我遇到的错误信息
(dev-serve/api) [dynodatingappbe:user_profile_edit_api] % npm run test > backendtemplate@1.0.0 test > jest PASS tests/UserProfileEditModule/update-user-profile.test.ts PASS tests/server.test.ts FAIL tests/QuestionModule/get-questions.test.ts ● Test suite failed to run Jest encountered an unexpected token Jest failed to parse a file. This happens e.g. when your code or its dependencies use non-standard JavaScript syntax, or when Jest is not configured to support such syntax. Out of the box Jest supports Babel, which will be used to transform your files into valid JS based on your Babel configuration. By default "node_modules" folder is ignored by transformers. Here's what you can do: • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/ecmascript-modules for how to enable it. • If you are trying to use TypeScript, see https://jestjs.io/docs/getting-started#using-typescript • To have some of your "node_modules" files transformed, you can specify a custom "transformIgnorePatterns" in your config. • If you need a custom transformation specify a "transform" option in your config. • If you simply want to mock your non-JS modules (e.g. binary assets) you can stub them out with the "moduleNameMapper" config option. You'll find more details and examples of these config options in the docs: https://jestjs.io/docs/configuration For information about custom transformations, see: https://jestjs.io/docs/code-transformation Details: /Users/rahul.negi/personal/Dyno/dynodatingappbe/tests/QuestionModule/get-questions.test.ts:1 ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import request from "supertest"; ^^^^^^ SyntaxError: Cannot use import statement outside a module at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1505:14) Test Suites: 1 failed, 2 passed, 3 total Tests: 2 passed, 2 total Snapshots: 0 total Time: 0.143 s, estimated 1 s Ran all test suites.
我已经尝试过的方法
- 把
babel.config.js重命名为babel.config.cjs - 确认
tsconfig.json里已经正确设置了"module": "ESNext"和"moduleResolution": "node" - 在
test.config.js里添加了transformIgnorePatterns: ['node_modules/(?!supertest/)']
但还是没解决问题,请问我还有哪里没配置对吗?
备注:内容来源于stack exchange,提问作者Rahul Negi
相关产品推荐
相关产品推荐

