0

This feels like it's nowhere near as difficult as I'm making it. Here is a little (heavily simplified) function as an example:

dateCalculator.js

const today = new Date();
const deliveryDate = new Date();

deliveryDate.setDate(today.getDate() + 3);

export const dateCalculator = () => {
  return `${deliveryDate.toLocaleString('en-GB', { weekday: 'long' })}`;
};

So this function grabs today's date, adds three days to it and then returns the day of the week. Obvs, I'm going to test it:

dateCalculator.spec.js

import { dateCalculator } from './dateCalculator';

describe('dateCalculator', () => {
  it('should return the correct day of the week', () => {
    expect(dateCalculator()).toBe('Thursday');
  });
});

This test passes, but it will only pass when it is run on a Monday.

How do I force the variable today to be a specific date which I can control from the test? I can't work out how to mock this single variable.

Sternjobname
  • 740
  • 1
  • 10
  • 23
  • Hi, have you tried this? [so answer](https://stackoverflow.com/a/65548068/6262162) – SakisTsalk Jul 12 '21 at 10:07
  • @sakisTsalk I have, but unfortunately the organisation I'm working for is on 25.5.4 which isn't new enough to support that... :( – Sternjobname Jul 12 '21 at 10:10
  • 1
    Alright, still I would suggest looking at other answers on that thread. – SakisTsalk Jul 12 '21 at 10:13
  • I have done actually - it was one of the threads I found before writing the question. Although using the accepted answer does have an affect when I use it in isolation in the test, it has no affect on what is returned from the `deliveryDate.js` file which is what I'm looking for help with. How do I force the `today` variable to be a date I control from within the test file? – Sternjobname Jul 12 '21 at 10:17

1 Answers1

1

And of course, it was something I was doing wrong; this does work:

dateCalculator.spec.js

  it('should return a date in the expected format', () => {
    const mockDate = new Date(1466424490000);
    const spy = jest.spyOn(global, 'Date').mockImplementation(() => mockDate);
    expect(dateCalculator()).toBe('Thursday');
    spy.mockRestore();
  });

it wasn't working because I wasn't instantiating today within the dateCalculator function. Putting everything inside the function body resolves this:

dateCalculator.js

export const dateCalculator = () => {
  const today = new Date();
  const deliveryDate = new Date();

  deliveryDate.setDate(today.getDate() + 3);

  return `${deliveryDate.toLocaleString('en-GB', { weekday: 'long' })}`;
};
Sternjobname
  • 740
  • 1
  • 10
  • 23