我试图测试http呼叫的响应。问题是,无论我在那里放置什么响应代码或响应数据,它都会通过。有任何想法吗?谢谢!
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
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()
});
});
答案 0 :(得分:1)
好的,首先,避免像alert
这样的全局函数。他们很难测试。而是将$window
注入您的控制器并使用
$window.alert("We were not able to retrieve your press data");
现在,至于您的测试,您需要测试实际结果。例如......
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();
});