【问题标题】:How to check if element is visible on AngularJS template?如何检查元素是否在 AngularJS 模板上可见?
【发布时间】:2015-11-24 10:37:15
【问题描述】:

我有一个 AngularJS 控制器和与之关联的 HTML 模板。我在模板中有一个“保存”按钮。我想用 Jasmine 编写一个测试来检查按钮在特定条件下是否可见。

对于指令,我测试了这些东西没有任何问题。但这不是指令。

当你没有指令但只有控制器和HTML模板视图时如何测试这种情况?

【问题讨论】:

  • 你可以$compile() 一个模板,ng-includes 你要测试的模板。
  • @NikosParaskevopoulos 你能写更多吗?

标签: javascript angularjs jasmine bdd karma-jasmine


【解决方案1】:

如果不是指令,你应该可以只用控制器来测试它(它应该有一个控制状态的变量)。

如果您需要测试模板,建议您为该功能创建一个指令,然后编写测试。

编辑:另一种选择是使用 ng-include 为模板和 ng-controller 为控制器模拟指令,然后使用 $compile 服务对其进行编译。查找测试指令的示例并替换 ng-include 和 ng-controller 之间的混合指令,您将能够对其进行测试。

来自 Angular 文档的示例已修改。

describe('Unit testing great quotes', function() {

  var $compile, $rootScope;

  // Load the myApp module, which contains the directive
  beforeEach(module('myApp'));

  // Store references to $rootScope and $compile
  // so they are available to all tests in this describe block
  beforeEach(inject(function(_$compile_, _$rootScope_){
    // The injector unwraps the underscores (_) from around the parameter names when matching
    $compile = _$compile_;
    $rootScope = _$rootScope_;
  }));

  it('Replaces the element with the appropriate content', function() {
    // Compile a piece of HTML containing the directive **I replaced the directive for the controller and view template**
    var element = $compile("<div ng-controller="yourController"><div ng-include="yourViewTemplate"></div></div>")($rootScope);
    // fire all the watches, so the scope expression {{1 + 1}} will be evaluated
    $rootScope.$digest();
    // Check that the compiled element contains the templated content
    expect(element.html()).toContain("lidless, wreathed in flame, 2 times");
  });
});

另外,你不知道用手机写代码有多难哈哈

【讨论】:

  • 这是一个很好的解决方法,但不是直接的解决方案。
  • 没错,我添加了其他信息。
  • 我花了很长时间才弄清楚我的问题是我没有嵌套我的 ng-include。我正在使用它,它总是失败,该元素不包含 html:var element = $compile("&lt;div ng-controller="yourController" ng-include="yourViewTemplate"&gt;&lt;/div&gt;")($rootScope);
猜你喜欢
  • 2017-01-01
  • 2012-07-08
  • 1970-01-01
  • 2012-04-21
  • 2014-04-22
  • 2020-08-06
  • 2015-03-29
  • 2016-04-18
  • 1970-01-01
相关资源
最近更新 更多