node.js - 开 Jest - 语法错误 : Cannot use import statement outside a module with @nestjs/axios

标签 node.js typescript jestjs nestjs ts-jest

我只是尝试在 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'),
},

这应该强制jestnode_modules正确解析库

关于node.js - 开 Jest - 语法错误 : Cannot use import statement outside a module with @nestjs/axios,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/75233695/

相关文章:

Node.js Sequelize typescript

html - 将 html 类型 ="date"与 typescript new Date() 对象进行比较

javascript - 在 Typescript 中输入 Immutable.js Map

node.js - 加快 Node.js 项目的编译速度

javascript - 为什么前端框架在 NPM 中?

javascript - 请建议使用 jest 对这两个功能进行单元测试的正确方法

javascript - 使用 Enzyme 测试点击监听器

reactjs - 无法在 bool 值 'true' 测试用例上准备属性 __mobxInstanceCount 失败 typescript 和 mobx

coffeescript - 如何将 jest 与 CoffeeScript 和 ES6/ES2015 一起使用(例如通过 Babel)?

node.js - 创建后从设备 JSON 生成 Azure IoT 中心的连接字符串