ngAnimate 1.4.7单元测试不调用动画函数

2024-01-18

我一直在工作本教程 http://www.sitepoint.com/angularjs-testing-tips-bootstrap-blocks-routes-events-animations/并在谷歌上进行了令人作呕的搜索,但我似乎无法得到看似微不足道的东西ngAnimate单元测试运行。

I have ngAnimate在应用程序中运行良好。所有 Angular 核心库的版本均为 1.4.7。

Module

angular.module 'MyAnimation', [ 'ngAnimate' ]
  .animation '.added-class', ->
    addClass: (element, className, done) ->
      console.log 'add class triggered'
      element.css 'opacity', '0.5'
      done()

Test

describe 'MyAnimation', ->
  beforeEach -> module 'ngAnimate'
  beforeEach -> module 'ngAnimateMock'
  beforeEach -> module 'MyAnimation'

  it 'animates', -> inject ($animate, $rootScope, $rootElement) ->
    $animate.enabled(true)
    divElement = angular.element '<div>my div</div>'

    # Kick off initial digest loop in which no animations are run.
    $rootScope.$digest()

    # Trigger animation.
    $animate.addClass divElement, 'added-class'
    $rootScope.$digest()

    # Tried this, doesn't seem to do anything.
    # $animate.flush()

    # Results in AssertionError: expected '' to equal '0.5'
    expect(divElement.css('opacity')).to.eq '0.5'

我确定该模块已包含在测试中,但正在触发$animate.enter甚至没有得到我的log输出。

我和其他人一起尝试过这个$animate功能也很好,但一事无成。帮助?


经过认真研究 Angular 的源代码后,看来罪魁祸首是内部检查areAnimationsAllowed https://github.com/angular/angular.js/blob/bfad2a4f4ae71cfead61c112b0d2ab1fcadd39ee/src/ngAnimate/animateQueue.js#L533Angular 使用它来确定是否提前中止动画。除其他外,它检查正在动画的节点是否是$rootElement和文档正文。

这里你有两个选择。

  1. Plunker http://plnkr.co/edit/GhQFwIDJ9HEEQbNgLmGY?p=preview. 附加您要设置动画的节点$rootElement并附上$rootElement对身体。后者是必要的,因为ngMock实际上存根$rootElement与一个分离的<div>节点保存在内存中。Example:
var element, body, root;
beforeEach(module('ngAnimate', 'ngAnimateMock', 'MyAnimation'));
beforeEach(inject(function ($animate, $document, $rootElement, $rootScope) {
  // enable animations globally
  $animate.enabled(true);

  // create a node to be animated and inject it into the DOM
  element = angular.element('<div></div>');
  root = $rootElement.append(element)[0];
  body = $document[0].body;
  body.appendChild(root);

  // trigger initial digest
  $rootScope.$digest();
}));
afterEach(function () {
  // clean up
  body.removeChild(root);
});
  1. Plunker http://plnkr.co/edit/hXbzZybASa7NxdzZdSzr?p=preview。不要使用以下方式测试您的动画$animate.addClass, 但反而使用较低级别的$$animateJs service。角使用它在他们自己的测试中 https://github.com/angular/angular.js/blob/d077966ff1ac18262f4615ff1a533db24d4432a7/test/ngAnimate/animateJsSpec.js#L212,我假设绕过上述检查。Example:
it('should animate', inject(function ($animate, $$animateJs) {
  // trigger animation
  $$animateJs(element, 'addClass', {
    addClass: 'added-class'
  }).start();
  $animate.flush();
}));

如果您运行 Plunkers 并检查控制台,您应该会看到“addClass returned”消息。我还添加了一些断言。

这两种解决方案都是hacky且没有文档记录的,并且如果您的addClass动画做了一些异步的事情(我认为它会)。不幸的是,我找不到更好的方法来测试 JS 动画。在过去,我实际上忽略了覆盖率中的动画代码,因为它很难测试。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

ngAnimate 1.4.7单元测试不调用动画函数 的相关文章

随机推荐