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.
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.
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 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.
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(); });
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With