14

我在用 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"
}
4

1 回答 1

29

你只是错过了这个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;
于 2017-09-20T04:59:51.437 回答