调用callOnce时无效的Chai属性

时间:2017-07-25 22:07:10

标签: javascript sinon sinon-chai

我在使用sinon和chai在javascript中编写测试时遇到了问题。 我正在尝试检查是否在间谍上调用了一个函数并获取“错误:无效的Chai属性:calledOnce”

我在另一个具有相同测试依赖性的项目中做同样的事情没有任何问题......

var udpSocketStub = this.sandbox.spy(udpSocket, 'send');
expect(udpSocketStub).calledOnce; // SHOULD FAIL


"dependencies": {
  "body-parser": "~1.17.1",
  "bootstrap": "^4.0.0-alpha.6",
  "chai": "^4.1.0",
  "co-mocha": "^1.2.0",
  "cookie-parser": "~1.4.3",
  "debug": "~2.6.3",
  "express": "~4.15.2",
  "jquery": "^3.2.1",
  "mocha": "^3.4.2",
  "morgan": "~1.8.1",
  "node-compass": "0.2.3",
  "pug": "^2.0.0-rc.1",
  "serve-favicon": "~2.4.2",
  "sinon": "^2.3.8",
  "sinon-chai": "^2.12.0"
}

1 个答案:

答案 0 :(得分:13)

你只是错过了sinon-chai包,它为chai添加了类似sinon的断言。

npm install --save sinon-chai

初始化:

var chai = require('chai');
var sinon = require('sinon');
chai.use(require('sinon-chai'));

如果你想知道,使用存根或原始功能都可以工作:

var expect = chai.expect;

var udpSocketStub = this.sandbox.spy(udpSocket, 'send');

// Make a call
updSocket.send({..});

// Both should pass
expect(udpSocketStub).calledOnce;
expect(udpSocket.send).calledOnce;

// Identical, but more readable
expect(udpSocketStub).to.have.been.calledOnce;
expect(udpSocket.send).to.have.been.calledOnce;