Date mock with two or more tests

拜拜、爱过 提交于 2021-02-19 08:17:07

问题


We are using jest for mocking. I have a function which will greet us based on the time that file looks like below:

export default function getGreetingMessage() {
  const today = new Date();
  const curHr = today.getHours();

  if (curHr < 12) {
      return 'Good morning';
  } else if (curHr < 18) {
      return 'Good afternoon';
  }
  return 'Good evening';
}

And My test file will look like below

import getGreetingMessage from '../messages';

describe('messages', () => {
 function setup(date) {
  const DATE_TO_USE = new Date(date);
  global.Date = jest.fn(() => DATE_TO_USE);
 }
 it('should return good afternoon when time is greater than 12', () => {
  setup('Tue Oct 16 2018 15:49:11');
  expect(getGreetingMessage()).toEqual('Good afternoon');
});

it('should return good morning when time is less than 12', () => {
  setup('Tue Oct 16 2018 10:49:11');
  expect(getGreetingMessage()).toEqual('Good morning');
});

it('should return good evening when time is greater than than 19', () => {
  setup('Tue Oct 16 2018 19:49:11');
  expect(getGreetingMessage()).toEqual('Good evening');
});
});

When I ran each test individually it's working fine. When I ran all at a time then tests are failing.

I tried resetting the jest function. But not working.

Are there any other ways to try?

Thanks in advance :)


回答1:


This is bad practice to assign a mock to a global because it cannot be cleaned up:

global.Date = jest.fn(() => DATE_TO_USE);

Unmocked Date won't be available on subsequent setup calls:

const DATE_TO_USE = new Date(date);

It's unnecessary to provide the implementation with jest.fn, it can be changed per test. Since it's Date object that is expected, original Date may be used to create instances:

const OriginalDate = Date;

beforeEach(() => {
  jest.spyOn(global, 'Date');
});

it('', () => {
  Date.mockImplementation(() => new OriginalDate('Tue Oct 16 2018 15:49:11'));
  expect(getGreetingMessage()).toEqual('Good afternoon');
});


来源:https://stackoverflow.com/questions/52828824/date-mock-with-two-or-more-tests

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!