[英]Angular Jasmine $httpBackend Response Tests
I'm trying to test the response of an http call. 我正在尝试测试http调用的响应。 The problem is, it passes no matter what response code I put in there or response data.
问题是,无论我放入什么响应代码或响应数据,它都会通过。 Any ideas?
有任何想法吗? Thanks!
谢谢!
Controller.js Controller.js
$scope.getPresses = function() {
var pressRequest = {
method: 'GET',
url: localAPI.url + 'press/',
headers: requestHeaders
};
$http(pressRequest)
.success(function(data) {
$scope.userPresses = data.results;
})
.error(function() {
alert("We were not able to retrieve your press data");
});
};
testController.js testController.js
describe('Get Presses', function() {
it("sets scope attributes for the user's presses", function() {
$scope.getPresses()
$httpBackend.expectGET('http://0.0.0.0:8000/api/press/', function() {
return {
Authorization: "Token fakeToken2903920932"
}
}).respond(304, 'responseData')
$httpBackend.flush()
});
});
Ok, first, avoid global functions like alert
. 好的,首先,避免使用诸如
alert
全局函数。 They are difficult to test. 他们很难测试。 Instead, inject
$window
into your controller and use 相反,将
$window
注入控制器并使用
$window.alert("We were not able to retrieve your press data");
Now, as for your test, you need to test the actual results. 现在,对于您的测试,您需要测试实际结果。 For example...
例如...
var $window, $scope, $httpBackend;
beforeEach(function() {
module('your.module', function($provide) {
$provide.value('$window', $window = jasmine.createSpyObj('$window', ['alert']));
});
// and however else you set up your $scope and $httpBackend vars
});
it('assigns results to userPresses on success', function() {
$httpBackend.expectGET('http://0.0.0.0:8000/api/press/', function(headers) {
return headers['Authorization'] === 'Token fakeToken2903920932';
}).respond({results: 'results'});
$scope.getPresses();
$httpBackend.flush();
expect($scope.userPresses).toBe('results');
});
it('calls alert on error', function() {
$httpBackend.whenGet('http://0.0.0.0:8000/api/press/').respond(500);
$scope.getPresses();
$httpBackend.flush();
expect($window.alert).toHaveBeenCalled();
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.