Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jasmine spyOn angularjs internal methods such as $filter('date')

Please see the code in

http://jsfiddle.net/2Ny8x/69/

I wonder how I can add another spy to spyOn the method returned by $filter('date') so that I can verify

expect(something, something).toHaveBeenCalledWith('1234', 'dd-MMM-yyyy');
like image 571
user2001850 Avatar asked Sep 04 '14 11:09

user2001850


People also ask

What does Jasmine spyOn do?

Jasmine spies are used to track or stub functions or methods. Spies are a way to check if a function was called or to provide a custom return value. We can use spies to test components that depend on service and avoid actually calling the service's methods to get a value.

What is spyOn angular?

Test the Component logic using SpyOn - Testing Angular. Testing Angular. 9. Test the Component logic using SpyOn. SpyOn is a Jasmine feature that allows dynamically intercepting the calls to a function and change its result.

How do you use parameters in spyOn method?

spyOn() takes two parameters: the first parameter is the name of the object and the second parameter is the name of the method to be spied upon. It replaces the spied method with a stub, and does not actually execute the real method. The spyOn() function can however be called only on existing methods.

Which method can be used to create a Jasmine spy?

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.


1 Answers

You should be able to mock the filter passed into the controller, and return a spy from this mock. You can then test that the spy was called as normal.

Example:

describe('MyCtrl', function () {
  var filter, innerFilterSpy, http, scope;

  beforeEach(inject(function ($rootScope, $controller, $http) {
    http = $http;
    innerFilterSpy = jasmine.createSpy();
    filter = jasmine.createSpy().and.returnValue(innerFilterSpy);
    scope = $rootScope.$new();
    controller = $controller('MyCtrl', {
      '$scope': scope,
      '$http': http,
      '$filter': filter
    });
  }));

  it('call $filter("date") and test()', function () {
      expect(scope.date).toBe('01-Jan-1970');
      expect(http.get).toHaveBeenCalled();
      expect(filter).toHaveBeenCalledWith('date');
      expect(innerFilterSpy).toHaveBeenCalledWith('1234', 'dd-MMM-yyyy');
  });
});
like image 179
Tom Spencer Avatar answered Nov 16 '22 20:11

Tom Spencer