LoginSignup
1
1

More than 5 years have passed since last update.

現在時刻に依存したモジュールのテスト

Last updated at Posted at 2013-10-06

現在時刻に依存するモジュールでテストを書く場合、まあ Mock ライブラリを使えばいいんだけど

  • 数行程度のモジュール
  • テスト環境を最小限にしたい(普段の環境以外でテストさせたい)

とかいう場合のサンプル。というかメモ。
やってることは簡単で、テスト期間限定で Date.prototype の メソッドをオーバーライドして 期待値を返すようにするだけ。今回はスタブ(?)の手法を使う。

stub.js
var test = require('tape')

test('stub for Date#toString', function (t) {
    t.test('hook .toString', function (tt) {
        var stub = {}
        var toString

        function setup () {
            toString = Date.prototype.toString
            Date.prototype.toString = function () { return stub.time }
        }
        function teardown () {
            Date.prototype.toString = toString
            stub.time = null
        }
        function subtest (time) {
            stub.time = time
            tt.equal((new Date).toString(), time
              , '(new Date).toSting() === "' + time + '"')
        }

        setup()
        subtest(12)
        subtest('hoge')
        teardown()

        tt.end()
    })

    t.test('reset .toString', function (tt) {
        var d = new Date
        var str = d.toString()
        tt.ok(/\d\d:\d\d:\d\d\sGMT[+-]\d\d\d\d/.test(str)
          , '(new Date).toString() === "' + str + '"')
        tt.end()
    })

    t.end()
})

テスト結果

result.txt
TAP version 13
# stub
# hook .toString
ok 1 (new Date).toSting() === "12"
ok 2 (new Date).toSting() === "hoge"
# reset .toString
ok 3 (new Date).toString() === "Sun Oct 06 2013 16:56:13 GMT+0900 (JST)"

1..3
# tests 3
# pass  3

# ok
ok      127 ms
All tests successful.
Files=1, Tests=3,  0 wallclock secs ( 0.06 usr  0.01 sys +  0.06 cusr  0.02 csys =  0.15 CPU)
Result: PASS
1
1
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
1
1