user3077887
user3077887

Reputation: 51

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

Upvotes: 4

Views: 12966

Answers (1)

subash-a
subash-a

Reputation: 121

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().

Upvotes: 9

Related Questions