如何在jest中模拟Date.toLocaleDateString?

rslzwgfq  于 9个月前  发布在  Jest
关注(0)|答案(4)|浏览(96)

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

new Date(createDate).toLocaleDateString()

字符串
我的本地机器和我们的构建机器设置了不同的locale,所以这个函数的结果不一致。所以正如你所期望的,单元测试在我的机器上通过,在构建机器上失败,反之亦然。
我想模拟“toLocalDateString”,使它总是使用相同的locale,比如'en-US',或者至少总是返回相同的字符串。我们的测试框架是jest。我如何实现这个目标?
我在我的test.spec.js中尝试了这一点,但它没有任何效果:

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


我仍然在快照中得到相同的旧toLocalDateString实现,我的mockReturnValue没有被考虑在内。

lymgl2op

lymgl2op1#

我可能会晚一点,但希望它能帮助别人。

let mockDate;

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

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

字符串

fnx2tebb

fnx2tebb2#

你能把

new Date(createDate).toLocaleDateString()

字符串
在一个函数中,将它作为属性传递给组件,然后模拟它?

vawmfj5a

vawmfj5a3#

如果你想响应当前日期,但选择一个替代的(固定的)区域设置,我发现这很好用。你可以把它放在测试文件或setupTests.js/ts文件中来应用它:

const origDate = global.Date.prototype.toLocaleDateString;
jest.spyOn(global.Date.prototype, 'toLocaleDateString').mockImplementation(function () { 
  return origDate.call(this, 'en-US');
});

字符串
这个例子将所有localeDateString输出修复为en-US。注意,你必须使用function(){}而不是()=>{},因为你依赖于this由调用者正确设置。

lvjbypge

lvjbypge4#

下面的代码对你有用吗?我用这种方式模拟日期对象。

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;

字符串

相关问题