如果我有以下情況:
<a [href]="some-url" target="_blank">
<button (click)="onClick()">Press me</button>
</a>
function onClick(){
this.service.doSomething();
}
使用 Jasmine/Karma,我如何doSomething
在不打開任何鏈接或其他不需要的瀏覽器行為的情況下測驗被呼叫的內容?我努力了:
設定href
為空字串和target
to _self
,不斷重繪 瀏覽器視窗:
const anchor = fixture.debugElement.query(By.css('a'))?.nativeElement as HTMLAnchorElement;
anchor.href = '';
anchor.target = '_self';
設定href
to#
和target
to _self
,在瀏覽器中打開一個嵌入式 Karma 實體:
const anchor = fixture.debugElement.query(By.css('a'))?.nativeElement as HTMLAnchorElement;
anchor.href = '#';
anchor.target = '_self';
從點擊處理函式回傳false
,該函式測驗成功但會破壞應用程式:
function onClick(){
this.service.doSomething();
return false;
}
uj5u.com熱心網友回復:
這可能不完全是您想要的,但我只是獲取按鈕的句柄并單擊它,并且知道如果單擊它,單擊將轉到按鈕,a
因為我假設這就是 HTML/JavaScript 的作業方式。
spyOn(window, 'open');
const button = fixture.debugElement.query(By.css('button')).nativeElement as HTMLButtonElement;
button.click();
// continue
uj5u.com熱心網友回復:
另一個答案導致我洗掉a href
并使用點擊處理程式來呼叫window.open
。
<button (click)="onClick()">Press me</button>
function onClick(){
window.open(some-url, '_blank');
this.service.doSomething();
}
spyOn(window, 'open'); // prevent new tab being opened
const button = fixture.debugElement.query(By.css('button'))?.nativeElement as HTMLButtonElement;
button.click();
spyOn(window, 'open')
這還具有您可以檢查呼叫是否已撥打的優點。
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/504760.html
上一篇:在C#單元測驗中使用2位元組陣列