Sunday, June 2, 2024
 Popular · Latest · Hot · Upcoming
131
rated 0 times [  137] [ 6]  / answers: 1 / hits: 43921  / 9 Years ago, thu, july 23, 2015, 12:00:00

I want to verify that various date fields were updated properly but I don't want to mess around with predicting when new Date() was called. How do I stub out the Date constructor?



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();
});
});
});


In case it is relevant, these tests are running in a node app and we use TypeScript.


More From » testing

 Answers
169

I suspect you want the useFakeTimers function:





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


This is plain JS. A working TypeScript/JavaScript example:



var now = new Date();

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

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

[#65702] Wednesday, July 22, 2015, 9 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
stephonkeandrer

Total Points: 392
Total Questions: 94
Total Answers: 100

Location: Tajikistan
Member since Sun, Aug 29, 2021
3 Years ago
;