Karma-Jasmine: Error: Unexpected request: POST

Karma-Jasmine: Error: Unexpected request: POST

情况:

我正在 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 请求的正确方法吗?

谢谢!

您缺少期望定义。见下文 - 可以在此处找到显示期望的示例文档 - 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 );
    });