首页 > 解决方案 > 使用 Protractor 和 Angular 进行 E2E 测试:在浏览器加载时让量角器等待

问题描述

我正在测试一个网页,该网页正在访问第三个网站以处理登录 (oAuth)。为了测试我的网页,我首先需要让我的 e2e 测试登录到第三个网站。我能够在第三个网站上找到用户电子邮件地址的输入元素并输入它。然后我还可以单击“继续”按钮,第三个网站现在打开一个新片段以输入密码。

然后问题来了:密码字段不可交互,我收到以下错误:

 - Failed: element not interactable
    (Session info: chrome=87.0.4280.141)
    (Driver info: chromedriver=87.0.4280.20 (c99e81631faa0b2a448e658c0dbd8311fb04ddbd-refs/branch-heads/4280@{#355}),platform=Windows NT 10.0.17763 x86_64)

我认为原因是页面尚未呈现新片段,因此密码输入字段尚不可见。所以我使用browser.sleep(1000)了,但这也会停止浏览器,对吧?因此,经过 1000 毫秒后,片段仍未加载。我知道还有一些东西

browser.wait(EC.urlContains("The URL of the password input page"))), 1000);

这里的问题是“Enter Email”-Part 和“Enter-Password”-Part 的 URL 是相同的,所以这个命令会检查 URL 并立即继续。

我也试过这个:

element(by.id("<id of the continueButton on the login fragment>).click().then(() => {
 ->perform my other actions for the passowrt part here
})

但这不起作用,click()我认为单击发生后返回的Promise会立即解决,因此页面仍然没有到达passowrd部分。

到目前为止,这是我的代码:

describe('workspace-project App', () => {

  it('Login at third website works.', async () => {
    await browser.get('https://my-webiste.com');
    
    const startButton = element(by.tagName('button'));
    startButton.click();
    // after clicking the start button on my page we get redirected to the login page of my 
    // oauth provider (third website) 
    browser.sleep(100)
    browser.getCurrentUrl().then(url => {
        expect(url.split("?")[0]).toEqual('https://my-oauth-login-page.com/login/gb/en_GB')
      })

    const inputEmail = element(by.id('username'));
    const LogInButtonEmail = element(by.tagName('button'));
      
    await inputEmail.sendKeys("<user-email-address for login>");
    browser.sleep(100)
    LogInButtonEmail.click();
    browser.sleep(1000)
    //until here everything works fine, but now we open the new fragment for entering the password and the test failsbefore the fragment gets shown:

    const inputPassword = element(by.id('current-password'));
    const LogInButtonPassword = element(by.tagName('button'));
    await inputPassword.sendKeys("<user-password for login>");
    browser.sleep(100)
    LogInButtonPassword.click();
    browser.sleep(100)
      
    browser.getCurrentUrl().then(url => {
        expect(url).toEqual('https://my-website-URL-after-successfull-redirect-from-oauth.com')
    })

  });

  afterEach(async () => {
    // Assert that there are no errors emitted from the browser
    const logs = await browser.manage().logs().get(logging.Type.BROWSER);
    expect(logs).not.toContain(jasmine.objectContaining({
      level: logging.Level.SEVERE,
    } as logging.Entry));
  });
});

当我让浏览器休眠更长时间并在保护器打开的浏览器中手动输入密码时,登录成功并且我的网站的所有后续测试都通过了。天哪,我希望他们将电子邮件和密码放在同一个视图/片段上,这样就没有问题了,arg...

欢迎任何提示;)

标签: angularprotractorangular-e2e

解决方案


在量角器中,一切都是承诺,您应该等待承诺得到解决

await browser.wait(EC.urlContains("The URL of the password input page"))), 1000);

Await 只能在异步函数中使用,因为您已将其声明为异步阻塞,您可以使用 await

await browser.sleep(3000) 不会停止浏览器,它只是停止量角器向浏览器发送命令 3 秒。就像添加脚本睡眠一样


推荐阅读