LoginSignup
3
2

More than 5 years have passed since last update.

babel7で power-assert を mocha6 で使う

Last updated at Posted at 2019-03-30

概要

通常、power-assertをmochaで使う場合は、intelli-espower-loadermocha --requireすることで使えますが、ES6以降のテストコードで使う場合は babel を使ってトランスパイルしなければなりません。
babelを使ってpower-assertを使用するやり方を今日一日探していたんですが、babelやmochaのバージョンが古い情報が多くて新しい情報が少なく、動かすまで半日以上かかってしまいました。

したがって今回自分用のメモとして babelの 7系 でpower-assertを使うパターンを紹介します。

必要なモジュール

それぞれのモジュールについては詳しく説明しませんので各自ググりをお願いします。

babel系

  • @babel/core 7.4.0
  • @babel/polyfill 7.4.0
  • @babel/preset-env 7.4.1
  • @babel/register7.4.0

mocha

  • mocha 6.0.0

power-assert系

  • power-assert 1.6.1
  • babel-plugin-espower 3.0.1

【注意】
* babel7系は6系とモジュール名が違うので注意してください。
* babel-plugin-espowerを使う場合は、intelli-espower-loaderは使いません。

やり方

1. モジュールインストール > 2. 設定ファイルの作成 > 3. テストを書く > 4. mocha実行

1. モジュールのインストール

$ npm install --save-dev @babel/core @babel/polyfill @babel/preset-env @babel/register mocha power-assert babel-plugin-espower

もしくは

$ yarn add @babel/core @babel/polyfill @babel/preset-env @babel/register mocha power-assert babel-plugin-espower

2. 設定ファイルの作成

.babelrc

.babelrcに設定を記述します。

{
    "presets": [
        "@babel/preset-env"
    ],
    "plugins": [
        "babel-plugin-espower"
    ]
}

presets@babel/preset-envを使うのはES6以降のコードを書くためです。

mocha.opts

mocha.optsにmochaを実行するときの引数を記述します。

--recursive
--require @babel/register
--require @babel/polyfill
  • --recursivetestディレクトリを再帰的にテストする引数です。
  • --require @babel/registerはmochaに@babel/registerモジュールを require するための引数です。@babel/registerがES6以降のテストコードを変換してくれます。
  • --require @babel/polyfillはmochaに@babel/polyfillモジュールを require するための引数です。Promiseなどの@babel/coreが変換できない機能を変換してくれます。

【注意】
* --compilersは廃止されましたので、 --requireを使用してください。

3. テストを書く

test.js
import assert from "power-assert";
describe("Tests", () => {
    it("Calcuation test", () => {
        const value = 1 + 1;
        assert(value === 2);
    });
});

4. mochaを実行

$ npx mocha

結果:



  Tests
    1) Calcuation test


  0 passing (69ms)
  1 failing

  1) Tests
       Calcuation test:

      AssertionError [ERR_ASSERTION]:   # test/test.js:6

  assert(value === 3)
         |     |     
         2     false 

  [number] 3
  => 3
  [number] value
  => 2

      + expected - actual

      -false
      +true

これでpower-assertが動きます。

3
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
3
2