Tri Vuong Tri Vuong - 6 months ago 41
Javascript Question

How do we clear spy programmatically in Jasmine?

How do we clear the spy in a jasmine test suite programmatically? Thanks.

beforeEach(function() {
spyOn($, "ajax").andCallFake(function(params){
})
})

it("should do something", function() {
//I want to override the spy on ajax here and do it a little differently
})

Answer

I'm not sure if its a good idea but you can simply set the isSpy flag on the function to false:

describe('test', function() {
    var a = {b: function() {
    }};
    beforeEach(function() {
        spyOn(a, 'b').andCallFake(function(params) {
            return 'spy1';
        })
    })
    it('should return spy1', function() {
        expect(a.b()).toEqual('spy1');
    })

    it('should return spy2', function() {
        a.b.isSpy = false;
        spyOn(a, 'b').andCallFake(function(params) {
            return 'spy2';
        })
        expect(a.b()).toEqual('spy2');
    })

})

But maybe its a better idea to create a new suite for this case where you need an other behavior from your spy.

Comments