简体   繁体   English

Mocking 开玩笑的日期

[英]Mocking date in jest

I have function called setMockDate that looks like:我有名为setMockDate的 function 看起来像:

/**
 * @param {Date} expected
 * @returns {Function} Call to remove Date mocking
 */
const setMockDate = (expected: Date): AnyObject => {
  const RealDate = Date
  function MockDate(mockOverride?: Date | number) {
    return new RealDate(mockOverride || expected)
  }

  MockDate.UTC = RealDate.UTC
  MockDate.parse = RealDate.parse
  MockDate.now = () => expected.getTime()
  MockDate.prototype = RealDate.prototype

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  global.Date = MockDate as any

  return () => {
    global.Date = RealDate
  }
}

export default setMockDate

and used like:并使用如下:

test('Should change date', () => {
  const mockDate = new Date('Feb 22, 2021 11:59:00')
  setMockDate(mockDate)
  expect(new Date()).toEqual(mockDate)
})

I wanted to change the MockDate function in setMockDate() to use an arrow function like:我想更改MockDate setMockDate()中的 MockDate function 以使用箭头 function ,例如:

const MockDate = (mockOverride?: Date | number) => {
  return new RealDate(mockOverride || expected)
}

However I get TypeError :但是我得到TypeError

TypeError: Date is not a constructor

Why I am getting this error when changing to use an arrow function?为什么在更改为使用箭头 function 时出现此错误?

MockDate is supposed to mimic new Date() which is a constructor and arrow function cannot be used as a constructor MockDate应该模仿new Date()这是一个constructor和箭头 function 不能用作constructor

More information here:更多信息在这里:

I updated my helper function to:我将我的助手 function 更新为:

import { AnyObject } from 'typings/custom'

/**
 * @param {Date} expected
 * @returns {Function} Call to remove Date mocking
 */
const setMockDate = (expected: Date): AnyObject => {
  const RealDate = Date

  function MockDate(mockOverride?: Date | number) {
    return new RealDate(mockOverride || expected)
  }

  MockDate.now = () => expected.getTime()
  MockDate.prototype = RealDate.prototype

  // eslint-disable-next-line @typescript-eslint/no-explicit-any
  global.Date = MockDate as any

  return () => {
    global.Date = RealDate
  }
}

export default setMockDate

Using this helper looks like:使用这个助手看起来像:

/**
 * Testing a component that changes text based on time of day
 * ie: good morning, good afternoon & good evening
 */
describe('Greeting', () => {
  it('Should update message after time', () => {
    jest.useFakeTimers()
    setMockDate(new Date('Feb 22, 2021 11:59:00'))
    const wrapper = mount(<Greeting />)

    const greetingText = wrapper.text()
    setMockDate(new Date('Feb 22, 2021 12:00:00'))
    jest.advanceTimersByTime(60000)
    expect(wrapper.text()).not.toBe(greetingText)
  })

})

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM