Reputation: 1317
I am pretty new in Jasmine test.
Lett say I have this sample.js file:
(function() {
function myFunction() {
do some thing and then make a call to MyOtherFunciton
}
myOtherFunciton(p1, p2, p3) {
//do some stuff in here
}
module.exports = {
myOtherFunciton,
myFunction
}
})();
Now I have this jasmine test does the following
const mySampleFile = require(./sample.js);
spyOn(mySampleFile, "myOtherFunciton").and.callFack(()=>{
});
mySampleFile.myFunction();
expect(mySampleFile.myOtherFunciton).toHaveBeenCalled();
The problem I am experiencing is that it makes a call to real myOtherFunciton function but not the mocked one. Why is that ?
Upvotes: 1
Views: 44
Reputation: 6060
It's a function scope problem you are running into. The function myOtherFunciton()
called from within myFunction()
is not the same as mySampleFile.myOtherFunciton()
, as you found out. To fix will require a slight refactor of your original code (don't you love it when testing exposes such things?). I added some console.logs below just to be clear where the execution context is going during testing.
Suggested refactor:
(function() {
exports.myFunction = function() {
// do some thing and then make a call to MyOtherFunciton
console.log('inside myFunction');
exports.myOtherFunciton('a', 'b', 'c'); // scoped to exports, now can be mocked
// myOtherFunciton('a', 'b', 'c'); // <-- don't call it like this: scoped within IIFE
}
exports.myOtherFunciton = function(p1, p2, p3) {
console.log('inside original myOtherFunciton');
//do some stuff in here
}
// module.exports = {
// myOtherFunciton,
// myFunction
// }
})();
Here is a working StackBlitz showing the test now passing. Click on 'console' below the Jasmine test window to see the output.
I hope this helps.
Upvotes: 1