【问题标题】:spy on argument to class method using sinon使用 sinon 监视类方法的参数
【发布时间】:2019-06-28 07:10:36
【问题描述】:

我有一个类,我想监视它以检查调用该方法的参数。

class Animal {
  constructor() {
     this.animals = [];
  }

  add(animal) {
    this.animals.push(animal);
  }
}

我的测试文件是这样的

const chai = require('chai');
const sinon  = require('sinon');
const Lazy = require('../lazy');

it('should be able to add an animal', function () {
    const animal = new Animal();
    const add = sinon.spy(animal, 'add');
    animal.add('cat')
    expect(animal).to.have.been.called.with('cat');
});

间谍没有工作。我想知道如何使用 sinon 检查调用的内容。

【问题讨论】:

  • 窥探原型?
  • sinon.spy(Animal.prototype, 'add')?

标签: javascript ecmascript-6 tdd sinon chai


【解决方案1】:

animal是对象,spy其实是add,所以应该是:

expect(add).to.have.been.called.with('cat');

【讨论】:

    【解决方案2】:

    Patrick 对代码的看法是正确的,您需要验证 spy 而不是对象,但您的代码在没有更改的情况下仍然无法运行。我做了一个functioning example on RunKit。看来您还需要使用calledWith,但您可能使用了其他一些设置(缺少)。查看代码:-)

    所以把期望改成

    expect(add).to.have.been.calledWith('cat');
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-11-11
      • 2016-12-24
      • 2015-05-13
      • 2018-08-19
      • 2017-12-20
      • 1970-01-01
      • 1970-01-01
      • 2020-05-23
      相关资源
      最近更新 更多