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 pathcreatedDate
What is the right way to achieve this?
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