Reputation: 230
I am trying to use sinon stub to mock a function but its not working as expected, can some one explain how to fix it
In one of the file customFunc.js I have functions like
function test() {
return 'working good';
}
exports.test = test;
function testFunction(data, callback) {
var sample = test();
if(sample === 'test') {
return callback(null, sample);
}
else {
return callback(null, 'not working');
}
}
exports.testFunction = testFunction;
and I am trying to test testFunction using mocha and I tried to stub test function using sinon like this
it('testing sinon', function(done) {
var stub = sinon.stub(customFunc,'test').returns('working');
customFunc.testFunction('test', function(err, decodedPayload) {
decodedPayload.should.equal('working');
done();
});
});
Is sinon works I should always get 'working' as output but its not happening, please let me know how to mock test() function.
Upvotes: 0
Views: 1064
Reputation: 5298
Your sinon stub looks okay, but what you're expecting in the test is incorrect. If the 'test' function returns 'working' (because of the stub), then the following will happen:
var sample = test(); // sample = 'working'
if(sample === 'test') { // will evaluate false
return callback(null, sample);
}
else {
return callback(null, 'not working'); // will return 'not working'
}
So naturally this will evaluate false.
decodedPayload.should.equal('working');
Upvotes: 1