Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How does the createSpy work in Angular + Jasmine?

I made a simple demo of a factory and I am trying to test this using jasmine. I am able to run the test but I am using the spyOn method. I would rather use jasmine.createSpy or jasmine.createSpyObj to do the same test. Could someone help me to refactor my code so that uses 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()
})
like image 935
user944513 Avatar asked Oct 30 '22 12:10

user944513


1 Answers

I have changed your plunkr:

 spy = jasmine.createSpy('spy');

 fac.setValue = spy;

Edit

In Jasmine, mocks are referred to as spies. 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.

Found the information here. The link has a lot more information about creating spies.

like image 61
Daan van Hulst Avatar answered Nov 09 '22 08:11

Daan van Hulst