【问题标题】:Angular 2 setTimeout e2e tests failsAngular 2 setTimeout e2e 测试失败
【发布时间】:2017-07-03 17:49:29
【问题描述】:

我有一个组件可以计算“afterViewChecked”生命周期中的属性,所以我需要使用 setTimeout - 应用更改,否则我会出错。 (Angular 4 Changes based on view)

我刚刚发现 setTimeout,无论在我的应用程序中的哪个位置都会导致量角器抛出超时消息。 - 上面写着

Failed: Timed out waitig for asynchronous angular tasks to finish..... - 这可能是因为当前页面不是 Angular 应用程序”,

我该怎么办? - 有时你只需要使用 setTimeout...

【问题讨论】:

  • 您需要一种方法来在 DOM 元素被渲染后触发函数?
  • 嗯,是的,在项目被渲染之后,我需要计算一些 dom 属性,如果它们满足条件 - 来触发一个函数。我的应用程序中另一个超时的地方是在启动时,但它是暂时的。如果我删除这 2 个超时,测试就可以了。
  • 好的。您的setTimout 的目的是在渲染元素后触发一个函数?为了避免setTimeout-问题,另一种方法可以吗?另一种检查是否呈现的方法。
  • 好吧,我想不出其他方法,我可以调用 markForDetection,但我担心可能会出现无限循环之类的情况。
  • 我在一个答案中整理了一个例子

标签: angular protractor


【解决方案1】:

检测 DOM 更改的另一种方法是通过 MutationObserver。在构造函数中实例化该类,您可以在其中定义对更改执行的操作,然后在ngAfterViewInit() 中观察它。当你运行你想要的计算函数时,你可以停止观察,这样如果发生进一步的变化,函数就不会继续触发。

import { Component, AfterViewInit } from '@angular/core';

@Component({
  selector: 'app-test',
  template: `<div #element></div>`
})
export class TestComponent implements AfterViewInit {
  @ContentChild('element') element : ElementRef;
  this.observer: MutationObserver;

  constructor() {
    this.observer = new MutationObserver(mutations => {
      this.testFunction();
    });
  }

  ngAfterViewInit() {
    this.observer.observe(this.element.nativeElement, { attributes: true, childList: true, characterData: true });
  }

  testFunction() {
    this.observer.disconnect(); // We no longer want to observe
    alert('Test!');
  }

}

【讨论】:

    【解决方案2】:

    您需要将 $timeout 替换为 $interval,它会起作用。 “如果您的页面使用 $timeout 进行轮询,Protractor 将无法判断您的页面何时准备就绪。请考虑使用 $interval 而不是 $timeout。”

    他们的官方文档:http://www.protractortest.org/#/system-setup https://github.com/marcorinck/angular-growl/issues/43

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-04-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-10
      • 2018-12-03
      • 1970-01-01
      相关资源
      最近更新 更多