小编Bra*_*sky的帖子

如何“伪造”日期/时间来测试猫鼬模型

在此之前,感谢您提供的任何帮助/建议!

我要完成的工作

我正在尝试找到一种优雅的方法来创建Mongoose模型的实例时测试日期/时间。

我想确保存储的时间是正确的时间。

我的模型当前如下所示:

const messageSchema = mongoose.Schema({
  user: { type: String, required: true },
  message: { type: String, required: true },
  created: { type: Date, default: Date.now },
});

const Message = mongoose.model('Message', messageSchema);
Run Code Online (Sandbox Code Playgroud)

我将此模型导入到mocha测试套件中,在其中尝试按照以下方式运行测试:

const now = {Date message was created}
it('check time matches time created', () => {
  expect(message.created).to.equal(now);
});
Run Code Online (Sandbox Code Playgroud)

到目前为止我尝试过的

我尝试完成此操作的方法是使用Sinon的Fake计时器功能。

所以我的测试用例看起来像这样:

describe('creating new message', () => {
  let clock;
  let message;
  let now;

  before(() => {
    clock = sinon.useFakeTimers();
    clock.tick(100);
    message = …
Run Code Online (Sandbox Code Playgroud)

unit-testing mongoose mongodb node.js sinon

5
推荐指数
1
解决办法
381
查看次数

标签 统计

mongodb ×1

mongoose ×1

node.js ×1

sinon ×1

unit-testing ×1