Sinon.JSのuseFakeTimersを教えてもらった

ということがあって、HipChat上に投げたら、sinon.useFakeTimersつかってないの?というツッコミがあったので、そんなのあるんだと。ちょっと使ってみました。 あら便利

http://sinonjs.org/ を見てみると JavaScript test spies, stubs and mocks.らしい。ちなみにバージョンは1.14.1で動かしてます。

var sinon = require('sinon');
describe('test', function() {
  describe('sub-test', function() {
    var sandbox;
    beforeEach(function(done) {
      sandbox = sinon.sandbox.create(); // sandbox でまとめて管理
      sandbox.useFakeTimers(new Date(2000, 0, 1).getTime());
      done();
    });

    it('call new Date', function(done) {
      console.log(new Date());
      done();
    });

    it('call new Date2', function(done) {
      console.log(new Date());
      done();
    });

    afterEach(function(done) {
      sandbox.restore();
      console.log('afterEach', new Date());
      done();
    });
  });
});

で動かすと、

  test
    sub-test
Sat Jan 01 2000 00:00:00 GMT+0900 (JST)
      ✓ call new Date
afterEach Thu May 21 2015 23:02:23 GMT+0900 (JST)
Sat Jan 01 2000 00:00:00 GMT+0900 (JST)
      ✓ call new Date2
afterEach Thu May 21 2015 23:02:23 GMT+0900 (JST)


  2 passing (14ms)