web-dev-qa-db-ja.com

Angular CDKテストハーネスを使用した材料選択コンポーネントをテストできません

Angular Material Componentsを使用するコンポーネントのテストを記述しようとしています。CDKテストハーネスについて読みます https://material.angular.io/guide/using- component-harnesses とそれに基づいて、Mat Selectコンポーネントのオプションの数をフェッチしたいと思います。

<mat-card>
  <mat-card-content>
    <form [formGroup]="filterLikelihoodForm" (ngSubmit)="onSearchClick()">
      <div class="container">
        <div class="row align-items-center">
          <div class="col-sm">
            <mat-form-field class="full-width" id="periodField">
              <mat-label>Select Period</mat-label>
              <mat-select formControlName="period" id="period">
                <mat-option *ngFor="let period of periodList" [value]="period.id">
                  {{ period.monthName }}
                </mat-option>
              </mat-select>
              <mat-error *ngIf="f.period.errors">
                Please select a valid period
              </mat-error>
            </mat-form-field>
          </div>
          <div class="col-sm">
            <mat-form-field class="full-width">
              <input
                matInput
                type="number"
                formControlName="finishedDeals"
                placeholder="Enter no of finished deals"
              />
              <mat-error *ngIf="f.finishedDeals.errors">
                Please enter a valid number
              </mat-error>
            </mat-form-field>
          </div>
          <div class="col-sm">
            <button
              mat-flat-button
              color="primary"
              [disabled]="filterLikelihoodForm.invalid"
              class="full-width"
            >
              Search
            </button>
          </div>
        </div>
      </div>
    </form>
  </mat-card-content>
</mat-card>

これが私のスペックファイルコードです:

import { HarnessLoader } from "@angular/cdk/testing";
import { TestbedHarnessEnvironment } from "@angular/cdk/testing/testbed";
import { TestBed, async, ComponentFixture } from "@angular/core/testing";
import { FilterLikelihoodComponent } from "./filter-likelihood.component";
import { MatFormFieldHarness } from "@angular/material/form-field/testing";
import { MatFormFieldModule } from "@angular/material/form-field";
import { ReactiveFormsModule } from "@angular/forms";
import { MatSelectModule } from "@angular/material/select";
import { MatCardModule } from "@angular/material/card";
import { MatButtonModule } from "@angular/material/button";
import { MatInputModule } from "@angular/material/input";
import { NoopAnimationsModule } from "@angular/platform-browser/animations";
import { periodListMock } from "./mock/filter-likelihood.mock";
import { MatSelectHarness } from "@angular/material/select/testing";
import { MatButtonHarness } from "@angular/material/button/testing";
import { Component } from "@angular/core";
import { MatInputHarness } from "@angular/material/input/testing";

describe("Filter Likelihood Component", () => {
  let testHostComponent: TestHostComponent;
  let testHostFixture: ComponentFixture<TestHostComponent>;

  let component: FilterLikelihoodComponent;
  let fixture: ComponentFixture<FilterLikelihoodComponent>;
  let loader: HarnessLoader;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [FilterLikelihoodComponent, TestHostComponent],
      imports: [
        ReactiveFormsModule,
        MatFormFieldModule,
        MatSelectModule,
        MatCardModule,
        MatButtonModule,
        MatInputModule,
        NoopAnimationsModule,
      ],
    }).compileComponents();
  }));

  beforeEach(() => {
    testHostFixture = TestBed.createComponent(TestHostComponent);
    testHostComponent = testHostFixture.componentInstance;
    testHostFixture.detectChanges();

    loader = TestbedHarnessEnvironment.loader(testHostFixture);
  });

  it("should have correct period label", async () => {
    const expectedLabel = "Select Period";
    const periodFieldHarness = await loader.getHarness<MatFormFieldHarness>(
      MatFormFieldHarness.with({ selector: "#periodField" })
    );
    const actual = await periodFieldHarness.getLabel();
    expect(actual).toBe(expectedLabel);
  });

  it("should have 3 recent periods in the dropdown", async () => {
    const expectedCount = 3;
    const selectHarness = await loader.getHarness<MatSelectHarness>(
      MatSelectHarness
    );
    const actual = ((await selectHarness.getOptions()).length);
    expect(actual).toBe(expectedCount);
  });

  it("should have a search button", async () => {
    const expectedLabel = "Search";
    const buttonHarness = await loader.getHarness<MatButtonHarness>(
      MatButtonHarness
    );
    const actual = await buttonHarness.getText();
    expect(actual).toBe(expectedLabel);
  });

  it("should have 10 finished deals by default", async () => {
    const expectedFinishedDeals = 10;
    const inputHarness = await loader.getHarness<MatInputHarness>(
      MatInputHarness
    );
    const actual = await inputHarness.getValue();
    expect(parseInt(actual)).toBe(expectedFinishedDeals);
  });

  it("should have a enabled button by default", async () => {
    const expectedDisabledState = false;
    const buttonHarness = await loader.getHarness<MatButtonHarness>(
      MatButtonHarness
    );
    const actual = await buttonHarness.isDisabled();
    expect(actual).toBe(expectedDisabledState);
  });

  @Component({
    selector: `Host-component`,
    template: `<app-filter-likelihood
      [periodList]="periodList"
      [initialFinishedDeals]="defaultFinishedDeals"
    ></app-filter-likelihood>`,
  })
  class TestHostComponent {
    periodList = new Helper().mockPeriodList;
    defaultFinishedDeals = 10;
  }
});

class Helper {
  mockPeriodList = periodListMock;
}

タイトル付きの2番目の仕様 "ドロップダウンに最近3つのピリオドが必要"は、オプションのカウントが常に0になるため失敗します。

誰かが私のバグを理解し、マットテストハーネスを使用してこの仕様を記述する正しい方法を教えてもらえますか?

前もって感謝します!

2
Arindam Dawn

Select Harness APIをいじくり回した後、私はこれを解決することができました。 Host要素を取得するように仕様を更新し、クリックイベントをトリガーしました。

  it("should have 3 recent periods in the dropdown", async () => {
    const expectedCount = 3;
    const selectHarness = await loader.getHarness<MatSelectHarness>(
      MatSelectHarness
    );

    //Click the select element Host
    (await selectHarness.Host()).click();
    const actual = (await selectHarness.getOptions()).length;
    expect(actual).toBe(expectedCount);
  });
1
Arindam Dawn

Select要素を開く前に、いくつかのオプションを取得しようとしています。

const selectHarness = await loader.getHarness<MatSelectHarness>(MatSelectHarness);
const count = (await selectHarness.getOptions()).length;  // count will be 0
await selectHarness.open();  // you can open matselect element via open method
const count = (await selectHarness.getOptions()).length;  // count will be as expected
0
quardem