我在我的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实现,未考虑我的模拟返回值。
new Date(createDate).toLocaleDateString()
在一个函数中,将它作为prop传递给组件,然后对其进行模拟?
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;