简体   繁体   中英

Jest - SyntaxError: Cannot use import statement outside a module with @nestjs/axios

I'm just trying to run some integration tests on a nestjs app, but I'm getting the following error:

SyntaxError: Cannot use import statement outside a module

I spent a lot of time on this problem that should be easy to fix but I can't deal with it. This problem occurs with @nestjs/axios lib which uses ESM instead of CommonJs. After doing some research, I saw that theoretically I should run the tests with this command:

yarn node --experimental-vm-modules $(yarn bin jest)

But nothing i do works I also don't understand why this file is being matched since it is in node_modules Can someone help me?

My Jest config:

"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"
    }

My versions:

"@nestjs/axios": "^1.0.1",
"@types/jest": "^24.0.18",
"jest": "^26.0.0",
"ts-jest": "^26.5.5",
"typescript": "^4.2.3"

I've already tried putting node_modules (which is already jest's default behavior) in the transformIgnorePatterns setting, but it's not working.

The lib I'm having this error is an internal lib (node_modules/@bank/auth/node_modules/@nestjs/axios/node_modules/axios/index.js:1), could it be the reason for the problem?

This has to do with jest and ts-jest seeing the library as an ESM module due to how the package.json is set up. You should be able to add this to your jest config and have no issues.

moduleNameMapper: {
    '^axios$': require.resolve('axios'),
},

This should force jest to resolve the library correctly from node_modules

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM