我只是尝试在 Nestjs 应用程序上运行一些集成测试,但收到以下错误:
语法错误:无法在模块外部使用 import 语句
我花了很多时间来解决这个问题,本应该很容易解决,但我无法处理它。
使用 ESM 而不是 CommonJs 的 @nestjs/axios
lib 会出现此问题。经过一些研究后,我发现理论上我应该使用以下命令运行测试:
yarn Node --experimental-vm-modules $(yarn bin jest)
但我所做的一切都不起作用 我也不明白为什么这个文件被匹配,因为它位于 node_modules 中 有人可以帮助我吗?
我的 Jest 配置:
"jest": {
"moduleFileExtensions": [
"js",
"json",
"ts"
],
"rootDir": "",
"preset": "ts-jest",
"testRegex": ".spec.ts$",
"transform": {
"^.+\\.(t|j)s$": "ts-jest"
},
"coverageDirectory": "./coverage",
"testEnvironment": "node",
"globalSetup": "<rootDir>/tests/jest.setup.ts",
"globalTeardown": "<rootDir>/tests/jest.teardown.ts"
}
我的版本:
"@nestjs/axios": "^1.0.1",
"@types/jest": "^24.0.18",
"jest": "^26.0.0",
"ts-jest": "^26.5.5",
"typescript": "^4.2.3"
我已经尝试将node_modules(这已经是jest的默认行为)放入transformIgnorePatterns
设置中,但它不起作用。
我遇到此错误的库是内部库(node_modules/@bank/auth/node_modules/@nestjs/axios/node_modules/axios/index.js:1),这可能是问题的原因吗?
最佳答案
由于 package.json 的设置方式,这与 jest 和 ts-jest 将库视为 ESM 模块有关。您应该能够将其添加到您的 Jest 配置中并且没有任何问题。
moduleNameMapper: {
'^axios$': require.resolve('axios'),
},
这应该强制jest
从node_modules
正确解析库
关于node.js - 开 Jest - 语法错误 : Cannot use import statement outside a module with @nestjs/axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75233695/