Javascript 嘲笑服务时与Jasmine的问题
我有一个控制器如下Javascript 嘲笑服务时与Jasmine的问题,javascript,angularjs,Javascript,Angularjs,我有一个控制器如下 (function () { var mockController = function ($scope, MockService) { $scope.message = "This is a text message"; $scope.getCities = function () { return MockService.getCities(); }; }; var m
(function () {
var mockController = function ($scope, MockService) {
$scope.message = "This is a text message";
$scope.getCities = function () {
return MockService.getCities();
};
};
var mockService = function ($http) {
this.getCities = function () {
return $http.get("../rest/url", {
headers: {
'Accept': 'application/yang.data+json'
}
});
};
};
angular.module("MockApp", [])
.service("MockService", mockService)
.controller("MockController", mockController);
}())
describe("MockController", function () {
var $scope;
beforeEach(function () {
module("MockApp");
inject(function (_$controller_, _$rootScope_, MockService) {
$scope = _$rootScope_.$new();
spyOn(MockService, "getCities").and.callFake(function () {
return [{
city: "Bangalore"
, country: "India"
}];
});
controller = _$controller_("MockController", {
$scope: $scope
});
});
});
describe("Test", function () {
it("Should be Bangalore", function () {
$scope.getCities()
.then(function (data) {
console.log("got it");
})
});
});
});
我正试图写一个UT模拟服务,如下所示
(function () {
var mockController = function ($scope, MockService) {
$scope.message = "This is a text message";
$scope.getCities = function () {
return MockService.getCities();
};
};
var mockService = function ($http) {
this.getCities = function () {
return $http.get("../rest/url", {
headers: {
'Accept': 'application/yang.data+json'
}
});
};
};
angular.module("MockApp", [])
.service("MockService", mockService)
.controller("MockController", mockController);
}())
describe("MockController", function () {
var $scope;
beforeEach(function () {
module("MockApp");
inject(function (_$controller_, _$rootScope_, MockService) {
$scope = _$rootScope_.$new();
spyOn(MockService, "getCities").and.callFake(function () {
return [{
city: "Bangalore"
, country: "India"
}];
});
controller = _$controller_("MockController", {
$scope: $scope
});
});
});
describe("Test", function () {
it("Should be Bangalore", function () {
$scope.getCities()
.then(function (data) {
console.log("got it");
})
});
});
});
这是一个错误的说法
TypeError:$scope.getCities(…)。then不是函数
请帮帮我。我想:
$scope.getCities = function () {
return MockService.getCities();
};
应该是:
$scope.getCities = function () {
return MockService(getCities());
};
我认为:
$scope.getCities = function () {
return MockService.getCities();
};
应该是:
$scope.getCities = function () {
return MockService(getCities());
};
这可能是一个愚蠢的问题,但Angular的$http服务是如何注入到您的服务中的呢?此外,您还为MockService.getCitites()创建了一个不返回承诺对象的伪对象。不要认为可以对伪造的返回类型调用.then()函数。它存在于angular.jsp中。这可能是一个愚蠢的问题,但是angular的$http服务是如何注入到您的服务中的呢?此外,您还为MockService.getCitites()创建了一个不返回承诺对象的伪对象。不要认为可以对伪造的返回类型调用.then()函数。它出现在angular.js中