用玩笑和打字稿模拟Global.Date构造函数和Date.now

时间:2020-03-04 05:05:45

标签: typescript mocking jestjs

我正在尝试用玩笑和打字稿正确地模拟Date,以便测试一些记录时间戳的功能。

我准备了以下代码来模拟日期

// 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)”上的“属性现在不存在”

0 个答案:

没有答案
相关问题