【问题标题】:Date mock with two or more tests使用两个或更多测试进行日期模拟
【发布时间】:2019-03-20 14:16:50
【问题描述】:

我们使用 jest 来模拟。 我有一个功能会根据时间向我们打招呼 该文件如下所示:

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

当我单独运行每个测试时,它工作正常。当我一次运行所有测试时,测试失败了。

我尝试重置 jest 功能。但不工作。

还有其他方法可以尝试吗?

提前谢谢:)

【问题讨论】:

  • 调试输出 console.log(today) 并确保它是一个笑话。
  • 哈,当我运行每个测试时,它给了我一个嘲笑的结果。当我一起运行所有测试时,它给出了正常的日期

标签: javascript reactjs mocking jestjs


【解决方案1】:

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

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

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

const DATE_TO_USE = new Date(date);

没有必要为实现提供jest.fn,它可以在每个测试中更改。由于预期的是Date 对象,因此可以使用原始Date 来创建实例:

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

【讨论】:

  • Date.mockReturnedValue 抛出错误。它表明 Date.mockReturnedValue 不起作用。
  • 这是一个错字。
  • 真的有用吗?我在 TypeScript 中使用上面的代码,但得到了Property 'mockReturnValue' does not exist on type 'DateConstructor'.ts(2339)
  • @choasia 这个问题不涉及TS,难怪代码会导致类型问题。尝试断言一个类型,(Date as jest.Mock).mockReturnValue(...)
  • @estus 啊哈,它现在可以工作了。太感谢了。顺便说一句,我决定使用const dateToUse = new Date("Tue Oct 16 2018 11:49:11"); jest.spyOn(global, "Date").mockImplementation(() =&gt; dateToUse); 来避免上面的类型问题。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-03-23
  • 1970-01-01
  • 2015-07-27
  • 2022-01-20
  • 2011-05-25
相关资源
最近更新 更多