コピペコードで快適生活

明日使えるソースを自分のために

ES2015のコードをBabel+Jestでテストする

まだ試したことがなかったので、やり方をメモ。

ライブラリのインストール

# bableのインストール
npm install --save-dev @babel/core @babel/cli @babel/preset-env

# jestのインストール
# babel-jestも一緒にインストールされる
npm install --save-dev jest

# importはNode.jsで使えないため
# requireに変換するライブラリをインストール
npm install --save-dev @babel/plugin-transform-modules-commonjs

babelの設定

babel.config.js

module.exports = {
  presets: [
    [
      "@babel/preset-env"
    ]
  ],
  env: {
    test: {
      // テスト環境でimport->require変換を有効にする
      plugins: [
        "transform-es2015-modules-commonjs",
      ],
    },
  },
};

jestの設定

jestの設定ファイル(jest.config.js)作成

npx jest --init

jest.config.jsは初期状態のままでOK。

設定詳細 https://jestjs.io/docs/ja/configuration

scriptの追加

package.json

"scripts": {
  "test": "jest",
  "test:w": "jest --watch",
  "test:coverage": "jest --coverage"
},

テストを書いてみる

app/models/user.js

class User {
  constructor(attrs = {}) {
    this.firstName = attrs.firstName;
    this.lastName = attrs.lastName;
  }

  getFullName() {
    return `${this.firstName} ${this.lastName}`;
  }
}

export default User;

test/models/user.test.js

import User from '../../app/models/user';

describe('getFullName', () => {
  it('firstName + lastName の値が返される', () => {
    let user = new User({firstName: 'taro', lastName: 'yamada'});
    let fullName = user.getFullName();
    expect(fullName).toEqual('taro yamada');
  });
});

テスト実行

# ファイルを指定して実行
npm run test test/models/user.test.js

# テスト後にカバレッジ率を表示
npm run test:coverage test/models/user.test.js

メモ

しばらくbabelから離れている間に色々変わっていた。

  • babelが7系からパッケージ名が @bable/xxx になっていた。
  • babelの設定ファイルが babel.config.js になっていた。
  • babelrcは個別設定用という位置づけに変わっていた。
  • preset-2015が不要になり、preset-envが設定に応じて適切なライブラリを選択してくれるようになっていた。

参考にさせていただきました
Babel + Jest で JavaScript のテストをする - かもメモ