Search code examples
typescriptsinon

Ensure new Date() value in sinon test matches value in code


Apologies if this is a real basic request, I am relatively new to sinon and I have struggled to find anyone trying to do exactly what I am doing.

In my code, I am generating an ISO string using new Date() if there is no value:

const toDateTimeParameter: string = encodeURIComponent(new Date().toISOString());

In my test, I am also generating a new Date() value to compare with:

const toDateTime: string = encodeURIComponent(new Date().toISOString());

You might be able to see where this is going, but as these Date instances are not generated at exactly the same time, they don't match (1-2ms out). Obviously it is hard to predict the exact variance (and I'd rather not do that anyway), so is there a way to line up the two values?

Example failure:

AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual

- 'https://example.com(fromDateTime=2019-11-01,toDateTime=2020-12-16T21%3A48%3A00.520Z)'
+ 'https://example.com(fromDateTime=2019-11-01,toDateTime=2020-12-16T21%3A48%3A00.519Z)'
      + expected - actual

Solution

  • Sinon provides a utility called fake timers that allow you control date and time. You can create a date and pass that date to useFakeTimers to specify what the date/time should be for that test:

    afterEach(() => {
      // need to restore if you want date to not be stubbed by sinon
      sinon.restore();
    });
    
    it('should do something', () => {
      // create a date to indicate current date/time
      const now = new Date();
      // pass that date to useFakeTimers
      sinon.useFakeTimers(now);
      const expected = toDateTime();
      const actual = now.toISOString();
      assert.strictEqual(actual, expected); // or whatever assertion you do
    });
    

    Hopefully that helps!