我在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没有被考虑在内。
4条答案
按热度按时间lymgl2op1#
我可能会晚一点,但希望它能帮助别人。
字符串
fnx2tebb2#
你能把
字符串
在一个函数中,将它作为属性传递给组件,然后模拟它?
vawmfj5a3#
如果你想响应当前日期,但选择一个替代的(固定的)区域设置,我发现这很好用。你可以把它放在测试文件或
setupTests.js/ts
文件中来应用它:字符串
这个例子将所有localeDateString输出修复为
en-US
。注意,你必须使用function(){}
而不是()=>{}
,因为你依赖于this
由调用者正确设置。lvjbypge4#
下面的代码对你有用吗?我用这种方式模拟日期对象。
字符串