Angularjs 角指令的Jasmine单元测试

Angularjs 角指令的Jasmine单元测试,angularjs,unit-testing,angularjs-directive,jasmine,Angularjs,Unit Testing,Angularjs Directive,Jasmine,我有下面的angular指令,当我将鼠标悬停在跨度上时,它会添加一个工具提示 angular.module('mainMod') .directive('toolTip', [function() { return { restrict: 'A', scope: { theTooltip: '@toolTip' }, link: function

我有下面的angular指令,当我将鼠标悬停在跨度上时,它会添加一个工具提示

angular.module('mainMod')
    .directive('toolTip', [function() {
        return {
            restrict: 'A',
            scope: {
                theTooltip: '@toolTip'
            },
            link: function(scope, element, attrs){
                element.tooltip({ 
                        delay: 0, 
                        showURL: false, 
                        bodyHandler: function() {
                            return jQuery('<div class="hover">').text(scope.theTooltip);
                        } 
                });
            }
        }
    }])
    ;


<span ng-show="data.tooltip" class="icon" tool-tip="{{data.tooltip}}"></span>

我认为这是由我在上面指定的行末尾的($rootScope)引起的。

任何单元测试基本上都是相同的-模拟环境,构造单元,检查单元是否以预期的方式与环境交互。在本例中,您可能希望模拟工具提示创建者

spyOn(jQuery.fn, 'tooltip');
然后使用指令编译一些模板(您已经在这样做了),然后在编译的元素上模拟悬停事件,然后检查是否以预期的方式调用了工具提示创建者

expect(jQuery.fn.tooltip).toHaveBeenCalledWith(jasmine.objectContaining({
    // ... (expected properties)
}));

模拟事件的方式取决于
元素的工作方式。工具提示
。如果它真的像您在问题代码中使用它那样工作,您根本不需要模拟任何东西,只需在模板编译之后立即检查预期的交互。

在编译之前,您必须先用angular.element包装DOM内容。我不确定您使用的工具提示模块是什么,但我使用了jQuery UI工具提示

    //create a new scope with $rootScope if you want
    $scope  = $rootScope.$new();

    var element = angular.element("<span class='icon' tool-tip='This is the tooltip data'></span>");

    //use the current scope has just been created above for the directive
    $compile(element)($scope);
基于此参考:


您可以在这里找到可用的小提琴:

非常感谢。正如我在问题中所描述的那样,它确实起作用。我想我已经很好地理解了应该采取的步骤,但是在我上面强调的那一行中,测试失败了,我不知道为什么。@Daft然后你需要做一点调试,准确地找出失败的原因。在这里,我对
工具提示
一无所知,只看到了3种可能不存在的东西--
.tooltip
插件、
jQuery
函数和
文本
函数。找出它是哪一个,并相应地采取行动。@Daft On sidenote,您真的不应该使用
jQuery(“”)
来创建元素。可以使用
jQuery(“”).addClass('hover')
(通过标记名创建元素)或
jQuery(“”)
(正确的HTML片段)。根据,您不必包装任何东西,字符串模板就可以了。另外,从外部测试单元时,不必担心得到隔离的作用域。您是否尝试过不使用angular.element,因为当我删除该部分时,它会导致错误。可能它与AngularJS版本有关。我使用
$compile
在各种AngularJS版本的所有指令测试中编译字符串模板,没有任何问题。你能用$compile而不使用AngularJS元素更新我的小提琴吗?太棒了:)哇,非常感谢。隔离作用域部分如何,有没有获得指令作用域的方法?
expect(jQuery.fn.tooltip).toHaveBeenCalledWith(jasmine.objectContaining({
    // ... (expected properties)
}));
    //create a new scope with $rootScope if you want
    $scope  = $rootScope.$new();

    var element = angular.element("<span class='icon' tool-tip='This is the tooltip data'></span>");

    //use the current scope has just been created above for the directive
    $compile(element)($scope);
   element.isolateScope()