簡體   English   中英

ngx-bootstrap 引導菜單未在 Angular4+ 單元測試中打開

[英]ngx-bootstrap bootstrap menu is not opening in Angular4+ unit tests

下拉菜單在應用程序中打開正常,但在單元測試中不起作用。 我不確定我是否遺漏了什么,但我已經看了很長時間,我找不到任何用戶錯誤。 我也在github上提交了一個問題。 https://github.com/valor-software/ngx-bootstrap/issues/4282

這是 stackblitz 鏈接: https ://stackblitz.com/edit/angular-euyvq4-khflez ? file = src%2Fmain.ts

運行應用程序

// bootstrap(); // to run karma
platformBrowserDynamic().bootstrapModule(AppModule); // to run the app

經營業力

bootstrap(); // to run karma
// platformBrowserDynamic().bootstrapModule(AppModule); // to run the app

任何人都可以確認它是錯誤還是用戶錯誤? 提前致謝

我認為您遇到了問題,因為事件循環如何在 DOM 節點上手動執行單擊方法。

Jake Archibald(Google 的開發人員倡導者)在 JSConf Asia 2018 上發表了關於事件循環的精彩演講。我強烈建議您觀看整件事,但在29:57 他談到了我相信您遇到的問題。 本質上,由於您是手動觸發此單擊事件,因此您需要在事件循環中將測試斷言作為單獨的任務執行。

您可以在測試中使用setTimeout(...) (並使用done方法)或在使用fixture.whenStable()方法的 Angular 測試中執行此操作的首選方法來完成此操作。 更改此設置將使您的測試通過:

fit('should open dropdown menu', () => {
  const h2: HTMLElement = fixture.nativeElement.querySelector('button#button-basic');
  h2.click();

  fixture.whenStable().then(() => {
    fixture.detectChanges();
    expect(fixture.nativeElement.querySelectorAll('li a.dropdown-item').length).toEqual(4);
  });
});

我無法讓您的 Stackblitz 工作,但以防萬一其他人遇到此問題,如果您動態生成列表項(使用 ngFor),那么您需要在 tick() 之后添加另一個 detectChanges()

 it('should show 8 items (fakeasync)', fakeAsync(() => {
    const h2: HTMLElement = fixture.nativeElement.querySelector('button#button-basic');
    h2.click();
    fixture.detectChanges();
    tick(); 
    fixture.detectChanges();
 expect(fixture.nativeElement.querySelector('[dropdown]').classList).toContain('open');
    expect(fixture.nativeElement.querySelectorAll('li a.dropdown-item').length).toEqual(8)
  }));

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM