模拟当前时间

问题描述 投票:0回答:1

我正在为使用连接到MongoDB的应用程序编写集成测试。我将实体创建时间写到DB并为此使用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
})

但是这会扔掉我的猫鼬模式验证

无效的架构配置:ClockDate在路径createdDate上不是有效的类型

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

javascript testing sinon stub
1个回答
0
投票

这是为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/stackoverflow/59635513

© www.soinside.com 2019 - 2024. All rights reserved.