LoginSignup
11
6

More than 5 years have passed since last update.

ES6なクラスをmocha,chaiでテストする

Last updated at Posted at 2017-01-10

結論から言うといつものmochaコマンドを

mocha --compilers js:babel-core/register

とすればトランスパイルが走ってES6をテストできます。

例えばこのようなクラスがあったとします

ReceiveParameter.es6

export default class RecieveParameter {
  constructor(e) {
    const req = JSON.parse(e.postData.contents);
    const payload = req.payload;
    this.status = payload.status;
    this.subject = payload.subject;
    this.build_url = payload.build_url;
    this.branch = payload.branch;
    this.reponame = payload.reponame;
    this.username = payload.username;
  }

  returnParams() {
    return {
      status: this.status,
      subject: this.subject,
      build_url: this.build_url,
      branch: this.branch,
      reponame: this.reponame,
      username: this.username,
    };
  }
}

このクラスをテストするスクリプトは、以下となります。

ReceiveParameterSpec.es6

import chai from 'chai';
import ParameterClass from 'ReceiveParameter';
let should = chai.should();
// import {should, expect} from 'chai';

describe('ParameterClass', () => {
  const contents = {
    payload: {
      status: 'fixed',
      subject: '',
      build_url: '',
      branch: '',
      reponame: '',
      username: ''
    }
  };
  const request = {
    postData: {
      contents: JSON.stringify(contents)
    }
  };
  let params;

  beforeEach(() => {
    params = new ReceiveParameter(request);
  });

  context('this is first test script.', () => {
    it('test!', () => {
      const result = params.returnParams();
      result.status.should.equal('fixed');
    });
  });
});

テストスクリプトの中でもimportの様なes6構文が使えます。

あとはmochachaiをインストールして

mocha --compilers js:babel-core/register

コマンドを実行してください。

このコマンドはトランスパイルを実行するので、babelの設定を忘れないでください。

自分の場合、babel-preset-latestをインストールしています。

まとめ

es6によりJavaScriptがよりOOPしやすい言語となり、テスト・振る舞い駆動開発と相性がよくなった印象です。

参考文献

11
6
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
11
6