首页 > 解决方案 > 在 Karma 上测试异步用户界面操作

问题描述

我在下面进行了以下测试,其中我更新了一个文本字段,之后进行了 API 调用,然后,我希望另一个文本字段根据 API 响应具有相同的值。但是,它一直失败,错误Expected '0' to equal '2'.是我期望根据 API 的响应得到 2 = 2 的结果。知道如何解决这个问题吗?

Stackblitz 在这里:https ://stackblitz.com/edit/http-get-post-dgcuur

测试

it('should successfuly convert A to A', fakeAsync(() => {
      fixture.detectChanges();
      fixture.whenStable().then(() => {
        let fromAmountValueEl = fixture.debugElement.query(By.css('#fromAmountValue')).nativeElement;
        expect(fromAmountValueEl.value).toEqual('0');
        let toAmountValueEl = fixture.debugElement.query(By.css('#toAmountValue')).nativeElement;
        expect(toAmountValueEl.value).toEqual('0');
        fromAmountValueEl.value = '2'
        fromAmountValueEl.dispatchEvent(new Event('input'));
        fromAmountValueEl.dispatchEvent(new KeyboardEvent('keyup', {
          'key': 'Enter'
        }));
        tick();
        fixture.whenStable().then(() => {
          fixture.detectChanges();
          expect(fromAmountValueEl.value).toEqual('2');
          expect(toAmountValueEl.value).toEqual('2');
        });
      });
    }));

看法

      <input class="form-control form-control-lg" type="number" placeholder="0" [(ngModel)]="fromAmount"
        (keyup)="updateRates()" id="fromAmountValue">
      <select class="form-control form-control-lg" id="fromCurrency">
        <option value="GBP">GBP</option>
      </select>

      <input class="form-control form-control-lg" type="number" placeholder="0" [(ngModel)]="toAmount"
        (keyup)="updateRates()" id="toAmountValue">
      <select class="form-control form-control-lg" [(ngModel)]="toCurrency" id="toCurrency">
        <option value="GBP">GBP</option>
      </select>

控制器

  updateRates() {
    this.postSubscription = this.post().subscribe((data) => {
      if(data) {
        this.result = data;

        if (this.toCurrency == "GBP") {
          this.toAmount = this.fromAmount;
        }
      }
    });
  }

标签: angularkarma-runner

解决方案


推荐阅读