Pravesh Jain
Pravesh Jain

Reputation: 4288

Mocking the current time in sinon

I am writing integration tests for my application that uses connects to MongoDB. I write the entity creation time to DB and use Date.now() for that. My application is time-sensitive and hence I want to mock the current time such that my tests always work. I have tried examples shared on multiple other similar posts but not able to get a working solution for me.

I try adding

const date = new Date()
date.setHours(12)
sandbox.stub(Date, "now").callsFake(function() {return date.getTime()})

in my beforeEach method but it has no impact.

I also tried

const date = new Date()
date.setHours(12)

sinon.useFakeTimers({
    now: date,
    shouldAdvanceTime: true
})

But this throws my mongoose schema validation for a toss and throws

Invalid schema configuration: ClockDate is not a valid type at path createdDate

What is the right way to achieve this?

Upvotes: 0

Views: 1669

Answers (2)

Pravesh Jain
Pravesh Jain

Reputation: 4288

The usage of useFakeTimers was doing what it intended to do. However, mongoose type comparison was failing as it does type comparison by checking the names. The solution turned out to add ClockDate as a known type in mongoose inside the sandbox.

Adding the following line in the before method worked.

import { SchemaTypes } from "mongoose"
SchemaTypes["ClockDate"] = SchemaTypes.Date

Upvotes: 2

Lin Du
Lin Du

Reputation: 102237

Here is a way to make a stub for Date.now():

main.ts:

export function main() {
  return Date.now();
}

main.test.ts:

import { main } from "./main";
import sinon from "sinon";
import { expect } from "chai";

describe("59635513", () => {
  afterEach(() => {
    sinon.restore();
  });
  it("should pass", () => {
    const mDate = 1000 * 1000;
    const dateNowStub = sinon.stub(Date, "now").returns(mDate);
    const actual = main();
    expect(actual).to.be.eq(mDate);
    sinon.assert.calledOnce(dateNowStub);
  });
});

Unit test results with coverage report:


  59635513
    ✓ should pass


  1 passing (8ms)

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |      100 |      100 |      100 |      100 |                   |
 main.test.ts |      100 |      100 |      100 |      100 |                   |
 main.ts      |      100 |      100 |      100 |      100 |                   |
--------------|----------|----------|----------|----------|-------------------|

Source code: https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/stackoverflow/59635513

Upvotes: 0

Related Questions