I have function called setMockDate
that looks like:
/**
* @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:
const MockDate = (mockOverride?: Date | number) => {
return new RealDate(mockOverride || expected)
}
However I get TypeError
:
TypeError: Date is not a constructor
Why I am getting this error when changing to use an arrow function?
MockDate
is supposed to mimic new Date()
which is a constructor
and arrow function cannot be used as a constructor
More information here:
I updated my helper function to:
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)
})
})
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.