Angular unit testing with Jasmine: how to remove or modify spyOn

emersonthis picture emersonthis · Mar 3, 2015 · Viewed 36.2k times · Source

AngularJS v1.2.26

Jasmine v2.2.0

How can I change or remove the behavior of a spyOn? When I try to override it, I get the following error: Error: getUpdate has already been spied upon

var data1 = 'foo';
var data2 = 'bar';

describe("a spec with a spy", function(){

    beforeEach(module('app'));

    var $q;

    beforeEach(inject(function(_updateService_, _$q_){
        updateService = _updateService_;

        //spy the results of the getUpdate()
        $q = _$q_;
        var deferred = $q.defer();
        deferred.resolve( data1 );
        spyOn(updateService, 'getUpdate').and.returnValue(deferred.promise);

    }));

    describe('and here the spy should be different', function() {

        it('returns a different value', function() {

          var deferred = $q.defer();
          deferred.resolve( data2 );
          spyOn(updateService, 'getUpdate'); //ERROR HERE
          updateService.getUpdate.and.returnValue(deferred.promise);

          ...

        });
    });

...

When I remove the second spyOn the test doesn't work.

How do I do this?

Answer

Peter Ashwell picture Peter Ashwell · Mar 3, 2015

You can just overwrite it

updateService.getUpdate = jasmine.createSpy().and.returnValue(etc)