Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I stub new Date() using sinon?

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.

like image 859
MrHen Avatar asked Jul 23 '15 14:07

MrHen


People also ask

What is Sinon stub ()?

The sinon. stub() substitutes the real function and returns a stub object that you can configure using methods like callsFake() . Stubs also have a callCount property that tells you how many times the stub was called.

How do you stub a promise in Sinon?

To stub a promise with sinon and JavaScript, we can return a promise with a stub. import sinon from "sinon"; const sandbox = sinon. sandbox. create(); const promiseResolved = () => sandbox.

What is stub method in JavaScript?

What are Stubs? A test stub is a function or object that replaces the actual behavior of a module with a fixed response. The stub can only return the fixed response it was programmed to return.


1 Answers

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(); }); 
like image 81
Alex Booker Avatar answered Sep 17 '22 15:09

Alex Booker