【问题标题】:Ensure new Date() value in sinon test matches value in code确保 sinon 测试中的新 Date() 值与代码中的值匹配
【发布时间】:2021-03-27 15:01:32
【问题描述】:

如果这是一个真正的基本要求,我深表歉意,我对 sinon 还比较陌生,我一直在努力寻找尝试做我正在做的事情的人。

在我的代码中,如果没有值,我将使用 new Date() 生成一个 ISO 字符串:

const toDateTimeParameter: string = encodeURIComponent(new Date().toISOString());

在我的测试中,我还生成了一个新的 Date() 值进行比较:

const toDateTime: string = encodeURIComponent(new Date().toISOString());

您也许可以看到这是怎么回事,但由于这些 Date 实例不是在完全相同的时间生成的,它们不匹配(1-2 毫秒)。显然很难预测确切的方差(而且我宁愿不这样做),那么有没有办法将这两个值对齐?

示例失败:

AssertionError [ERR_ASSERTION]: Input A expected to strictly equal input B:
+ expected - actual

- 'https://example.com(fromDateTime=2019-11-01,toDateTime=2020-12-16T21%3A48%3A00.520Z)'
+ 'https://example.com(fromDateTime=2019-11-01,toDateTime=2020-12-16T21%3A48%3A00.519Z)'
      + expected - actual

【问题讨论】:

    标签: typescript sinon


    【解决方案1】:

    Sinon 提供了一个名为fake timers 的实用程序,可让您控制日期和时间。您可以创建一个日期并将该日期传递给 useFakeTimers 以指定该测试的日期/时间:

    afterEach(() => {
      // need to restore if you want date to not be stubbed by sinon
      sinon.restore();
    });
    
    it('should do something', () => {
      // create a date to indicate current date/time
      const now = new Date();
      // pass that date to useFakeTimers
      sinon.useFakeTimers(now);
      const expected = toDateTime();
      const actual = now.toISOString();
      assert.strictEqual(actual, expected); // or whatever assertion you do
    });
    

    希望对您有所帮助!

    【讨论】:

    • 太棒了,谢谢。现在似乎每次都有效。
    • 很高兴听到! @LeeFord 如果有帮助,请标记答案。
    猜你喜欢
    • 2012-08-24
    • 2021-08-21
    • 2016-04-28
    • 2012-10-05
    • 1970-01-01
    • 1970-01-01
    • 2019-04-17
    • 2015-05-07
    • 1970-01-01
    相关资源
    最近更新 更多