【问题标题】:Javascript Unittest Jest Time Interval from a DayJavascript 单元测试 Jest 一天的时间间隔
【发布时间】:2021-06-15 14:43:40
【问题描述】:

我在测试一天的间隔时遇到了困难。 也许有人可以解释我做错了什么。

这就是我要测试的内容

export const getMondayFromDay = (date) => {
  const monday = new Date(date);
  const day = monday.getDay();
  monday.setDate(monday.getDate() - day + (day === 0 ? -6 : 1));
  monday.setHours(0, 0, 0, 0);
  return monday;
}

我的失败测试

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

        jest.fn(() => mockMondayFromDay);
        const { from , to } = getMondayFromDay(new Date('2021-01-04'));
        expect(from).toEqual(expectedFrom);
        expect(to).toEqual(expectedTo);
    });

【问题讨论】:

    标签: javascript unit-testing jestjs


    【解决方案1】:

    您的getMondayFromDay 函数仅返回一个日期(根据给定日期的前一个星期一(或如果已经是星期一,则为当天))。

    所以 fromto 在此处未定义: const { from , to } = getMondayFromDay(new Date('2021-01-04'));.

    您的测试可能是:

    // test if the same date is returned if it's a monday
    const monday = getMondayFromDay(new Date('2021-01-04'));
    expect(monday).toEqual(expectedFrom);
    
    // test if the previous monday is returned if the date is not a monday
    const monday2 = getMondayFromDay(new Date('2021-01-05'));
    expect(monday2).toEqual(expectedFrom);
    

    【讨论】:

      【解决方案2】:

      我现在有一个解决方案:

          it("returns day interval from monday", () => {
              const expectedFrom = new Date('2021-06-14');
              expectedFrom.setHours(0, 0, 0, 0);
              const expectedTo = new Date('2021-06-14');
              expectedTo.setHours(23, 59, 59, 999);
      
              const monday = getMondayFromDay(new Date('2021-06-16'));
              expect(monday.getDate()).toEqual(14);
              expect(monday.getMonth()).toEqual(5);
              expect(monday.getFullYear()).toEqual(2021);
          });
      

      【讨论】:

      • 它有效,但我的回答更完整,你只测试一个案例(不是星期一)。
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-08-05
      • 2022-06-28
      • 1970-01-01
      • 1970-01-01
      • 2021-11-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多