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"});


  })

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

《angularjs – 业力中服务呼叫成功响应的代码覆盖率》
如何在代码覆盖中涵盖此代码?谢谢.

最佳答案 您的测试有几个问题:

>你做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');
        });
    });
});
点赞