vanilla js の jest で impor export を使用する

vanilla js で jest で テストファイルの中にimpor export を使用すると次のようなエラーが表示されることがあります

   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.

これを node.js 変換によって回避する方法はこちらです

● 1. シェルから次のコマンドを実行する

export NODE_OPTIONS=--experimental-vm-modules

● 2. package,json に追加

"type": "module" を追加します。

{
  "devDependencies": {
    "jest": "^28.1.2"
  },
  "type": "module"
}

● jest.config.js を esモジュール形式にする

module.exports = {
  testMatch: ['<rootDir>/**/*.test.js'],
};

   ↓

export default {
  testMatch: ['<rootDir>/**/*.test.js'],
};

以上です。

● jest の実行

npm test

または

npx jest

してみましょう

No.2182
07/01 13:48

edit