【问题标题】:ngAnimate 1.4.7 unit test not calling animation functionsngAnimate 1.4.7 单元测试不调用动画函数
【发布时间】:2016-01-29 02:08:24
【问题描述】:

我一直在 this tutorial 工作,并在 Google 上搜索过令人作呕的东西,但我似乎无法获得看似微不足道的 ngAnimate 单元测试正在运行。

我的 ngAnimate 在应用程序中运行良好。所有 Angular 核心库都是 1.4.7 版本。

模块

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

测试

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 函数,但无济于事。帮忙?

【问题讨论】:

    标签: angularjs unit-testing coffeescript ng-animate


    【解决方案1】:

    在深入研究 Angular 的源代码之后,罪魁祸首似乎是内部检查 areAnimationsAllowed,Angular 使用它来确定是否提前中止动画。除此之外,它检查动画节点是否是$rootElement 和文档正文的后代。

    这里有两个选择。

    1. Plunker将要制作动画的节点附加到$rootElement,并将$rootElement 附加到主体。后者是必要的,因为ngMock 实际上存根$rootElement,并在内存中保存了一个分离的&lt;div&gt; 节点。 例子:
    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。不要使用$animate.addClass 测试您的动画,而是使用较低级别的$$animateJs 服务。 Angular 使用它inside their own tests,我假设绕过上述检查。 例子:
    it('should animate', inject(function ($animate, $$animateJs) {
      // trigger animation
      $$animateJs(element, 'addClass', {
        addClass: 'added-class'
      }).start();
      $animate.flush();
    }));
    

    如果您运行 Plunker 并检查控制台,您应该会看到“addClass 触发”消息。我还添加了几个断言。

    这两种解决方案都是 hacky 和无证的,如果您的 addClass 动画执行异步操作(我认为它会这样做),两者都会变得更加复杂。不幸的是,我找不到更好的方法来测试 JS 动画。过去我实际上忽略了覆盖范围内的动画代码,因为它很难测试。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-02-14
      • 2015-09-16
      • 2014-11-05
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-22
      • 1970-01-01
      相关资源
      最近更新 更多