angularjs - Karma 中服务调用成功响应的代码覆盖率

标签 angularjs unit-testing karma-jasmine

我有一个这样的功能

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


  })

因此代码未涵盖function(response){}

so the code is not covering code for <code>function(response){}</code> 如何在我的代码覆盖范围中覆盖此代码?谢谢。

最佳答案

您的测试有几个问题:

  1. 您执行 spyOn(documentTypes,"getDocument") 而不是 spyOn(DocumentTypes,"getDocument")
  2. 您的假函数返回一个值(同步),而不是调用提供的回调(异步)
  3. 首先将 scope.documentTypes 初始化为测试的预期结果,即无论代码做什么,测试都会通过(除非出现异常)
  4. 您的代码存在更多问题 - 您正在测试的函数对输入 mail 参数没有任何作用

这是我测试它的方法:

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 - Karma 中服务调用成功响应的代码覆盖率,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47301711/

相关文章:

javascript - 如何测试 $(window).on ("load", function() {}); 内的代码在 Jasmine

javascript - Angular 根据另一个 json 文件从一个 json 文件读取数据

使用 GeoDjango + PostGIS 进行 Django 测试

javascript - Karma 自动 watch 不工作

c# - c# 中可读性好的测试名称

unit-testing - Moq - 如何验证 Action<T>?

javascript - Jasmine - 无法获得异步调用的响应

ajax - 从网站表单写入谷歌文档时遇到 CORS 错误

javascript - Angularjs ng 单击清除输入并更新范围

javascript - ng-repeat 遍历对象中的对象