如何在Angular 6 UI测试中检查组件是否已显示(* ngIf)

时间:2018-09-17 09:47:04

标签: angular jasmine angular-test

我正在尝试在Angular 6中为我的组件编写UI测试,并且想要验证是否已显示我的组件。该组件通过* ngIf有条件显示。

<tbody>
    <ng-container *ngFor="let data of summaryData">
        <tr>
            <td>
                <app-icon *ngIf="data.isFlagSelected"></app-icon>
                {{data.description}}
            </td>
[...]

这是我所做的:

describe("MyComponent", () => {
    let component: MyComponent;
    let fixture: ComponentFixture<MyComponent>;
    let de: DebugElement[];
    let elRows: HTMLElement[];

    beforeEach(async(() => {
        TestBed.configureTestingModule({
            declarations: [MyComponent]
        }).compileComponents().then(() => {
            fixture = TestBed.createComponent(MyComponent);
            component = fixture.componentInstance;

            de = fixture.debugElement.queryAll(By.css("table tbody tr"));
            elRows = de.reduce((acc, curr) => acc.concat(curr.nativeElement), []);
        });
    }));

    it("should display icon when flag === true", () => {

        // data1 has Description SomeRecord_1 and data.isFlagSelected=true
        const data1 = elRows.find(e => e.innerText.includes("SomeRecord_1")).getElementsByTagName("td")[0];

        // data2 has Description SomeRecord_2 and data.isFlagSelected=false
        const data2 = elRows.find(e => e.innerText.includes("SomeRecord_2")).getElementsByTagName("td")[0];

        expect(data1.getElementsByTagName("app-icon").length).toBeTruthy();
        expect(data2.getElementsByTagName("app-icon").length).toBeFalsy();
    });
});

效果很好!但是我想知道我是用正确的方式做的还是我可以以某种方式做得更好。

0 个答案:

没有答案