我无法模拟 moment()
或 moment().format
函数。我的状态是,currentDateMoment
和 currentDateFormatted
设置如下。
currentDateMoment: moment() //2019-04-23T17:45:26.339Z
currentDateFormatted: moment().format('MM-DD-YYYY').valueOf() //"04-23-2019"
尝试在我的快照测试中模拟 moment()
和 moment().format
以返回特定日期,但无法。尝试如下。
jest.mock('moment', () => () => '2018–01–30T12:34:56+00:00');
jest.mock('moment', () => ({
constructor: () => '2018–01–30T12:34:56+00:00'
}));
jest.mock('moment', () => () => ({ format: () => '01–30-2018' }));
最佳答案
模拟 moment() 及其使用的任何函数(即 .day()
、.format()
)的最简单方法是更改
moment()
在底层使用的日期
将下面的代码片段添加到您的测试文件中
Date.now = jest.fn(() => new Date("2020-05-13T12:33:37.000Z"));
这使得每当在测试中调用 moment()
时,moment()
都会认为今天是 2020 年 5 月 13 日星期三
关于javascript - 使用 jest 模拟 moment() 和 moment().format,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55838798/