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?
SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result. This example shows how spyOn works, even if we are still mocking up our service.
There are two ways to create a spy in Jasmine: spyOn() can only be used when the method already exists on the object, whereas jasmine. createSpy() will return a brand new function: //spyOn(object, methodName) where object. method() is a function spyOn(obj, 'myMethod') //jasmine.
Jasmine is a behavior development testing framework. Unit tests are written using Jasmine and are run to see if individual parts of an application are working correctly. As a result, unit tests will either pass or fail depending on if the code is working correctly or has a bug.
xdescribe: FunctionLike describe , but instructs the test runner to exclude this group of test cases from execution. This is useful for debugging, or for excluding broken tests until they can be fixed. See http://jasmine.github.io/ for more details.
You can just overwrite it
updateService.getUpdate = jasmine.createSpy().and.returnValue(etc)
You can override the return value of the spy
var deferred = $q.defer(); deferred.resolve( data1 ); var getUpdateSpy = spyOn(updateService, 'getUpdate').and.returnValue(deferred.promise); var newDeferred = $q.defer(); newDeferred.resolve( data2 ); getUpdateSpy.and.returnValue(newDeferred.promise);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With