我如何在玩笑中模拟 Date.toLocaleDateString? [英] How do I mock Date.toLocaleDateString in jest?

查看:25
本文介绍了我如何在玩笑中模拟 Date.toLocaleDateString?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have this codepiece in my React component, which renders an HTML in the end:

new Date(createDate).toLocaleDateString()

我的本​​地机器和我们的构建机器设置了不同的语言环境,所以这个函数的结果是不连贯的.因此,如您所料,单元测试在我的机器上通过,在构建机器上失败,反之亦然.

My local machine and our build machine have different locales set, so the result of this function is not coherent. So as you'd expect, the unit test passes on my machine and fails on build machine, or vice versa.

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

I want to mock "toLocalDateString" so that it always uses the same locale, say 'en-US', or at least it always returns the same string. Our test framework is jest. How do I achieve this goal?

我在我的 test.spec.js 中尝试了这个,但它根本没有任何效果:

I tried this in my test.spec.js but it didn't have any effect at all:

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

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

I still get the same old toLocalDateString implementation in the snapshot, my mockReturnValue is not taken into account.

推荐答案

可能有点晚了,但希望对大家有所帮助

I may be a bit late but hope it helps someone

let mockDate;

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

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

这篇关于我如何在玩笑中模拟 Date.toLocaleDateString?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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