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

标签 javascript reactjs unit-testing jestjs momentjs

我无法模拟 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/

相关文章:

javascript - AJAX 函数没有从它调用的函数接收返回数据

javascript - 尝试将获取的 json 数据映射到 React 应用程序时,"State"未定义

javascript - typescript 和@types/react 错误

javascript - input 的 event.target 在 this.setState [React.js] 中为 null

java - 模拟外部服务返回 null

unit-testing - 如何使用@testing-library/react-native 监视 React Native 中的 TouchableNativeFeedback onPress?

c# - 比较具有不同项目类型的集合

javascript - 带有 JavaScript 的日期时间范围分隔符适用于除少数范围之外的所有范围

reactjs - 为什么 react-sortable-hoc 基本示例无法使用 typescript 进行编译?

javascript - 通过Java脚本暂停youtube视频