Invalid Chai property when calling calledOnce
Asked Answered
D

1

22

I'm having problems writing tests in JavaScript with Sinon and Chai. I'm trying to check if a function is called on a spy and get I get

"Error: Invalid Chai property: calledOnce"

I'm doing the same thing in another project with the same test dependencies without any problem.

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"
}
Divergency answered 25/7, 2017 at 22:7 Comment(3)
Are you sure? I think that It should be expect(udpSocketStub.send.calledOnce).to.be.true, correct me if I'm wrong.Hittel
@hinok ricostacruz.com/cheatsheets/sinon-chai.html Looks like you don't need the to.be.true.Collected
@Elliott sinon-chai, I missed that package, you're right. But still probably it should be expect(udpSocketStub.send).calledOnce;Hittel
F
36

You're just missing the sinon-chai package, that adds sinon-like assertions to chai.

npm install --save sinon-chai

Initialization:

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

In case you're wondering, using the stub or the original function both work:

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;
Ferdy answered 20/9, 2017 at 4:59 Comment(4)
Thanks for your answer, as this solved my problem...would you mind explaining or pointing me towards on answer on how to do the chai.use(require('sinon-chai')); line if you're trying to do import instead of require?Ursola
You can try import sinonChai from 'sinon-chai' then chai.use(sinonChai) but you're using TypeScript am I right ? I'm not sure sinon-chai supports typescript.Ferdy
Feel free to tick the green arrow to mark the question as answered if you feel I solved your problem ;)Ferdy
you did solve my problem but unfortunately I'm not the OPUrsola

© 2022 - 2024 — McMap. All rights reserved.