在 sinon 中模拟当前时间

Mocking the current time in sinon

我正在为使用连接到 MongoDB 的应用程序编写集成测试。我将实体创建时间写入数据库并为此使用 Date.now()。 我的应用程序对时间很敏感,因此我想模拟当前时间,以便我的测试始终有效。 我尝试过在其他多个类似帖子中分享的示例,但无法为我找到有效的解决方案。

我尝试添加

const date = new Date()
date.setHours(12)
sandbox.stub(Date, "now").callsFake(function() {return date.getTime()})

在我的 beforeEach 方法中,但它没有影响。

我也试过了

const date = new Date()
date.setHours(12)

sinon.useFakeTimers({
    now: date,
    shouldAdvanceTime: true
})

但这会抛出我的猫鼬模式验证以进行折腾和抛出

Invalid schema configuration: ClockDate is not a valid type at path createdDate

实现此目标的正确方法是什么?

这是为 Date.now() 创建存根的方法:

main.ts:

export function main() {
  return Date.now();
}

main.test.ts:

import { main } from "./main";
import sinon from "sinon";
import { expect } from "chai";

describe("59635513", () => {
  afterEach(() => {
    sinon.restore();
  });
  it("should pass", () => {
    const mDate = 1000 * 1000;
    const dateNowStub = sinon.stub(Date, "now").returns(mDate);
    const actual = main();
    expect(actual).to.be.eq(mDate);
    sinon.assert.calledOnce(dateNowStub);
  });
});

包含覆盖率报告的单元测试结果:


  59635513
    ✓ should pass


  1 passing (8ms)

--------------|----------|----------|----------|----------|-------------------|
File          |  % Stmts | % Branch |  % Funcs |  % Lines | Uncovered Line #s |
--------------|----------|----------|----------|----------|-------------------|
All files     |      100 |      100 |      100 |      100 |                   |
 main.test.ts |      100 |      100 |      100 |      100 |                   |
 main.ts      |      100 |      100 |      100 |      100 |                   |
--------------|----------|----------|----------|----------|-------------------|

源代码:https://github.com/mrdulin/mocha-chai-sinon-codelab/tree/master/src/Whosebug/59635513

useFakeTimers 的用法是做它想做的事。但是,mongoose 类型比较失败了,因为它通过检查名称进行类型比较。 解决方案原来是在沙箱内的猫鼬中添加 ClockDate 作为已知类型。

before 方法中添加以下行有效。

import { SchemaTypes } from "mongoose"
SchemaTypes["ClockDate"] = SchemaTypes.Date