简体   繁体   English

我该如何修复此单元测试?

[英]How to fix this unit test in my case?

I am trying to do unit test for my directive. 我正在尝试对我的指令进行单元测试。

I have something like 我有类似的东西

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

My directive 我的指令

(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);

For some reason, my unit test doesn't cover the link function. 由于某些原因,我的单元测试没有涵盖链接功能。 I am not sure what I do wrong. 我不确定我做错了什么。 Can someone please help me out? 有人可以帮我吗? Thanks! 谢谢!

You will also need to flush the template request: 您还需要刷新模板请求:

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

Make sure the correct template is loaded and rendered. 确保正确的模板已加载并呈现。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM