【问题标题】:Javascript Jest Unit Test Date Timespan for Today and Day before今天和前一天的Javascript Jest单元测试日期时间跨度
【发布时间】:2021-06-14 10:04:43
【问题描述】:

我想用 Jest 测试我今天和前一天的时间跨度,但我不知道该怎么做。 也许有人可以告诉我它是如何工作的?我是编写单元测试的新手..

这是我要测试的代码:

export const getToday = () => {
  const today = new Date();
  return today;
}

export const getDayBefore = (date) => {
  const day = new Date(date);
  day.setDate(date.getDate() - 1);
  return day;
}

这是我现在所做的,但它不起作用。

describe('getToday', () => {
    it('should checks "today"', () => {
        const ts1 = Date.now();
        expect(ts1).toEqual(getToday);
    })
});

【问题讨论】:

  • 不应该expect(ts1).toEqual(getToday);expect(ts1).toEqual(getToday());

标签: javascript unit-testing


【解决方案1】:

这是更正后的代码,我建议交换断言和函数,以便测试更有意义。您应该运行一个函数并期望它等于一个值,而不是相反。

Date.now() 不等于 new Date(),因为前者返回日期的数字表示,而后者返回 Date 对象,因此它们不匹配。

export const getToday = () => {
  const today = new Date();
  return today;
}

describe('getToday', () => {
  it('matches todays date', () => {
      const now = new Date();
      expect(getToday()).toEqual(now);
  });
});

已更新,获取日期早于

我重新设计了函数以使日期参数可选,以便默认返回昨天的日期。我们不能只将 null 传递给 Date 构造函数,否则它将返回 01-01-1970。请参见下面的示例。

const getDayBefore = (date = null) => {
  const day = date ? new Date(date) : new Date();
  day.setDate(day.getDate() - 1);
  return day;
};

describe("getDayBefore", () => {
  it("returns yesterdays date", () => {
    const date = new Date();
    date.setDate(date.getDate() - 1);
    expect(getDayBefore()).toEqual(date);
  });

  it("returns the correct date if 31/12/2021 was supplied as the date arg", () => {
    const date = new Date(2021, 11, 30); // month has an offset of 11 (11 = december)
    expect(getDayBefore('2021-12-31')).toEqual(date);
  });

  it("returns the correct date if 24/02/1900 was supplied as the date arg", () => {
    const date = new Date(1990, 1, 23); // month has an offset of 1 (1 = feb)
    expect(getDayBefore('1990-02-24')).toEqual(date);
  });
});

【讨论】:

  • 非常感谢 :) 但是我如何测试 getDayBefore?我应该在参数中添加 -1 吗?
  • 非常感谢您的详细解释。你拯救了我的一天:D
  • @tripleD 如果有帮助,请标记为答案 :)
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多