【问题标题】:Javascript Jest Unit Test Time IntervalJavascript Jest 单元测试时间间隔
【发布时间】:2021-06-14 13:56:23
【问题描述】:

我需要一些关于时间间隔单元测试的帮助。 也许有人可以告诉我它是如何工作的?我是编写单元测试的新手.. 举个例子就好了。

这是我要测试的代码:

export const dayIntervalFromDate = (date) => {
  const fromDate = new Date(date);
  fromDate.setHours(0, 0, 0, 0);

  const toDate = new Date(date);
  toDate.setHours(23, 59, 59, 999);
  return { from: fromDate, to: toDate };
}

dayIntervalFromDate 测试

    it("returns day interval from date", () => {
        const mockDayInterval = new Date('2021-01-01');
        const expectedFrom = new Date('2021-01-01');
        expectedFrom.setHours(0, 0, 0, 0);
        const expectedTo = new Date('2021-01-01');
        expectedTo.setHours(23, 59, 59, 999);

        jest.fn(() => mockDayInterval);
      
        const { from , to } = dayIntervalFromDate(Date);
  
        expect(from).toEqual(expectedFrom);
        expect(to).toEqual(expectedTo);
    });

【问题讨论】:

  • 这不是测试写作服务;你有什么尝试,它到底有什么问题?
  • it("从日期返回天间隔", () => { const dayIntervalFrom = new Date(0, 0, 0, 0); dayIntervalFrom.setHours(0, 0, 0, 0) ; const from = dayIntervalFromDate; const dayIntervalTo = new Date(23, 59, 59, 999); dayIntervalTo.setHours(23, 59, 59, 999); const to = dayIntervalTo; expect(dayIntervalFromDate(Date)).toHaveBeenCalledWith(from , to); });
  • "...它到底有什么问题?" - 它是通过、失败、崩溃还是...?
  • 我已经更新了我的问题
  • dayIntervalFromDate(Date) 有意义吗?那是传递 class,而不是实例。此外,还不清楚jest.fn(() => mockDayInterval) 应该如何连接到正在发生的任何其他事情。

标签: javascript unit-testing


【解决方案1】:

我现在已经解决了...

    it("returns day interval from date", () => {
        const mockDayInterval = new Date();
        const expectedFrom = new Date();
        expectedFrom.setHours(0, 0, 0, 0);
        const expectedTo = new Date();
        expectedTo.setHours(23, 59, 59, 999);

        jest.fn(() => mockDayInterval);
      
        const { from , to } = dayIntervalFromDate(new Date());
  
        expect(from).toEqual(expectedFrom);
        expect(to).toEqual(expectedTo);
    });

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-08-05
    • 1970-01-01
    • 1970-01-01
    • 2021-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多