javascript - 如何检查元素在 AngularJS 模板上是否可见?

标签 javascript angularjs jasmine bdd karma-jasmine

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

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

当你没有指令而只有 Controller 和 HTML 模板 View 时如何测试这种情况?

最佳答案

如果不是指令,您应该能够仅使用 Controller 来测试它(它应该有一个控制状态的变量)。

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

编辑:另一种选择是使用 ng-include 作为模板,使用 ng-controller 作为 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");
  });
});

而且,你不知道通过手机编写代码有多困难,哈哈

关于javascript - 如何检查元素在 AngularJS 模板上是否可见?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33891342/

相关文章:

javascript - jQuery 使用 insertAfter 创建的元素不起作用

javascript - 如何保持饼图中切片的顺序固定? [d3]

angularjs - Protractor (WebDriverJS)无法切换到窗口。 nameOrHandle 未定义

javascript - 如何阻止 Protractor 在失败时运行进一步的测试用例?

javascript - 在 Vue.js2 中使用哪个生命周期 Hook 在页面加载时调用函数?

ASP.NET - 脚本和 css 压缩

javascript - 在 Angular 中使用 ng-repeat 进行动态模型和脏检查

angularjs - 将 zip 文件从 Node api 流式传输到 Angular

javascript - Jasmine spy On javascript getter 导致 karma 挂起

angularjs - 如何在指令中对 watch 表达式进行单元测试