【发布时间】:2019-03-21 13:59:08
【问题描述】:
我正在尝试测试 $http 请求,但无论我做什么,我似乎都无法让它工作。我有一个工厂,它拥有 4 种请求类型 GET、POST、PUT、DELETE。
我正在尝试测试来自 get 请求的响应,但在控制器中分配响应的作用域变量给出错误或 undefined = get 请求的响应。
工厂代码如下:
app.factory('requestService', ['$http', function ($http) {
// reusable requests
return {
//reuable get request
getRequest: function (url) {
return $http({
method: 'GET',
dataType: "json",
url: url
});
},
//reuable post request
postRequest: function (url, data) {
return $http({
method: 'POST',
data: data,
url: url
});
},
//reuable put request
putRequest: function (url, data) {
return $http({
method: 'PUT',
data: data,
url: url
});
},
//reuable delete request
deleteRequest: function (url) {
return $http({
method: 'DELETE',
url: url
});
}
}
}]);
以下在控制器中。
//get the teams
$scope.getTeams = function(){
requestService.getRequest('https:.../teams').then(function (response) {
$scope.teams = response;
});
}
$scope.getTeams();
茉莉码:
describe('Controller Test', function() {
var $rootScope, controller;
//Tell the $httpBackend to respond with our mock object
var teamsResponse = {// Teams Data //};
beforeEach(function() {
module('myApp')
});
beforeEach(inject(function($rootScope, $controller, _$httpBackend_, $http) {
$scope = $rootScope.$new();
controller = $controller;
controller('Controller', {$scope: $scope});
$httpBackend = _$httpBackend_;
$httpBackend.whenGET('https:...../teams').respond(200, teamsResponse);
}));
it('should load a list of teams', function() {
$scope.getTeams();
$httpBackend.flush();
expect($scope.teams).toBe(teamsResponse);
});
});
我得到的错误是:
预计未定义为 {// 团队数据 //}
【问题讨论】:
-
您正在测试的代码在哪里?确切的错误是什么? 'error or undefined = the response from the get request' 不够清楚。
-
@estus 编辑了问题内容
-
我不明白为什么它是未定义的,甚至不确定是否可以考虑提供的数据,但问题是您正在进行功能/集成测试。适当的单元测试是双重的。在控制器测试中,您模拟 requestService。在服务测试中,您模拟 http 请求。这样做的目的是逐行测试代码,并在有问题时将问题缩小到一行代码。
-
另外,最好使用 expect...respond in
it而不是 when...respond inbeforeEach,参见关于严格与松散docs.angularjs.org/api/ngMock/service/…的注释 -
代码创建了两个 get 请求:一个是在控制器被实例化时,另一个是在
it块中。这是故意的吗?
标签: angularjs jasmine karma-jasmine