使用玩笑嘲笑一下moment()和moment().format [英] Mocking moment() and moment().format using jest

查看:295
本文介绍了使用玩笑嘲笑一下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"

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返回特定日期,然后不必模拟format.

You can mock Moment to return a specific date, then format don't have to be mocked.

jest.mock('moment', () => {
  return () => jest.requireActual('moment')('2020-01-01T00:00:00.000Z');
});

这样做,对Moment()的任何调用都将始终返回一个时刻对象,该对象的日期设置为 2020-01-01 00:00:00

By doing so, any call to Moment() will always return a moment object with date set to 2020-01-01 00:00:00

下面是一个示例函数,该函数返回明天的日期和对该函数的测试.

Here is an example with a function that return the date of tomorrow and the test for this function.

const moment = require('moment');
const tomorrow = () => {
  const now = moment();
  return now.add(1, 'days');
};

describe('tomorrow', () => {
  it('should return the next day in a specific format', () => {
    const date = tomorrow().format('YYYY-MM-DD');
    expect(date).toEqual('2020-01-02');
  });
});

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

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