简体   繁体   中英

How can I unit test that a PrimeNg p-button is disabled?

I'm writing a component that wraps (some) PrimeNg buttons. I am trying to write a unit test that checks if the button is disabled based on some settings on the outer component.

But, the disabled field is always undefined? I can see in the Karma/Jasmine screen that it is indeed disabled, so I'm confused as to why I can't get the test to work.

The html template includes:

<p-button id="submit" label="Submit" [disabled]="!enableSubmit"">
</p-button>

and the test is:

    fit('should disable submit button', done => {
        component.enableSubmit = false;

        fixture.detectChanges();

        fixture.whenStable().then(() => {
            const elem = fixture.debugElement.query(By.css('#submit'));
            const button = elem.nativeElement as Button;
            expect(button.disabled).toEqual(true);
            done();
        });
    });

And the result is:

    Expected undefined to equal true.
    Error: Expected undefined to equal true.

For whatever design reason, the disabled tag is not actually present on the outer PrimeNg p-button element in the Html.

Instead there is an inner button which holds the actual disabled flag, and the test can be slightly modified as follows:

  1. Change the css selector to find the inner button.
  2. Change the native element type to HtmlButtonElement.
    fit('should disable submit button', done => {
        component.enableSubmit = false;

        fixture.detectChanges();

        fixture.whenStable().then(() => {
            const elem = fixture.debugElement.query(By.css('#submit > button'));
            const button = elem.nativeElement as HTMLButtonElement;
            expect(button.disabled).toEqual(true);
            done();
        });
    });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM