jasmine spyOn angularjs内部方法,例如$ filter('date')

时间:2014-09-04 11:14:10

标签: angularjs filter jasmine

请参阅

中的代码

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

我想知道如何添加另一个间谍来窥探$ filter返回的方法(' date')以便我可以验证

expect(something, something).toHaveBeenCalledWith('1234', 'dd-MMM-yyyy');

1 个答案:

答案 0 :(得分:14)

你应该可以模拟传递给控制器​​的过滤器,并从这个模拟中返回一个间谍。然后,您可以测试间谍是否正常调用。

示例:

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');
  });
});