【问题标题】:Mocha spies returns callCount 0摩卡间谍返回 callCount 0
【发布时间】:2019-02-18 18:11:38
【问题描述】:

我在节点环境中使用 mocha、chai 和 sinon 进行单元测试。我需要测试一个场景,它调用服务来获取数据并返回数据。

我的控制器如下所示:

{
   get model() { return schema},
   async findUser(data) {
      const data = await this.model.find({ id: data.id });
      return data;
   }
}

在我的 mocha 测试中,我使用 Sinon 存根返回模型并找到如下函数:

sinon.stub(controller, 'model').get(() => ({
    find: () => ({ username: 'asdf' })
}));

我的测试按预期进行。现在我想测试一下我的 find 方法 id 是否调用过一次,以及是否传递给它的参数。为此,我添加了以下代码

const spyFind = sinon.spy(controller.model, 'find');
assert.isTrue(spyFind.calledOnce);

这应该返回 true,因为调用了 spyFind 并且它返回了预期的模拟值。但是当我调试时,spyFind 对象说 isCalled 'false'。有人可以帮我理解我做错了什么吗?

【问题讨论】:

  • 不清楚controller.method 指的是什么。你的意思是const spyFind = sinon.spy(controller.model, 'find');
  • 哦,是的,更新了。它是controller.model

标签: node.js mocha.js sinon


【解决方案1】:

您的存根的设计方式将在每次调用controller.model 时返回一个新对象。结果:

controller.model === controller.model // false

因此,当您尝试监视 controller.modelfind 属性时:

const spyFind = sinon.spy(controller.model, 'find');

Sinon 抓取controller.model 返回的对象并在那个 对象上存根find。下次您调用controller.model 时,例如在您的测试中,您将从controller.model 获得一个未被监视的新对象。所以原来的间谍永远不会被调用。

我认为更好的方法是提供一个由find() 返回的单一存根,然后您可以判断存根是否被调用:

const sinon = require('sinon')

let controller = {
    get model() { return schema},
    async findUser(data) {
        const data = await this.model.find({ id: data.id });
    return data;
    }
}

let findStub = sinon.stub()
findStub.returns({ username: 'asdf' })

sinon.stub(controller, 'model').get(() => ({
    find: findStub
}));

console.log(controller.model.find()) // { username: 'asdf' }
console.log(findStub.calledOnce);    // true

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-07-01
    • 2018-11-20
    • 2017-06-13
    • 1970-01-01
    相关资源
    最近更新 更多