javascript - 使用单元测试测试 ng-if div 是否正确显示

标签 javascript angularjs unit-testing

已关注 this question我正在使用以下方法来尝试使用 Karma 而不是 Protractor 来测试 ng-if 标记的 div 是否正确显示:

var element;

beforeEach(inject(function ($rootScope, $templateCache, $compile) {
  scope = $rootScope.new();
  fooController.init(scope); //Some controller function that sets properties on the scope
                             //which are tested for in the template
  scope.$digest();
  var template = $templateCache.get('/my/template');  //Get the cached template
  var compiled = compile(template)(scope);            //Compile it

  element = angular.element(compiled);                //Wrap it with jQuery functions
}));

it('should do something', function () {
  var div = element.find('#someDiv'); //Get some div that should be affected by ng-if
  expect(div.html()).toBeUndefined(); //Expect the div not to be shown due to properties that
                                      //were set by fooController.init
});

我的模板有这样的内容:

<!-- scope.shown should be set to false by fooController.init -->
<div id = "someDiv" ng-if = "shown">Foo</div>

在这里,我使用 expect(div.html()).toBeUndefine(); 因为 ngIf(与 ngShow 和 ngHide 不同)如果内部条件计算结果为,则会从 DOM 中删除整个 div false(ngShow 和 ngHide 将类应用于 div 以使其不显示)。

但是,当我运行它并打印出编译后的变量时,我发现 ngIf div 的 HTML 总是被拿走并替换为注释,无论 scope.shown 的值如何。

Karma 使用的 Angular 编译函数的工作方式是否与 Angular 本身在浏览器中实际渲染时的工作方式不同?我问这个问题是因为当我用浏览器测试它时,它显示正确,但是当我尝试对它进行单元测试时,它输出错误的信息。也许也是因为我使用 PhantomJS 进行 headless 测试,但使用 Google Chrome 自己测试?

最佳答案

您需要评估模板中显示的内容。尝试创建一个返回 true 或 false 的函数。然后将其添加到您的模板中。

ng-if = "GetShown([parameters]) === true"

因此 Controller 中的功能类似于

$scope.GetShown = function([parameters]){
     return [evaluation]
};

关于javascript - 使用单元测试测试 ng-if div 是否正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27114408/

相关文章:

angularjs - http : multiple response. WriteHeader 调用

angularjs - 如何在 ion-nav-view 中禁用/更改 View 之间的动画

javascript - Angularjs $routeParams 导致 RangeError : Maximum call stack size exceeded

c# - 在单元测试中将 DI 与没有依赖关系的模块/类一起使用是否有令人信服的理由?

javascript - 检测链式动画集的 "animationend"事件

javascript - Chrome 扩展程序中出现错误 "Cannot read property ' style' of null"

javascript - owl carousel 在 ajax 加载的项目上不能正常工作

javascript - 可能的 Safari 错误?修复了相对 div 内的 div 没有动画

android - 我很困惑何时使用仪器测试以及何时使用单元测试

unit-testing - Xamarin Studio 上的代码覆盖率