In a nodejs application I am trying to write a test for a function which calls another function that builds a new object and then a method of that built object is called.
This is the code, service.js, I am trying to test;
// service.js
class Rectangle {
constructor(height, width) {
this.height = height;
this.width = width;
}
calcArea(){
return this.height * this.width
}
}
const rectBuilderFunc = (height, width) => new Rectangle(height, width);
const functionToBeTested = (height, width) => {
const rect = rectBuilderFunc(height, width);
const area = rect.calcArea();
return area;
}
module.exports ={
functionToBeTested,
rectBuilderFunc
}
I am using sinon, mocha and chai in my test classes. I am trying to assert that I am calling the builder function with required parameters and in the end a rectangle object is built and its calculate method is called. I end up a test similar to this one;
const expect = require('chai').expect;
const sinon = require('sinon');
const service = require('./service');
describe('test rectangle', () => {
it('should build a rectangle and calculate the area', (done) => {
//given
const rectangleMock = {
calcArea: sinon.stub()
};
service.rectBuilderFunc.withArgs(4,5).returns(rectangleMock);
//when
service.functionToBeTested(4,5);
//then
expect(service.rectBuilderFunc).to.be.calledOnce;
expect(service.rectBuilderFunc).to.be.calledWith(4,5);
expect(rectangleMock.calcArea).to.be.calledOnce;
expect(rectangleMock.calcArea).to.be.calledWith(4,5);
});
});
The problem is I keep getting rectBuilderFunc is not a function error. Any ideas to have a passing test are appreciated. Thanks.
That error is happening because rectBuilderFunc isn't a stub yet where you've called .withArgs here:
service.rectBuilderFunc.withArgs(4,5).returns(rectangleMock);
Instead, you need something like:
const rectBuilderStub = sinon.stub(service, 'rectBuilderFunc');
rectBuilderStub.withArgs(4,5).returns(rectangleMock);
Sinon stub docs: Docs. .withArgs() section is about 1/4 the way down.