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

如何用Jasmine测试Angular中Bootstrap 5下拉组件的渲染?

问题:Angular中Bootstrap 5下拉按钮单元测试不生效

问题背景

我在Angular项目里用Bootstrap 5实现了一个button.btn.dropdown-toggle按钮,项目运行时点击该按钮,它的aria-expanded属性会自动从false切换为true,同时添加show类;按钮没有绑定(click)事件,但下拉菜单能正常切换显示状态。我编写单元测试想要验证下拉菜单的渲染状态,通过检查aria-expanded属性来判断,但测试中点击按钮后,该属性没有变化,show类也未出现。

模板代码

<div class="dropdown">
    <button id="strategySelectionMenu" class="btn dropdown-toggle" type="button" data-bs-toggle="dropdown" aria-expanded="false">
        {{stratSelection}}
    </button>
    <ul class="dropdown-menu">
        <div *ngFor="let strategy of presetStrats">
            <li><button class="dropdown-item" (click)="stratSelection = strategy.name">{{strategy.name}}</button></li>
        </div>
    </ul>
</div>

初始单元测试代码

it('should show strategy dropdown only after clicking the dropdown button', () => {
    const strategyDropDown = root.getElementsByClassName('dropdown').item(0) as HTMLDivElement;
    expect(strategyDropDown).toBeDefined();
    
    let stratSelectButton = strategyDropDown.getElementsByTagName('button').namedItem('strategySelectionMenu') as HTMLButtonElement;
    expect(stratSelectButton.ariaExpanded).toEqual('false');

    stratSelectButton.click();
    fixture.detectChanges();

    expect(stratSelectButton.ariaExpanded).toEqual('true');
});

已尝试的无效方案

  • 测试过Stack Overflow上的多种解决方案
  • 用setTimeout()替代tick()
  • 改用debugElement获取目标元素
  • 手动触发dispatchEvent()模拟点击操作
  • 尝试点击div.dropdown和ul.dropdown-menu元素
  • 结合fakeAsync()、tick()和fixture.detectChanges(),并对Bootstrap的Dropdown实例的show()方法做spy:
const strategyDropDown = root.getElementsByClassName('dropdown').item(0) as HTMLDivElement;
const dropdownInstance = Dropdown.getOrCreateInstance(strategyDropDown) as Dropdown;

spyOn(dropdownInstance, 'show');

let stratSelectButton = strategyDropDown.getElementsByTagName('button').namedItem('strategySelectionMenu') as HTMLButtonElement;
expect(stratSelectButton.ariaExpanded).toEqual('false');
expect(stratSelectButton.classList.contains('show')).toBeFalse();

strategyDropDown.click();
tick();
fixture.detectChanges();

expect(dropdownInstance.show).toHaveBeenCalled();
expect(stratSelectButton.classList.contains('show')).toBeTrue();
expect(stratSelectButton.ariaExpanded).toEqual('true');

以上所有断言均不成立,另外调试时生成的极简页面中下拉菜单也未按预期渲染。想请教:是否可以通过单元测试验证这类前端渲染是否正常?


内容的提问来源于stack exchange,提问作者Rayshaun Thompson

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.23 06:05:01