调用calledOnce时Chai属性无效

2022-06-17 00:00:00 javascript sinon sinon-chai

我在用SINON和Chai编写测试时遇到了问题。 我正在尝试检查是否对间谍调用了函数并获取

";错误:无效的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"
}

解决方案

您缺少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;

相关文章