You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何测试Stencil组件中按钮的disabled属性?

Stencil组件disabled属性测试问题解决

问题场景

我有一个简单的Stencil组件,运行时表现正常,但在测试disabled设为true时,发现组件prop确实为true,但HTML属性显示undefined,不知道如何正确检查按钮是否被禁用。

组件代码:

@Component({
  tag: 'app-filled-button',
  styleUrl: 'filled-button.css',
  shadow: true,
})
export class FilledButton {
  @Prop() disabled: boolean;

  render() {
    return (
      <button disabled={this.disabled}>
        <slot></slot>
      </button>
    );
  }
}

测试代码:

describe('testing filled button component', () => {
    let page: SpecPage;
    let host: HTMLElement;

    beforeEach(async () => {
        page = await newSpecPage({
            components: [FilledButton],
            html: '<app-filled-button disabled="true"></app-filled-button>'
        });

        host = page.body.querySelector('app-filled-button');
    });

    it('should be disabled', async () => {
        const button = host.shadowRoot.querySelector('button');
        expect(button.disabled).toBe(true);
    });
});

解决方案

问题核心在于布尔类型Prop的HTML写法和测试断言的正确方式,调整方案如下:

1. 修正HTML中布尔属性的写法

HTML里的布尔属性,只要存在就代表true,写disabled="true"会被解析为字符串值,而非布尔值。测试时应改用无值的布尔属性写法:

<app-filled-button disabled></app-filled-button>

2. 优化测试断言逻辑

可以从两个维度验证:组件的Prop值、渲染后按钮的状态。修改后的测试代码:

describe('testing filled button component', () => {
    let page: SpecPage;
    let host: HTMLAppFilledButtonElement;

    beforeEach(async () => {
        page = await newSpecPage({
            components: [FilledButton],
            html: '<app-filled-button disabled></app-filled-button>'
        });

        host = page.body.querySelector('app-filled-button') as HTMLAppFilledButtonElement;
    });

    it('should have disabled prop set to true', () => {
        expect(host.disabled).toBe(true);
    });

    it('should render disabled button', () => {
        const button = host.shadowRoot.querySelector('button');
        // 两种验证方式任选其一或同时使用
        expect(button.hasAttribute('disabled')).toBe(true);
        expect(button.disabled).toBe(true);
    });
});

3. 动态修改Prop的测试方式

如果需要测试动态切换disabled状态的场景,可以直接修改组件实例的Prop并等待渲染更新:

it('should disable button when prop is set to true', async () => {
    host.disabled = true;
    await page.waitForChanges();

    const button = host.shadowRoot.querySelector('button');
    expect(button.disabled).toBe(true);
});

关键注意点:

  • 区分HTML attribute和DOM property:button.hasAttribute('disabled')检查的是HTML属性是否存在,button.disabled检查的是DOM元素的布尔属性值,两者都能验证按钮禁用状态。
  • Stencil中布尔类型Prop,推荐用无值的HTML属性写法,避免字符串值和布尔值的解析差异。

内容的提问来源于stack exchange,提问作者Carla Candiotti

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.27 09:32:21