简体   繁体   English

如何对 PrimeNg p-button 被禁用进行单元测试?

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

I'm writing a component that wraps (some) PrimeNg buttons.我正在编写一个包装(一些)PrimeNg 按钮的组件。 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.我可以在 Karma/Jasmine 屏幕中看到它确实被禁用了,所以我很困惑为什么我不能让测试工作。

The html template includes: html 模板包括:

<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.无论出于何种设计原因,Html 的外部 PrimeNg p 按钮元素上实际上并不存在禁用标签。

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.更改 css 选择器以找到内部按钮。
  2. Change the native element type to HtmlButtonElement.将本机元素类型更改为 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();
        });
    });

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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