gpt4 book ai didi

javascript - Angular Jasmine $httpBackend 响应测试

转载 作者:行者123 更新时间:2023-12-03 10:48:14 24 4
gpt4 key购买 nike

我正在尝试测试 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()
});
});

最佳答案

好吧,首先,避免像 alert 这样的全局函数。它们很难测试。相反,将 $window 注入(inject)您的 Controller 并使用

$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();
});

关于javascript - Angular Jasmine $httpBackend 响应测试,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28489067/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com