在Angular 4单元测试中未调用ngOnChanges detectChanges()

Pau*_*ton 5 unit-testing promise angular-components angular angular-unit-test

问题

我有一个按钮组件,它接受承诺并禁用按钮,直到承诺解决为止,并且我想为此功能编写单元测试。

我的密码

我的按钮组件有一个承诺的输入

  /**
   * A single promise that triggers the busy state until it resolves
   */
  @Input()
  public promise: Promise<any>;
Run Code Online (Sandbox Code Playgroud)

在ngOnChanges内部,我听了承诺

/**
 * Enable button busy state until promise resolves
 */
if (changes && changes.promise && changes.promise.currentValue) {
  this.busyUntilPromiseResolves(changes.promise.currentValue);
}
Run Code Online (Sandbox Code Playgroud)

然后,我存储了一个有效的promise数组,以便可以传递多个promise

  /**
   * Add a promise that will keep the button in a busy state until it resolves
   * @param activityProimise
   */
  private busyUntilPromiseResolves(activityProimise) {
    this.activityPromises.push(activityProimise);
    activityProimise.then(() => {
      this.activityPromises.splice(this.activityPromises.indexOf(activityProimise), 1);
    });
  }
Run Code Online (Sandbox Code Playgroud)

然后最后在我的模板中,如果数组中有任何promise,我将禁用按钮。

[disabled]="activityPromises.length > 0"
Run Code Online (Sandbox Code Playgroud)

帮我带完

我一直在尝试并尝试各种不同的方法以使其正常工作,这是我当前无法使用的测试代码。基本上,我需要在承诺解决之前检查该按钮是否已禁用,然后我将要执行另一个测试,以检查在承诺解决后是否已重新启用该按钮。

  it('should be disabled when passed a single promise', async((done) => {
    let promise;

    return promise = new Promise(resolve => {
      component.promise = promise;
      fixture.detectChanges();
      expect(buttonElement.disabled).toBe(true);
      return resolve();
    });
  }));
Run Code Online (Sandbox Code Playgroud)

一如既往,任何帮助将不胜感激,谢谢。

Pau*_*ton 7

这个问题的简短回答是 ngOnChanges 在单元测试期间不会自动触发,所以我不得不手动调用它。

  it('should be disabled when passed a single promise', async () => {
    let promise;
    let resolve;

    // should not be disabled here
    expect(buttonElement.disabled).toBe(false);

    // Pass a promise to the component to disable it
    promise = new Promise(r => resolve = r);
    component.ngOnChanges({
      promise: new SimpleChange(null, promise, null)
    });

    fixture.detectChanges();
    expect(buttonElement.disabled).toBe(true);

    // now resolve the promise and make sure it's enabled again.
    promise.then(() => {
      fixture.detectChanges();
      expect(buttonElement.disabled).toBe(false);
    });

    resolve();

  });
Run Code Online (Sandbox Code Playgroud)