在量角器 `element().getAttribute()` 上使用 `await` 会给出错误:“‘await’操作数的类型必须是有效的 Promise...”

Mat*_*iba 5 async-await typescript protractor

我正在使用 Protractor 为 Angular2 应用程序编写行为测试,并且我对 async/await 语法很陌生。这个问题让我陷入了停滞。Type of 'await' operand must either be a valid promise or must not contain a callable 'then' member.有人可以解释为什么我在方法中遇到 Typescript 错误isLogoFooterPresent(),以及如何修复它吗?

我有以下简单的量角器规范,它尝试通过检查图像的宽度来验证图像是否显示。

以下是我的 e2e-spec.ts 文件的摘录:

import { LoginPage, Layout } from '../page_objects';

describe('Login page', () => {
  it('Should have the logo in the footer', async () => {
    await LoginPage.navigateTo();
    await expect(Layout.isFooterLogoPresent).toBe(true);
  })
});
Run Code Online (Sandbox Code Playgroud)

这是我的布局页面对象的一个​​片段,它可以看到相关徽标图像。await element(...).getAttribute(...)导致错误的链条行。

import { browser, element, by } from 'protractor/globals';

export class Layout {
  static get isFooterLogoPresent() {
    return ( async () => { // <-- this wrapping is necessary to use async/await in getter method
      return await element(by.css('.content-footer img')).getAttribute('naturalWidth') > 0; // <-- PROBLEM HERE
    })
  }
}
Run Code Online (Sandbox Code Playgroud)

我试图替换以下基于承诺的语法(有效):

  static get isFooterLogoPresent() {
    return element(by.css('.content-footer img')).getAttribute('naturalWidth') // naturalWidth attr is 0 if image is missing
      .then( imgWidth => imgWidth > 0 );
  }
Run Code Online (Sandbox Code Playgroud)

顺便说一句,我正在使用 Typscript 2.3.2 和 Protractor 5.2.0。我很欣赏你的智慧。谢谢!

Xot*_*bu4 0

只需为您的等待添加括号 -

  import { browser, element, by } from 'protractor/globals';

  export class Layout {
    static get isFooterLogoPresent() {
      return ( async () => {
        return (await $('.content-footer img').getAttribute('naturalWidth')) > 0;
      })
    }
  }
Run Code Online (Sandbox Code Playgroud)

这将适用> 0于解析值,而不适用于比较表达式

但!你这里有错误:

await expect(Layout.isFooterLogoPresent).toBe(true);
Run Code Online (Sandbox Code Playgroud)

函数isFooterLogoPresent仍然返回一个 Promise,所以你断言 Promise 对象为 true,根据 JS 中对象比较的工作方式,它将始终为 true。更改为修复误报测试:

await expect(await Layout.isFooterLogoPresent).toBe(true);
Run Code Online (Sandbox Code Playgroud)