Is there a way in Mocha to test if a function calls a specific method or external function?
I am using Mocha with Chai, but am open to any other assertion libraries.
Ok, so testing whether a methid is being called is pretty easy using sinon. I'm not sure about testing to see if an external function is being called though. So I updated the examples to represent something a little more "real world". I am working on a node app, so foo.js
and bar.js
are both modules.
Example:
foo.js
var bar = require('bar');
var xyz = function () {};
var Foo = module.exports = function () {
this.bar();
bar();
xyz();
};
Foo.prototype.bar = function () {};
bar.js
var bar = module.exports = function () {};
fooSpec.js
var chai = require('chai');
var sinon = require('sinon');
var sinonChai = require('sinonChai');
var expect = chai.expect;
var Foo = require('../lib/foo');
chai.use('sinonChai');
describe('Foo', function () {
var method;
beforeEach(function (done) {
method = sinon.spy(Foo.prototype, 'bar');
done();
});
afterEach(function (done) {
method.restore();
done();
});
it('should call Foo.prototype.bar() immediately', function () {
new Foo();
expect(method).to.have.been.called;
});
it('should call the module bar immediately', function () {
// ????????????
});
it('should call xyz() immediately', function () {
// ????????????
});
});
So as you can see I've figured out how to test for Foo.prototype.bar
, but I can't find a way to implement the second and third tests.