Search code examples
javascriptprotractore2e-testing

Having trouble using expect() in protractor, want to get the first child's text and compare it to a string


I want to get the element's child's text and test if it equals a user input string.

Have tried the code below, which has resulted in the same error msg

await expect(element(by.className('tlid-translation translation').isDisplayed()).to.equal(true)

as well as throwing in some random .eventually or checking for element.all, but none of these seem to help.

Page:

var CalculatorPage = function() {

    var expect = require('chai').expect;

  this.get = function() {
    browser.waitForAngularEnabled(false);
    browser.get('https://translate.google.com/', 50000);
  };

  this.checkTrans = async(stringg) => {
       await expect(element(by.className('tlid-translation translation').get(0).getText()).to.equal(stringg)
    }


};

module.exports = CalculatorPage;


Steps:


var chai = require('chai').use(require('chai-as-promised'));
var expect = chai.expect;

var CalculatorSteps = function() {

  var TranslatePage = require("../pages/translate_page.js");


  this.World = function MyWorld() {
    this.page = new TranslatePage();
  };

  this.When('I see $stringg as translated', async function end(stringg) {
      await this.page.checkTrans(stringg)
    })

};

module.exports = CalculatorSteps;

The erro msg:

AssertionError: expected { Object (browser_, then, ...) } to equal true

Solution

  • In Specific:

    The problem is with the parentheses in your code. Also, avoid deprecated methods

    Change:

    await expect(element(by.className('tlid-translation translation').isDisplayed()).to.equal(true)
    

    to

    await expect(element(by.css('tlid-translation translation:nth-child(1)')).getText()).toBe(stringg);
    

    Change:

    await expect(element(by.className('tlid-translation translation').isDisplayed()).to.equal(true)
    

    to

    await expect(element(by.className('tlid-translation translation')).isDisplayed()).toBeTruthy();
    

    In General:

    • expect() needs a promise. Most of the protractor API deals with Promises given it has to deal with browser asynchronous nature. Make sure expect() is getting a promise
    • element() needs a Locator for ex. by.css('div'). Make sure thats the case.
    • Methods on element(Locator) will always return a protractor Promise. Make sure the code handles it that way.
    • I would prefer CSS selector to get a child element rather than using get all elements and then get an element from that list. That way its a bit more performant and we dont need API to handle.

    Hope that helps..