如何在玩笑中模拟Date.toLocaleDateString?

时间:2020-04-15 09:06:14

标签: javascript reactjs unit-testing jestjs

我的React组件中有这个代码段,它最终呈现了一个HTML:

new Date(createDate).toLocaleDateString()

我的本​​地计算机和构建计算机的区域设置不同,因此此功能的结果不一致。因此,正如您所期望的,单元测试在我的计算机上通过,而在构建计算机上失败,反之亦然。

我想模拟“ toLocalDateString”,以便它始终使用相同的语言环境,例如“ en-US”,或者至少它始终返回相同的字符串。我们的测试框架是开玩笑。我如何实现这个目标?

我在test.spec.js中尝试了此操作,但它根本没有任何作用:

Date.prototype.toLocaleDateString = jest.fn().mockReturnValue('2020-04-15')
expect(component).toMatchSnapshot()

我仍然在快照中得到相同的toLocalDateString实现,未考虑我的模拟返回值。

3 个答案:

答案 0 :(得分:0)

可以包装

new Date(createDate).toLocaleDateString()

在函数中,将其作为prop传递给组件,然后对其进行模拟?

答案 1 :(得分:0)

我可能有点晚了,但希望它对某人有帮助

let mockDate;

beforeAll(() => {
  mockDate = jest.spyOn(Date.prototype, 'toLocaleTimeString').mockReturnValue('2020-04-15');
});

afterAll(() => {
  mockDate.mockRestore();
});

答案 2 :(得分:-1)

心爱的代码对您来说是否运作良好?我以这种方式嘲笑日期对象。

const realDateToLocaleDateString = Date.prototype.toLocaleDateString.bind(global.Date);
const toLocaleDateStringStub = jest.fn(() => '2020-04-15');
global.Date.prototype.toLocaleDateString = toLocaleDateStringStub;

const date = new Date();
console.log(date.toLocaleDateString()); // returns 2020-04-15

global.Date.prototype.toLocaleDateString = realDateToLocaleDateString;