【发布时间】:2015-10-23 12:47:52
【问题描述】:
情况:
我正在我的 Angular 应用程序中测试 POST http 请求。
我已经做了几次尝试,但我总是收到以下错误:
Error: Unexpected request: POST http://my_api.com/accountLogin
No more request expected
功能:
该函数将提交登录数据,如果插入的数据正确,则返回“1”。
$scope.submit_login = function()
{
$http.post('http://my_api.com/accountLogin', {"api_access_key": $rootScope.access_key, "email": $scope.loginData.email, "password": $scope.loginData.password}, {"headers" : { "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }}).
.success(function(data, status, headers, config)
{
$scope.result = data;
})
.error(function(data, status, headers, config)
{
console.log('error ');
});
};
测试:
目的是将响应模拟为 1 并期望 $scope.result = 1
describe('My account functions test', function()
{
beforeEach(inject(function()
{
var mockLoginResponse = 1;
$httpBackend
.when('POST', 'http://my_api.com/accountLogin','{"headers" : { "Content-Type" : "application/x-www-form-urlencoded; charset=UTF-8" }}',
{
api_access_key: 'hardcode_access_key',
email: 'hardcoded_email',
password: 'hardcoded_password'
})
.respond(200, mockLoginResponse);
}));
it('submit_login() properly working', function()
{
$scope.submit_login();
$httpBackend.flush();
expect($scope.result).toEqual( 1 );
});
});
问题:
为什么会出现这个错误?
我做错了什么?
这是测试 POST 请求的正确方法吗?
谢谢!
【问题讨论】:
标签: javascript angularjs unit-testing jasmine karma-runner