在运行jest测试的时候为何报错:SyntaxError: Cannot use import statement outside a module?
在我的测试项目中:
// test001.ts
export function mySum(a:number, b: number) {
return a + b
}
mySum(11, 22)
// test/unit/test001.spec.ts
import mySum from '../../test001'
describe('calculate function', () => {
it('', () => {
expect(mySum(11, 22)).toEqual(33)
})
}
但是在运行npm run test的时候报错:
$ npm run test
> my-app@0.1.0 test
> jest
FAIL test/unit/test001.spec.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/dele/Desktop/Test/js/typescript/ts-test01/my-app/test/unit/test001.spec.ts:1
({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,jest){import { mySum } from '../../test001';
^^^^^^
SyntaxError: Cannot use import statement outside a module
at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1495:14)
Test Suites: 1 failed, 1 total
Tests: 0 total
Snapshots: 0 total
Time: 0.136 s
Ran all test suites.
回复
1个回答

test
2024-07-02
1.用 Jest 的 transform 配置选项。在 Jest 配置文件( jest.config.js)里加一个 transform 选项,指定一个用来转换你代码的模块。用 babel-jest 来转换代码。
2.你用的是 TS,你也可以用 ts-jest。你可以在 Jest 配置文件中加一个 preset 选项,设为 'ts-jest'。
回复

适合作为回答的
- 经过验证的有效解决办法
- 自己的经验指引,对解决问题有帮助
- 遵循 Markdown 语法排版,代码语义正确
不该作为回答的
- 询问内容细节或回复楼层
- 与题目无关的内容
- “赞”“顶”“同问”“看手册”“解决了没”等毫无意义的内容