具有两个或多个测试的日期模拟 [英] Date mock with two or more tests

查看:44
本文介绍了具有两个或多个测试的日期模拟的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们在开玩笑地开玩笑. 我有一个可以根据时间打招呼的功能 该文件如下所示:

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';
}

我的测试文件如下所示

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.

还有其他尝试方法吗?

先谢谢您了:)

推荐答案

将模拟分配给全局是一种不好的做法,因为它无法清理:

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

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

未经模拟的Date在以后的setup调用中将不可用:

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

const DATE_TO_USE = new Date(date);

不必为实现提供jest.fn,可以根据每次测试对其进行更改.由于应该是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');
});

这篇关于具有两个或多个测试的日期模拟的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆