【问题标题】:Protractor: element.getText() returns an object and not String量角器:element.getText() 返回一个对象而不是字符串
【发布时间】:2015-04-06 20:13:53
【问题描述】:

我有一个元素定义为

this.clientRowName = element(by.id('CLIENT_NAME')); //page object file

我想阅读这个元素中的文本,它是“ABC”,但是这样做: var client = page.clientRowName.getText();

返回一个对象而不是一个字符串。有没有其他方法可以获取元素的文本

【问题讨论】:

    标签: javascript testing protractor


    【解决方案1】:

    getText() 返回一个承诺,你需要解决它:

    page.clientRowName.getText().then(function (text) {
        console.log(text);
    });
    

    或者,如果您只想断言文本,让expect() 为您解析承诺:

    expect(page.clientRowName.getText()).toEqual("ABC");
    

    Promises and the Control Flow 文档页面应该可以解决问题。

    【讨论】:

    • 如果你使用 Chai 期望,它有一个.eventually 方法来解决一个promise并从它内部获取值。 expect(page.clientRowName.getText()).to.eventually.equal("ABC")
    • 大家好,我可以在 toEqual() 或 toBe() 中使用 getText 函数吗?像这样:expect(element.getText()).toEqual(element2.getText())
    【解决方案2】:

    另一种解决方案可能是使用async/await

    class Page {
      constructor() {
        this.clientRowName = $('#CLIENT_NAME');
      }
    }
    
    /****************/
    
    it('should console.log client name', async () => {
      const client = await Page.clientRowName.getText();
      console.log(client);
    });
    

    【讨论】:

      【解决方案3】:

      我平时用element.getAttribute('value')

      【讨论】:

      • .getAttribute('value') 可能不起作用。也可以试试.getAttribute('textContent').getAttribute('innerText')
      【解决方案4】:

      如果你在 2021 年,你会想要阅读这个答案

      根据量角器文档,.getText() 返回一个承诺。

      截至 2021 年,处理承诺的最佳方式是使用 async/await 关键字。这将使 Protractor '冻结'并等待,直到 promise 得到解决,然后再运行下一个命令

      it('test case 1', async () => {
        let text = await page.clientRowName.getText();
        console.log(text);
      })
      

      .then() 也可以使用,但使用async/await 将使您的代码更具可读性和更易于调试。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2016-02-09
        • 1970-01-01
        • 2017-09-22
        • 1970-01-01
        • 2017-07-18
        • 2011-07-29
        • 2012-11-26
        相关资源
        最近更新 更多