Я пытаюсь правильно смоделировать Date с помощью jest и typcript, чтобы протестировать некоторые функции, которые регистрируют метки времени.
Я набрал следующий код, чтобы смоделировать дату
// Mocks date time
export const defaultInitialDate = new Date('2020-03-03T16:22:09.375Z')
/**
* Mock date funciton
* @param durations an array of durations in MS from initial date that we want to be mocked
* @param initialDate the initial date defaults to defaultInitialDate
*/
export function mockTime() {
const OriginalDate = global.Date
const spyedNow = jest.spyOn(Date, 'now')
const spyedDate = jest
.spyOn(global, 'Date')
// @ts-ignore
spyedDate.now = spyedNow
return {
setup: (durations: number[] = [], initialDate = defaultInitialDate) => {
let startDate = initialDate.getTime()
spyedDate.mockImplementationOnce(() => new OriginalDate(startDate) as any)
spyedNow.mockImplementationOnce(() => startDate as any)
let currentDate = startDate
durations.forEach((duration) => {
currentDate += duration
const returnDate = currentDate
spyedDate.mockImplementationOnce(() => new OriginalDate(returnDate) as any)
spyedNow.mockImplementationOnce(() => returnDate as any)
})
}
}
}
Код вызывается в тесте, похожем на приведенный ниже
import { mockTime } from './utils/mockTime'
describe('Check something with date', () => {
let sut
let setupDate
beforeAll(() => {
setupDate = mockTime().setup
})
beforeEach(() => {
sut = getSystemUnderTest()
})
test('Give correct response on success', async () => {
const expectedDuration = 600
setupDate([expectedDuration])
const responsePromise = sut()
const response = await responsePromise
expect(response.data.duration).toBe(expectedDuration)
})
})
Есть ли лучший способ манипулировать датой с помощью шутки?
Есть ли способ, которым я мог бы удалить // @ ts-ignore. Если я не добавлю его, я получу «Свойство сейчас» не существует для типа «SpyInstance» .ts (2339) »