我使用moment.js在我的React组件的帮助文件中做大部分的日期逻辑,但我还没有弄清楚如何在Jest a la sinon.useFakeTimers()中模拟日期。

Jest文档只谈到了计时器函数,如setTimeout, setInterval等,但没有帮助设置日期,然后检查我的日期函数是否做了他们应该做的事情。

这是我的一些JS文件:

var moment = require('moment');

var DateHelper = {
  
  DATE_FORMAT: 'MMMM D',
  API_DATE_FORMAT: 'YYYY-MM-DD',
  
  formatDate: function(date) {
    return date.format(this.DATE_FORMAT);
  },

  isDateToday: function(date) {
    return this.formatDate(date) === this.formatDate(moment());
  }
};


module.exports = DateHelper;

这是我用Jest设置的:

jest.dontMock('../../../dashboard/calendar/date-helper')
    .dontMock('moment');

describe('DateHelper', function() {
  var DateHelper = require('../../../dashboard/calendar/date-helper'),
      moment = require('moment'),
      DATE_FORMAT = 'MMMM D';

  describe('formatDate', function() {

    it('should return the date formatted as DATE_FORMAT', function() {
      var unformattedDate = moment('2014-05-12T00:00:00.000Z'),
          formattedDate = DateHelper.formatDate(unformattedDate);

      expect(formattedDate).toEqual('May 12');
    });

  });

  describe('isDateToday', function() {

    it('should return true if the passed in date is today', function() {
      var today = moment();

      expect(DateHelper.isDateToday(today)).toEqual(true);
    });
    
  });

});

现在这些测试通过了,因为我使用了moment,我的函数也使用了moment,但它似乎有点不稳定,我想将日期设置为测试的固定时间。

你知道该怎么做吗?


当前回答

我只是想在这里插一句,因为如果您只想在特定的套件中模拟Date对象,那么没有答案可以解决这个问题。

您可以使用每个套件的设置和拆卸方法来模拟它,jest文档

/**
 * Mocking Date for this test suite
 */
const globalDate = Date;

beforeAll(() => {
  // Mocked Date: 2020-01-08
  Date.now = jest.fn(() => new Date(Date.UTC(2020, 0, 8)).valueOf());
});

afterAll(() => {
  global.Date = globalDate;
});

希望这能有所帮助!

其他回答

我想使用手动模拟,所以它可以在所有测试中使用。

// <rootDir>/__mocks__/moment.js
const moment = jest.requireActual('moment')

Date.now = jest.fn(() => 1558281600000) // 2019-05-20 00:00:00.000+08:00

module.exports = moment

我想提供一些替代方法。

如果你需要存根格式()(可以是地区和时区相关!)

import moment from "moment";
...
jest.mock("moment");
...
const format = jest.fn(() => 'April 11, 2019')
moment.mockReturnValue({ format })

如果你只需要stub moment():

import moment from "moment";
...
jest.mock("moment");
...
const now = "moment(\"2019-04-11T09:44:57.299\")";
moment.mockReturnValue(now);

关于上面isDateToday函数的测试,我认为最简单的方法是根本不模拟moment

我推荐sinonjs/fake-timers。它与jest提供的假计时器非常相似,但用户友好得多。

import FakeTimers from '@sinonjs/fake-timers';

const clock = FakeTimers.install()
clock.setSystemTime(new Date('2022-01-01'));

console.log(new Date()) // 2020-01-01T00:00:00.000Z

你可以用date-faker。允许您相对地更改当前日期:

import { dateFaker } from 'date-faker';
// or require if you wish: var { dateFaker } = require('date-faker');

// make current date to be tomorrow
dateFaker.add(1, 'day'); // 'year' | 'month' | 'day' | 'hour' | 'minute' | 'second' | 'millisecond'.

// change using many units
dateFaker.add({ year: 1, month: -2, day: 3 });

// set specific date, type: Date or string
dateFaker.set('2019/01/24');

// reset
dateFaker.reset();

@pranava-s-balugari的回复有所改善

它不影响新日期(某事) 模拟日期可以更改。 它将工作日期。现在太

const DateOriginal = global.Date;

global.Date = class extends DateOriginal {
    constructor(params) {
        if (params) {
          super(params)
        } else if (global.Date.NOW === undefined) {
          super()
        } else {
          super(global.Date.NOW)
        }
    }
    static now () {
      return new Date().getTime();
    }
}

afterEach(() => {
  global.Date.NOW = undefined;
})

afterAll(() => {
  global.Date = DateOriginal;
});

describe('some test', () => {
  afterEach(() => NOW = undefined);

  it('some test', () => {
     Date.NOW = '1999-12-31T23:59:59' // or whatever parameter you could pass to new Date([param]) to get the date you want


     expect(new Date()).toEqual(new Date('1999-12-31T23:59:59'));
     expect(new Date('2000-01-01')).toEqual(new Date('2000-01-01'));
     expect(Date.now()).toBe(946681199000)

     Date.NOW = '2020-01-01'

     expect(new Date()).toEqual(new Date('2020-01-01'));
  })
})