angularjs – Angular Jasmine spyOn查询调用

前端之家收集整理的这篇文章主要介绍了angularjs – Angular Jasmine spyOn查询调用前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我对Angular和Jasmine很新,当我试图伪造一个服务“查询调用时,我遇到了问题.以下是“描述”:

var mockBackend;

beforeEach(inject(function($rootScope,$controller,AppServ) {
  // We need to setup our controllers to use fake services provided by angular-mocks
  $scope = $rootScope.$new();
  mockBackend = AppServ;

  $controller('AppInformationController',{
    $scope: $scope,AppServ: mockBackend
  });
}));

it("should try to call the service,but we intercept it",function() {
  spyOn(mockBackend,'query').andReturn({'title':'Mock title'});

  $scope.serverAppNameChange();
  expect($scope.app.title).toBe("Mock title");
});

上面的“AppServ”是我的服务,我想拦截每当测试调用该服务上的“查询”以返回一些默认信息.真的,这只是为了了解Jasmine和Angular如何工作.服务本身除了保留本地副本(它基本上是假服务)之外什么都不做.

这是服务:

Services.factory("AppServ",function($http) {
  var app = {};
  var theAppOnServer = {};

  app['query'] = function() {
    return theAppOnServer;
  };

  app['save'] = function(app) {
    theAppOnServer = $.extend({},app);
  };

  app['updateApp'] = function() {
    theAppOnServer['title'] = "Title From Server";
  };

  return app;
});

这是控制器:

MobileIntake.controller("AppInformationController",function($scope,AppServ) {
  $scope.app = AppServ.query();

  //var AppOverviewController = function($scope) {
  $scope.appNameChange = function(oldValue,newValue,scope) {
    console.log("You've changed the app name!");
  };

  $scope.serverAppNameChange = function() {
    AppServ.updateApp();
  };
  // Set up a watcher if we want to be updated by other things (like the server)
  $scope.$watch("app.title",$scope.appNameChange);

});

有人可以告诉我为什么spyOn似乎没有拦截服务上的“查询函数调用?我已经看到了其他几个答案,他们正在使用$http和一些特殊逻辑,但我只是想知道我也可以拦截非http函数.

解决方法

您不需要额外的mockBackend对象.只是窥探服务本身.

beforeEach(inject(function($rootScope,$controller) {
  // We need to setup our controllers to use fake services provided by angular-mocks
  $scope = $rootScope.$new();

  $controller('AppInformationController',{
    $scope: $scope
  });
}));

it("should try to call the service,inject(function(AppServ) {
  spyOn(AppServ,'query').andReturn({'title':'Mock title'});

  $scope.serverAppNameChange();
  expect($scope.app.title).toBe("Mock title");
}));

猜你在找的Angularjs相关文章