Javascript 使用sinon监视类方法的参数

Javascript 使用sinon监视类方法的参数,javascript,ecmascript-6,tdd,sinon,chai,Javascript,Ecmascript 6,Tdd,Sinon,Chai,我有一个我想监视的类,用来检查调用该方法的参数 class Animal { constructor() { this.animals = []; } add(animal) { this.animals.push(animal); } } 我的测试文件如下所示 const chai = require('chai'); const sinon = require('sinon'); const Lazy = require('../lazy'); it

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

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检查被称为什么。

animal
是对象,间谍实际上是
add
,因此它应该是:

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

animal
是对象,间谍实际上是
add
,因此它应该是:

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

Patrick对代码的看法是正确的,您需要验证的是
spy
而不是对象,但是您的代码在没有修改的情况下仍然无法运行。我发了一封信。似乎您也需要使用
调用,但可能使用了其他设置(缺少)。查看代码:-)

因此,将期望值更改为

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

Patrick对代码的看法是正确的,您需要验证的是
spy
而不是对象,但是您的代码在没有修改的情况下仍然无法运行。我发了一封信。似乎您也需要使用
调用,但可能使用了其他设置(缺少)。查看代码:-)

因此,将期望值更改为

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

侦察原型?
sinon.Spy(Animal.prototype,'add')
?侦察原型?
sinon.Spy(Animal.prototype,'add')