35
25

More than 5 years have passed since last update.

Rewireを使ってNode.jsのprivateなfunctionをテストする

Last updated at Posted at 2016-04-13

Node.js初心者な私がいろいろはまったことメモ。
Node.jsのUnit Testでexportsしていないfunctionをテストしたかったので、調べていたら便利なライブラリを発見。

使用ライブラリ

rewire(下記参照)
https://github.com/jhnns/rewire

使い方

インストール

npm install rewire

テストしたいファイルサンプル

somethig.js
exports.someMethod1 = someMethod1

function someMethod1(var1, var2) {
 // 外部ファイルから読み出せる
}

function someMethod2(var1, var2) {
 // 外部ファイルから読み出せない
}

この場合、someMethod1は外部からテストできるけど、someMethod2がexportsされていないためテストが出来ない。

普通にrequireしてテストしてみる

test.js
describe('#someMethod2', function () ) {
  it('should ok', function (done) ) {
    var something = require('something.js')
      ;
    result = something.someMethod2(var1, var2);
    assert.ok(result);
  }
}

結果

ReferenceError: someMethod2 is not defined

rewireを使ってテストしてみる

以下のようにrewireの__get__を使う事でexportsされていないオブジェクトにアクセスできるようになる。

test.js
describe('#someMethod2', function () ) {
  it('should ok', function (done) ) {
    var something = rewire('something.js')
      , someMethod2 = something.__get__('someMethod2')
      , result = null
      ;
    result = someMethod2(var1, var2);
    assert.ok(result);
  }
}

いろんな使い方

__get__以外に, __set__というものがあるので、それを使えばStubやMockも可能になる。

以下サンプルで、someMethod2のreturn値を変える。

test.js
describe('#someMethod2', function () ) {
  it('should ok', function (done) ) {
    var something = rewire('something.js')
      , someMethod2 = something.__get__('someMethod2')
      , result = null
      , stubMethod = null
      ;

    stubMethod = function () {
      return false;
    }
    something.__set__({
      'someMethod2': stubMethod
    });
    result = someMethod2(var1, var2) // resultがfalseになる
    // 省略
  }
}
35
25
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
35
25