在測驗時,我無法查詢里面的 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,并將 class.retry-button設定為所需的按鈕。
我很難過,我相信也許測驗是在創建 Toast 元素之前運行的。
這是測驗結果,您可以看到按鈕正在添加適當的類:

uj5u.com熱心網友回復:
這是一個非常奇怪的問題。
會不會是 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 中才能繼續。
uj5u.com熱心網友回復:
問題是 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();
});
我還在htmlAttributesToastController 的屬性中設定了 id 以確保一致性:
const toast = await this.toastController.create({
message: 'An error occurred retrieving entry.',
htmlAttributes: {
id: 'retry-toast'
},
color: 'danger',
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/479500.html
上一篇:**(Phoenix.Router.NoRouteError)找不到GET/fake(MyApp.Router)的路由
