首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular Jasmine spyOn查询调用

Angular Jasmine spyOn查询调用
EN

Stack Overflow用户
提问于 2013-04-24 02:24:23
回答 1查看 6.2K关注 0票数 4

我是Angular和Jasmine的新手,当我试图伪造一个服务“查询”调用时,我遇到了一些问题。下面用“describe”括起来:

代码语言:javascript
复制
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“是我的服务,每当测试对该服务调用"query”以返回一些默认信息时,我都会进行拦截。实际上,这只是为了了解Jasmine和Angular是如何工作的。服务本身什么也不做,只保留一个本地副本(它基本上是一个假服务)。

以下是该服务:

代码语言:javascript
复制
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;
});

下面是控制器:

代码语言:javascript
复制
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似乎没有拦截服务上的"query“函数调用吗?我已经看到了一些其他的答案,他们使用了$http和一些特殊的逻辑,但我只是想得到一个想法,我也可以拦截非http函数。

EN

回答 1

Stack Overflow用户

发布于 2013-04-24 04:43:17

您不需要额外的mockBackend对象。只需监视服务本身。

代码语言:javascript
复制
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, but we intercept it", inject(function(AppServ) {
  spyOn(AppServ, 'query').andReturn({'title':'Mock title'});

  $scope.serverAppNameChange();
  expect($scope.app.title).toBe("Mock title");
}));
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/16176492

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档