最近のJestでシンプルにimport/exportを使う方法

JestはデフォルトではECMAScript Modulesをサポートしていないため、import/export文を使いたい場合はbabelを使用してCommonJsに変換する必要がありました。

Googleで検索すると、多くの記事ではこの方法を紹介しています。

こちらによると、babelを使わなくてもimport/export文が使えるようなので試してみました。(20210417現在、実験的機能です)

前提

  • Jestのバージョンは26.x
  • nodeのバージョンは14.13.1以上

Jestをインストールする

npm install -D jest

インストールが終わったらpackage.jsonをみて、バージョンが26.xか確認します。

package.json を編集する

行うことは2点です。

  • nodeでimport/exportが使えるようにするために、"type": “module" を追記する
  • –experimental-vm-modules を指定したjest実行コマンドを追記する
{
  "name": "jest-es",
  "version": "1.0.0",
  "description": "",
  "type": "module", <<<追記
  "main": "index.js",
  "scripts": {
    "test": "node --experimental-vm-modules node_modules/.bin/jest" <<<追記
  },
  "keywords": [],
  "author": "",
  "license": "ISC",
  "devDependencies": {
    "jest": "^26.6.3"
  }
}

ソースコードとテストコードを書く

まずテスト対象にする関数を適当に書きます。

export const hoge = (str) => `hoge ${str}`

このhoge関数に対するテストを書きます。

import {hoge} from "./helper.js"

describe('hoge', () => {
  test('引数が文字列の場合の出力が正しい', () => {
    expect(hoge('tamibouz')).toBe('hoge tamibouz')
  })
  test('引数が空文字の場合の出力が正しい', () => {
    expect(hoge('')).toBe('hoge ')
  })
})

テストを実行する

$ npm test

> jest-es@1.0.0 test /Users/tmbuz/project/jest-es
> node --experimental-vm-modules node_modules/.bin/jest

(node:9945) ExperimentalWarning: VM Modules is an experimental feature. This feature could change at any time
(Use `node --trace-warnings ...` to show where the warning was created)
 PASS  src/helper.test.js
  hoge
    ✓ 引数が文字列の場合の出力が正しい (2 ms)
    ✓ 引数が空文字の場合の出力が正しい

Test Suites: 1 passed, 1 total
Tests:       2 passed, 2 total
Snapshots:   0 total
Time:        1.99 s
Ran all test suites.

特にbabelを使わなくてもimport/exportを使ったテストコードを実行することができました。

ただ、警告にもあるようにこれは実験的な機能です。(20210417現在)

なお、–experimental-vm-modules をなくすと以下のエラーになります。

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