angularjs – 业力中服务呼叫成功响应的代码覆盖率

前端之家收集整理的这篇文章主要介绍了angularjs – 业力中服务呼叫成功响应的代码覆盖率前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这样的功能

$scope.openMail=function(mail){
      DocumentTypes.getDocument(function(response){
          $scope.documentTypes=response.result;
          $log.log("documentTypes",$scope.documentTypes);
          })
}

以上乐趣的规格是

it("should test open mail",function(){
    scope.documentTypes=[{"type":"pdf"},{"type":"xml"}];
    spyOn(documentTypes,"getDocument").and.callFake(function(){
      return scope.documentTypes;
    });
    var mail='back';
    scope.openMail(mail);
    expect(scope.documentTypes).toEqual({"type":"pdf"},{"type":"xml"});


  })

所以代码没有涵盖功能(响应){}

so the code is not covering code for <code>function(response){}</code>


如何在代码覆盖中涵盖此代码?谢谢.

解决方法

您的测试有几个问题:

>你做spyOn(documentTypes,“getDocument”)而不是spyOn(DocumentTypes,“getDocument”)
>你的假函数返回一个值(同步)而不是调用提供的回调(异步)
>首先将scope.documentTypes初始化为测试的预期结果,即无论代码做什么,测试都会通过(除非你得到例外)
>更多代码问题 – 您正在测试的函数对输入邮件参数没有任何作用

这是我将如何测试它:

describe('$scope.openMail',function() {
    beforeEach(function() {
        spyOn(DocumentTypes,'getDocument');
    });

    it('uses DocumentTypes.getDocument service to get the document types',function() {
        $scope.openMail('test_mail');

        expect(DocumentTypes.getDocument).toHaveBeenCalledWith(jasmine.any(Function));
    });

    describe('provides a callback function that',function() {
        beforeEach(function() {
            DocumentTypes.getDocument.and.callFake(function (callback) {
                callback('test_document_types');
            });
        });

        it('stores the document types on the scope',function() {           
            $scope.openMail('test_mail');

            expect($scope.documentTypes).toEqual('test_document_types');
        });

        // Note: This is optional,depending on whether you test logging or not
        it('logs the document types',function() {           
            spyOn($log,'log');

            $scope.openMail('test_mail');

            expect($log.log).toHaveBeenCalledWith('documentTypes','test_document_types');
        });
    });
});

猜你在找的Angularjs相关文章