[英]Unable to get select button click in unit testing using Jasmine and Angular
[英]Testing Ionic Toast button click in Jasmine
在測試時,我無法查詢里面的 Toast 按鈕之一。 它只是返回null
。 該類已設置,這就是用於查詢的內容。
it('should make a call to retrieval method on retry', async () => {
spyOn(component, 'retrieveEntry');
await component.retryRetrieval();
fixture.detectChanges();
await fixture.whenStable();
const retryButton = fixture.debugElement.query(By.css('.retry-button'));
retryButton.nativeElement.click();
fixture.detectChanges();
expect(component.retrieveEntry).toHaveBeenCalled();
});
在測試結果中,我可以看到正在創建的 toast,其中.retry-button
類被設置為所需的按鈕。
我很難過,我相信也許測試是在創建 Toast 元素之前運行的。
這是測試結果,您可以看到按鈕正在添加適當的類:
這是一個非常奇怪的問題。
會不會是 HTML 元素不在fixture.debugElement
上,而是在文檔上?
嘗試以下操作(通過 nativeElement 查詢):
const retryButton = fixture.nativeElement.querySelector('.retry-button');
retryButton.click();
如果上述方法不起作用,請嘗試以下方法(按文檔查詢):
const retryButton = document.querySelector('.retry-button');
retryButton.click();
如果上述方法均無效,則可能是元素在稍后的時間點異步繪制。
您可以使用此答案來幫助您執行以下操作:
await waitUntil(() => !!document.querySelector('.retry-button'));
這應該等到.retry-button
在 DOM 中,然后再繼續。
問題是 Toast 按鈕實際上是 shadow DOM 的一部分。 通過訪問正確的影子 DOM,我能夠找到一個可行的解決方案:
it('should make a call to retrieval method on retry', async () => {
spyOn(component, 'retrieveEntry');
await component.retryRetrieval();
fixture.detectChanges();
const host = document.getElementById('retry-toast');
const root = host.shadowRoot;
const retryButton = root.querySelector('.retry-button') as HTMLElement;
retryButton.click();
fixture.detectChanges();
expect(component.retrieveEntry).toHaveBeenCalled();
});
我還在 ToastController 的htmlAttributes
屬性中設置了 id 以確保一致性:
const toast = await this.toastController.create({
message: 'An error occurred retrieving entry.',
htmlAttributes: {
id: 'retry-toast'
},
color: 'danger',
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.