情况:
我正在我的角应用中测试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请求的正确方法吗?
谢谢!
答案 0 :(得分:1)
您缺少期望定义。请参阅下文 - 带有示例的文档,其中显示了期望值 - https://docs.angularjs.org/api/ngMock/service/ $ httpBackend。
it('submit_login() properly working', function()
{
$httpBackend.expectPOST('http://my_api.com/accountLogin'); //This is what you are missing
$scope.submit_login();
$httpBackend.flush();
expect($scope.result).toEqual( 1 );
});