量角器,我什么时候应该在 click() 后使用 then()

问题描述:

我正在运行一个 Angular 应用程序,当在量角器上测试 click() 时,我不知道我什么时候应该用 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:

点击命令完成后将解决的承诺.

A promise that will be resolved when the click command has completed.

那么,我应该在每个 click 中使用 click().then() 吗?

So, should I use click().then() in every click?

那么,我应该在每次点击时都使用 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 队列,称为控件流,以保持执行有条理.

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:

您不再需要在测试中添加等待和睡眠.量角器可以在测试的那一刻自动执行下一步网页完成待处理的任务,所以你不必担心等待您的测试和网页同步.

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.

这导致了一个非常简单的测试代码:

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);

有时,如果您遇到同步/计时问题,或者您的被测应用程序不是 Angular,您可以通过使用 then()click() 来解决它/code> 并在点击回调中继续:


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);
});

还有 显式等待这些情况下的救援,但在此处无关紧要.

There are also Explicit Waits to the rescue in these cases, but it's not relevant here.