【问题标题】:Karma-Jasmine: Error: Unexpected request: POSTKarma-Jasmine:错误:意外请求:POST
【发布时间】: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


    【解决方案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 );
        });
    

    【讨论】:

    • 谢谢!几乎可以工作了。如果我只留下没有标头和数据的 api 地址,它可以工作并且测试通过。如果我传递标题和数据,我会收到一个奇怪的错误。我已经尝试修改每一个小字符,但我仍然得到它:错误:预期 POST my_api.com/accountLogin 具有不同的数据预期:{“api_access_key”:“hardcoded_access_key”,“email”:“hardcoded_email”,“password”:“hardcoded_pa​​ssword” } GOT: {"api_access_key":"hardcoded_access_key"}
    • 不需要在expectPOST中传递header和data?
    • 1) 我不会担心标题,除非您需要用它测试特殊逻辑。简单的测试是我的目标:)
    • 2) .when 定义的语法已关闭。在前面的示例中,您的数据和标题被翻转(.when(method, url, [data], [headers], [keys]);)。另外,我建议对 headers 对象使用对象表示法。我没有测试,但文档说明 headers 参数只接受对象和函数(对象),而不是像 data 属性那样的字符串。
    猜你喜欢
    • 2015-07-08
    • 2016-01-17
    • 2023-03-19
    • 1970-01-01
    • 2014-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多