Dev./Node.js

[Jest] SyntaxError: Cannot use import statement outside a module 이슈 해결

인쥭 2024. 5. 13. 14:56
반응형

분명히 며칠 전까진 잘 돌던 jest 테스트 케이스가 아래와 같은 메시지를 뱉으며 실패했다.

  ● Test suite failed to run

    Jest encountered an unexpected token

    This usually means that you are trying to import a file which Jest cannot parse, e.g. it's not plain JavaScript.

    By default, if Jest sees a Babel config, it will use that to transform your files, ignoring "node_modules".

    Here's what you can do:
     • If you are trying to use ECMAScript Modules, see https://jestjs.io/docs/en/ecmascript-modules for how to enable it.
     • 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/en/configuration.html

    Details:

    /Users/ingnoh/workspace/my-toy-project/src/node_modules/axios/index.js:1
    ({"Object.<anonymous>":function(module,exports,require,__dirname,__filename,global,jest){import axios from './lib/axios.js';
                                                                                             ^^^^^^

    SyntaxError: Cannot use import statement outside a module

      1 | "use strict";
      2 |
    > 3 | const axios = require("axios");
    
    at Runtime.createScriptFromCode (node_modules/jest-runtime/build/index.js:1350:14)
    at Object.<anonymous> (src/app.js:3:15)

알고보니 node_modules에 명시된 라이브러리들의 버전을 올리는 과정에서 axios의 버전이 0.2x.x 에서 1.6.x로 크게 올라가며 생긴 이슈로, 0.2x.x에서는 CommonJS 문법을 사용하던 axios가 1.6.x에서는 ESM을 사용하고 있기에 발생한 문제였다.

이에 jest.config.js에 아래와 같이 moduleNameMapper 옵션을 추가하는 것으로 해당 이슈를 해결할 수 있었다.

'use strict';

module.exports = {
    moduleNameMapper: {
        "^axios$": "<rootDir>/node_modules/axios/dist/node/axios.cjs"
    },
};