【问题标题】:how to write a unit test case for the following angular function如何为以下角度函数编写单元测试用例
【发布时间】:2016-05-11 21:19:45
【问题描述】:

如何为以下角度函数编写单元测试用例。我是业力和茉莉花的新手。具有 rootscope 的函数,并且还必须在 if 语句中测试 window.open。

  $rootScope.getStandardMapPDF = function (mt, g, u, m) 
        {

    var menuTitle = mt.trim();
    var grade = g.trim();
    var unit = u.trim();
    var module = m.trim();
    /*---->Getting the Grade, Unit and Module wise Help files <-------*/
    if ($.isEmptyObject($rootScope.StandardMapFiles)) {
        $rootScope.StandardMapFiles = DataProvider.StandardHelpMaster;
    }

    var obj = $rootScope.StandardMapFiles;
    for (var i = 0; i < obj.length; i++) {
        if (obj[i].Grade.toLowerCase().indexOf(grade.toLowerCase()) != -1 && obj[i].Unit.toLowerCase().indexOf(unit.toLowerCase()) != -1 && obj[i].Module.toLowerCase().indexOf(module.toLowerCase()) != -1 && obj[i].MenuTitle.toLowerCase() == menuTitle.toLowerCase()) {
            if (obj[i].FileType.toLowerCase() == 'pdf') {
                var path = 'Resources/StandardMappings/' + obj[i].FileName.trim() + '.pdf';
                //var path = '/fs/oleshare/ole-mygen/StandardMappings/' + obj[i].FileName.trim() + '.pdf';
                $window.open(path, '_blank');
            }
            else if (obj[i].FileType.toLowerCase() == 'video') {
                var path = 'Resources/Video/' + obj[i].FileName.split('.')[0].trim() + '.htm';
                $window.open(path, '_blank');
            }
        }
    }
};

【问题讨论】:

    标签: javascript angularjs jasmine karma-runner


    【解决方案1】:

    以下是编写测试的基本大纲:

    (function() {
        describe('your.controller.name.js', function() {
            var $rootScope, $window;           
    
            // Init
            beforeEach(module('your-app-name'));
            beforeEach(inject(function(_$rootScope_,_$window_) {
                $rootScope = _$rootScope_;
                $window = _$window_;
            }));
    
        // Spies
        beforeEach(function() {
            spyOn($window,'open');
        });
    
        it('should be defined', function() {
            expect($rootScope.getStandardMapPDF).toBeDefined();
        });
        describe('$rootScope.getStandardMapPDF', function() {
            beforeEach(function() {
                $rootScope.getStandardMapPDF()
            });
            it('should call $window.open', function() {
                expect($window.open).toHaveBeenCalled();
            });
        });
    }());
    

    你为什么要在$rootScope 上附加一个函数?

    【讨论】:

      猜你喜欢
      • 2021-06-12
      • 2021-06-12
      • 1970-01-01
      • 2019-04-13
      • 2021-12-08
      • 2021-09-13
      • 1970-01-01
      • 1970-01-01
      • 2020-06-27
      相关资源
      最近更新 更多