2015-07-23 18 views
13

Voglio verificare che i vari campi data siano stati aggiornati correttamente, ma non voglio scherzare con la predizione quando è stato chiamato new Date(). Come faccio a spegnere il costruttore Date?Come posso stubare nuovo Date() usando sinon?

import sinon = require('sinon'); 
import should = require('should'); 

describe('tests',() => { 
    var sandbox; 
    var now = new Date(); 

    beforeEach(() => { 
    sandbox = sinon.sandbox.create(); 
    }); 

    afterEach(() => { 
    sandbox.restore(); 
    }); 

    var now = new Date(); 

    it('sets create_date', done => { 
    sandbox.stub(Date).returns(now); // does not work 

    Widget.create((err, widget) => { 
     should.not.exist(err); 
     should.exist(widget); 
     widget.create_date.should.eql(now); 

     done(); 
    }); 
    }); 
}); 

Nel caso in cui sia pertinente, questi test sono in esecuzione in un'app nodo e usiamo TypeScript.

risposta

33

ho sospetto si desidera che la funzione useFakeTimers:

var now = new Date(); 
var clock = sinon.useFakeTimers(now.getTime()); 
//assertions 
clock.restore(); 

Questo è normale JS. Un esempio TypeScript/JavaScript funzionante:

var now = new Date(); 

beforeEach(() => { 
    sandbox = sinon.sandbox.create(); 
    clock = sinon.useFakeTimers(now.getTime()); 
}); 

afterEach(() => { 
    sandbox.restore(); 
    clock.restore(); 
}); 
+0

Impressionante, sembra che faccia ciò di cui avevo bisogno. Una volta ottenuta una versione funzionante, la modifico nella tua risposta e la accetto. – MrHen

Problemi correlati