Search code examples
javascriptjestjs

Tests on jest and new Date()


I'm trying to test function similar on this:

function foo() {
    return {
        key_a: "val_a",
        key_b: new Date()
};

How can I make an expected object for test for this case?

const expectedObject = {
    key_a: "val_a",
    key_b: new Date()
}
expect(foo()).toEqual(expectedObject)?
- Expected
+ Received
- "key_b": 2019-01-23T14:04:03.060Z,
+ "key_b": 2019-01-23T14:04:03.061Z,

Solution

  • There are various approaches to this, many are discussed in this thread.

    Probably the most simple and clean approach in this case is to spy on Date and get what was returned from new Date() using mockFn.mock.instances like this:

    function foo() {
      return {
        key_a: "val_a",
        key_b: new Date()
      };
    }
    
    test('foo', () => {
      const spy = jest.spyOn(global, 'Date');  // spy on Date
      const result = foo();  // call foo
      const date = spy.mock.instances[0];  // get what 'new Date()' returned
      const expectedObject = {
        key_a: "val_a",
        key_b: date  // use the date in the expected object
      };
      expect(result).toEqual(expectedObject);  // SUCCESS
    })