我对 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 函数。