問題描述
我正在運行一個 Angular 應(yīng)用程序,當(dāng)在量角器上測試 click()
時,我不知道何時應(yīng)該使用 then()
解決承諾.
I'm running an Angular app and when testing on protractor a click()
, I don't know when should I resolve the promise with a then()
.
我在 Protractor API 上找到了這個:
I found this on Protractor API:
當(dāng)點擊命令完成時將被解決的承諾.
A promise that will be resolved when the click command has completed.
那么,我應(yīng)該在每次 click
中使用 click().then()
嗎?
So, should I use click().then()
in every click
?
推薦答案
那么,我應(yīng)該在每次點擊中使用 click().then() 嗎?
So, should I use click().then() in every click?
絕對不是.
不需要,因為 Protractor/WebDriverJS 有這種稱為 " 的機制控制流",它基本上是一個需要解決的承諾隊列:
It's not needed because Protractor/WebDriverJS has this mechanism called "Control Flow" which is basically a queue of promises that need to be resolved:
WebDriverJS 維護一個待處理的 Promise 隊列,稱為控件流,以保持執(zhí)行有條理.
WebDriverJS maintains a queue of pending promises, called the control flow, to keep execution organized.
并且 Protractor 會自然地、開箱即用地等待 Angular:
and Protractor waits for Angular naturally and out-of-the-box:
您不再需要在測試中添加等待和睡眠.量角器可以在測試的那一刻自動執(zhí)行下一步網(wǎng)頁完成待處理任務(wù),您無需擔(dān)心等待您的測試和網(wǎng)頁同步.
You no longer need to add waits and sleeps to your test. Protractor can automatically execute the next step in your test the moment the webpage finishes pending tasks, so you don’t have to worry about waiting for your test and webpage to sync.
這導(dǎo)致了一個非常直接的測試代碼:
Which leads to a quite straight-forward testing code:
var elementToBePresent = element(by.css(".anotherelementclass")).isPresent();
expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click();
expect(elementToBePresent.isPresent()).toBe(true);
<小時>
但有時,如果您遇到同步/計時問題,或者您的被測應(yīng)用不是 Angular,您可以通過使用 then()<顯式解析
click()
來解決它/code> 并在點擊回調(diào)中繼續(xù):
Sometimes though, if you experience synchronization/timing issues, or your app under test is non-Angular, you may solve it by resolving the click()
explicitly with then()
and continue inside the click callback:
expect(elementToBePresent.isPresent()).toBe(false);
element(by.css("#mybutton")).click().then(function () {
expect(elementToBePresent.isPresent()).toBe(true);
});
還有顯式等待在這些情況下的救援,但在這里不相關(guān).
There are also Explicit Waits to the rescue in these cases, but it's not relevant here.
這篇關(guān)于量角器,我什么時候應(yīng)該在 click() 之后使用 then()的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!