使用 jest 模拟 moment() 和 moment().format [英] Mocking moment() and moment().format using jest

查看:49
本文介绍了使用 jest 模拟 moment() 和 moment().format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm unable to mock moment() or moment().format functions. I have states where, currentDateMoment and currentDateFormatted are getting set as below.

currentDateMoment: moment() //2019-04-23T17:45:26.339Z
currentDateFormatted: moment().format('MM-DD-YYYY').valueOf() //"04-23-2019"

尝试在我的快照测试中模拟 moment()moment().format 以返回特定日期,但无法做到.下面试过.

Trying to mock both moment() and moment().format in my snapshot tests to return a particular date, but was unable to. Tried below.

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

The easiest way to mock moment() and any function that it uses (i.e. .day(), .format()) is to change the Date that moment() uses under the hood

在您的测试文件中添加以下代码片段

Add the snippet below inside your test file

Date.now = jest.fn(() => new Date("2020-05-13T12:33:37.000Z"));

这使得任何时候 moment() 在您的测试中被调用,moment() 认为今天是 2020 年 5 月 13 日,星期三

This makes it so anytime moment() is called in your tests, moment() thinks that today is Wednesday, May 13th 2020

这篇关于使用 jest 模拟 moment() 和 moment().format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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