如何在角度单位测试中从指令而不是控制器模拟范围

use*_*582 4 unit-testing mocking angularjs karma-runner

所以我熟悉使用$ controller构造函数模拟$ scope和controller的概念

var scope = rootScope.$new();
it('should contain a testVar value at "test var home"', function(){
    homeCtrl = $controller('homeCtrl', {
        $scope: homeScope,
        $rootScope: rootScope
    })

    expect(homeScope.testVar).toBe('test var home');
})
Run Code Online (Sandbox Code Playgroud)

有没有办法以同样的方式模拟指令?指令和它的控制器?

//mock coding
var scope = rootScope.$new();
it('should contain a testVar value at "test var home"', function(){
    homeDir = $directive('homeCtrl', {
        $scope: homeScope,
        $elem: angular.element('<div....</div>'),
        $att: {}
        $modelViewController: angular.element().controller('ngModel')
    })
            homeCtrl = homeDir.$getController();
    expect(homeScope.testVar).toBe('test var home');
})
Run Code Online (Sandbox Code Playgroud)

这个问题意味着针对指令,如何测试它们?如何提取他们的组件?根据我所知道的,如果我在指令上有一个函数,我需要将它附加到一个作用域,否则如果它属于指令那么该函数是不可测试的.所以,如果我想在测试期间使用范围如何将范围注入变量?

iva*_*rni 6

我设置指令规范的方法是

beforeEach(inject(function($rootScope, $compile) {
    var htmlString = '' +
        '<my-directive some-attr="value">' +
        '</my-directive>'
        ;
    element = angular.element(htmlString)
    scope = $rootScope.$new();
    $compile(element)(scope);
    scope.$digest();
}));
Run Code Online (Sandbox Code Playgroud)

基本上我编译了一个声明我的指令的HTML字符串,并使用我注入的范围运行结果函数.然后我使用JQuery(或JQueryLite)element直接与the 或do断言进行交互scope