2

I've created this step definition to check if a given text exists in a web page. The code works properly but sometimes, expecially when I look for a long text, I get an error even if the text exists in the page.

The code is this:

this.Then(/^The text "([^"]*)" exists in page$/, function(myText, callback){

    browser.sleep(10000);

    var selectedElement = element(by.xpath("//*[. = '" + myText + "']"));

    expect(selectedElement.isPresent()).to.eventually.equal(true, "This text is not present in page").and.notify(callback);    

  });

Basically I do three things:

  1. I wait 10 seconds to be sure that all elements of the DOM have been loaded.
  2. I seach for an element(div, p, label or whatever) thet contains the text I'm looking for.
  3. I check if the element is present oterwise I get an error.

Can you tell me if there is a better way to do this? It's correct to use browser.sleep() at the beginning of a step definition to wait for the DOM loading?

IMPORTANT: I'm not using Angularjs

Thank you in advance.

Ema.jar
  • 2,370
  • 1
  • 33
  • 43

1 Answers1

2

Most likely, the problem is because you are using a strict text match, but there could be extra spaces or newlines around a desired text. You can try with contains() if this is applicable:

element(by.xpath("//*[contains(., '" + myText + "')]"));

Or, with normalize-space():

element(by.xpath("//*[text()[normalize-space() = '" + myText + "']]"));

As a side note, using browser.sleep() to wait for a page to load is not quite reliable and should be avoided. There is a better way - browser.wait() and Expected Conditions.

alecxe
  • 462,703
  • 120
  • 1,088
  • 1,195
  • Ok, I think that I have problem with special characters. If my page contains the text "My brother O'Brian" and I search this text I can find nothing. Do you know how to avoid this problem?? I've tried to escape the "'" but it doesn't solve the problem. – Ema.jar Jan 12 '16 at 09:18
  • @Ema.jar yeah, you need to escape the quotes in your `myText` variable, please see http://stackoverflow.com/questions/770523/escaping-strings-in-javascript. – alecxe Jan 12 '16 at 14:43