如何从一个指令,而不是在角度单元测试控制器模拟一个范围 [英] how to mock a scope from a directive instead of a controller in angular unit-test

查看:160
本文介绍了如何从一个指令,而不是在角度单元测试控制器模拟一个范围的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我熟悉的嘲讽一个$范围和控制器以$控制器构造函数的概念

so i am familiar with the concept of mocking a $scope and controller with a $controller constructor

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

有没有办法嘲笑以同样的方式指令?这两个指令及其控制器?

is there a way to mock a directive in the same way? both a directive and its controller?

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

意味着目标指令的问题,如何对它们进行测试?如何提取它们的组件?从我知道如果我对指令功能,我需要把它连接到一个范围,否则,如果它属于指令则函数是联合国测试。所以,如果我想在测试过程中使用的范围如何范围注入一个变量?

the question meant to target directives, how to test them? how to extract their components? from what i know if I had a function on directive, i need to attach it to a scope or else if it belongs to directive then the function is un-testable. so if i want to use the scope during the test how to inject the scope into a variable?

推荐答案

我设置了​​指令,规范的方式是

The way I set up directive-specs is

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

基本上我编译声明我的指令一个HTML字符串和我注射范围运行所产生的作用。然后使用jQuery(或JQueryLite)与元素交互或直接在范围做断言

这篇关于如何从一个指令,而不是在角度单元测试控制器模拟一个范围的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆