【问题标题】:How to fix this unit test in my case?在我的情况下如何修复这个单元测试?
【发布时间】:2015-10-14 18:22:21
【问题描述】:

我正在尝试对我的指令进行单元测试。

我有类似的东西

'use strict';
describe('directive test', function () {
    var $compile, $rootScope, httpBackend, ngFactory;

    beforeEach(module('myApp'));

    beforeEach(inject(function (_$compile_, _$rootScope_, _$httpBackend_, _ngFactory_) {
        $compile = _$compile_;
        scope = _$rootScope_.$new();
        $httpBackend = _$httpBackend_;
        ngFactory = _ngFactory_;

        $httpBackend.whenGET('template.html').respond(200);
    }));

    it('this will setup directive', function() { 
        var elem = $compile('<my-factory factoryName="name1"></my-factory>')(scope);      
        scope.$digest(); 
        expect(scope.run).toBe(1);   
    });
});

我的指令

(function(window, angular) {
    'use strict';
    var app = angular.module('myApp');
    app.directive('myFactory', ['ngFactory',
        function(ngFactory) {
            return {
                restrict: 'E',
                templateUrl:'template.html',
                link: function(scope, elem, attrs) {  //not cover               
                    scope.test = function() {         //not cover
                        //do stuff here               //not cover
                    };                                //not cover
                }                                     //not cover
            };
        }
    ]);
})(window, angular);

由于某种原因,我的单元测试没有涵盖链接功能。我不确定我做错了什么。有人可以帮我吗?谢谢!

【问题讨论】:

    标签: javascript angularjs unit-testing karma-runner


    【解决方案1】:

    您还需要刷新模板请求:

    it('this will setup directive', function() { 
        var elem = $compile('<my-factory factoryName="name1"></my-factory>')(scope);      
        $httpBackend.flush();
        scope.$digest(); 
        expect(scope.run).toBe(1);   
    });
    

    确保加载和呈现正确的模板。

    【讨论】:

      猜你喜欢
      • 2020-05-20
      • 2021-12-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-12-01
      • 2023-01-09
      • 2021-11-30
      • 1970-01-01
      相关资源
      最近更新 更多