angularjs - 使用 karma 测试 Angular : how to set scope

标签 angularjs angularjs-directive karma-runner

我有一个相当复杂的 Angular 指令,称为 hy-plugin-window,我在 ng-repeat block ( complete directive code here ) 中使用它:

<div ng-repeat="pluginD in pluginsDisplayed">
    <div hy-plugin-window content="pluginD" remove="remove"></div>
</div>

该指令使用隔离范围,它双向链接到父级的 content 成员:

return {
        restrict: 'A',
        replace: true,
        link: linker,
        scope: {
            content:'=',
        }
    };

这意味着,当它创建时,列表中的每个指令都可以访问其唯一内容(它是对象 pluginsDisplayed 的单个成员)并执行以下操作:

scope.statusMessage = 'Loading ' + scope.content.name + '...';

一切正常,只是我不知道如何用 Karma 测试它。通过像这样的相当常见的测试,我希望手动设置指令内的范围:

'use strict';

describe('Directive: hyPluginWindow', function () {

    beforeEach(module('hyacinthHostApp'));

    var element, $compile, scope;

    beforeEach(inject(function(_$compile_, $rootScope) {
        $compile = _$compile_;
        scope = $rootScope.$new();
    }));


  it('should do something', inject(function () {

      scope.content = {
          name: "testElement",
          id: "testElement000",
          uiType: "canvas"
      };

      element = angular.element('<div hy-plugin-window></div>');
      element = $compile(element)(scope);

      //expect(...);
  }));
});

但它惨遭失败:

TypeError: Cannot read property 'name' of undefined

我的指令第一次尝试访问其scope.content.name

考虑到我是一个完全测试的新手,我错过了什么?

最佳答案

短篇故事:将编译元素更改为 <div hy-plugin-window content="content"></div>我认为它应该有效。

该指令具有 ISOLATE 作用域,这意味着它在原型(prototype)上不是从“常规”作用域继承的。

在您的测试中,您定义 content在常规作用域上,但指令本身是封装的 - 它具有隔离的作用域,因此看不到 content在常规范围内定义的属性。

您需要通过组件的显式接口(interface)来传达这一点,即 content属性。

关于angularjs - 使用 karma 测试 Angular : how to set scope,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17174694/

相关文章:

javascript - Angularjs 输入字段焦点事件?

android - 在 android 的 Ionic 项目中的位置

javascript - 从指令访问 AngularJS 范围

angular - 运行 karma 测试时出现错误无法读取 null 的属性 'extras'

search - Angular 全局搜索框

javascript - 将字符串从 Flask 传递到 AngularJS

javascript - angularjs 中服务执行的优先级和层次结构

javascript - Angular 、 promise 和异步功能

javascript - Ubuntu 上的 Karma-Runner : 'usr/bin/env: node: No such file or directory' error

sapui5 - 即使未满足测试覆盖率阈值, karma 覆盖退出代码始终为 0