1

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 ?

1 Answer 1

1

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.