Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jasmine spyOn not working

I am fairly new to Jasmine, and I have to test a few function calls:

JS CODE

 object1 = {

    function1: function() {
       // object1.function2 is a callback
       object2.someFunction("called", object1.function2)
    },

    function2:  function() {
       // code to do stuff
    }

 }

TEST CODE

describe("test suite", function(){ 
     it("test1", function(){ 
          spyOn(object1, "function2");
          object1.function1();
          expect(object1.function2).toHaveBeenCalled();
     });
});

I've tried the above but it fails, and says "Expected spy function2 to have been called". Can somebody help me out with this ? Thanks

like image 208
user3077887 Avatar asked Jan 08 '23 18:01

user3077887


1 Answers

You can rewrite the test as follows

describe("test suite", function(){ 
     it("test1", function(done){ 
          spyOn(object1, "function2");
          object1.function1();
          setTimeout(function() {
              expect(object1.function2).toHaveBeenCalled();
              done();
          });
     });
});

Your test code needs to have asynchronous testing since the callback will never be called immediately. You can add another async call which will be placed after your object1.function2 in the call stack and by the time the function inside setTimeout is executed it would have already called the object1.function2 and once assertion is made you can end the async test by calling done().

like image 172
subash-a Avatar answered Mar 03 '23 13:03

subash-a