1

The goal is to mock the javascript Date object so that when I run my tests and snapshots are evaluated, the snapshot is not always failing.

I am attempting to write a Jest test for a function that utilizes the new Date constructor in a Vue 2.6.8 app (this is a Typescript project).

I have bound a variable called maxDate to the component. It uses a getter to compute the value as needed. The goal is to limit the date pickers' selectable range. Here is what the code looks like:

Vue Template:

<template>
  <date-picker :max-date="maxDate" />
</template>

Vue class method:

private get maxDate() {
  return new Date();
}

Jest Test (to match snapshot):

describe('Snapshots', () => {
  test('snapshot 1', () => {
    expect(component.vm.$el).toMatchSnapshot();
  });
});

The question I have is: How do I prevent my snapshots from failing since the date is going to change every time I run my tests?

For example, the first time I run the test and the snapshot is generated, I get something like this in the snapshot itself.

First run (generate snapshot):

...
maxdate="Wed Oct 30 2019 12:27:08 GMT-0700 (Pacific Daylight Time)"
...

And the next time I run the tests - say exactly one minute later - the snapshot will fail because it will be expecting the previous date but is now getting different data.

Second run (snapshot fails):

...
maxdate="Wed Oct 30 2019 12:28:08 GMT-0700 (Pacific Daylight Time)"
...
skyboyer
  • 22,209
  • 7
  • 57
  • 64
Moose
  • 1,270
  • 2
  • 19
  • 33
  • Did you get a solution? I have mocked `Date` constructor but in my Vue component computed still gets original `Date` object and fails the test :-/ – Adam Orłowski Dec 04 '19 at 20:46

0 Answers0