gpt4 book ai didi

javascript - 使用 jest 模拟 moment() 和 moment().format

转载 作者:行者123 更新时间:2023-12-03 13:25:34 26 4
gpt4 key购买 nike

我无法模拟 moment()moment().format 函数。我的状态是,currentDateMomentcurrentDateFormatted 设置如下。

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com