How does createSpy work in Angular + Jasmine?

I did a simple factory demo and I'm trying to test it using jasmine . I can run the test, but I use the spyOn method. I would prefer to use jasmine.createSpy or jasmine.createSpyObj to run the same test. Can someone help me reorganize my code to use these methods instead in my example?

http://plnkr.co/edit/zdfYdtWbnQz22nEbl6V8?p=preview

describe('value check',function(){ var $scope, ctrl, fac; beforeEach(function(){ module('app'); }); beforeEach(inject(function($rootScope,$controller,appfactory) { $scope = $rootScope.$new(); ctrl = $controller('cntrl', {$scope: $scope}); fac=appfactory; spyOn(fac, 'setValue'); fac.setValue('test abc'); })); it('test true value',function(){ expect(true).toBeTruthy() }) it('check message value',function(){ expect($scope.message).toEqual(fac.getValue()) }) it("tracks that the spy was called", function() { expect(fac.setValue).toHaveBeenCalled(); }); it("tracks all the arguments of its calls", function() { expect(fac.setValue).toHaveBeenCalledWith('test abc'); }); }) 

Update

 angular.module('app',[]).factory('appfactory',function(){ var data; var obj={}; obj.getValue=getValue; obj.setValue=setValue; return obj; function getValue(){ return data; } function setValue(datavalue){ data=datavalue; } }).controller('cntrl',function($scope,appfactory){ appfactory.setValue('test abc'); $scope.message=appfactory.getValue() }) 
+5
source share
2 answers

As stated in the comments, you absolutely do not need spies to check such a service. If you needed to write documentation for your service: you would say:

setValue() allows you to save the value. This value can then be obtained by calling getValue() .

And what you should check:

 describe('appfactory service',function(){ var appfactory; beforeEach(module('app')); beforeEach(inject(function(_appfactory_) { appfactory = _appfactory_; })); it('should store a value and give it back',function() { var value = 'foo'; appfactory.setValue(value); expect(appfactory.getValue()).toBe(value); }); }); 

In addition, your service is not a factory. A factory is an object that is used to create things. Your service does not create anything. It is registered in the angular module using the factory function. But the service itself is not a factory.

0
source

I changed plunkr :

  spy = jasmine.createSpy('spy'); fac.setValue = spy; 

Edit

In Jasmine, ridicule is called spy. There are two ways to create a spy in Jasmine: spyOn () can only be used when the method already exists on the object, while jasmine.createSpy () will return a new function.

Information found here . The link contains much more information about creating spies.

+2
source

Source: https://habr.com/ru/post/1239625/


All Articles