hlatshaw
hlatshaw

Reputation: 31

Using XPath with CasperJS

I am using CasperJS to test my frontend, and a new element of "foo" is created with the name "Brand New Name" and there are already existing 'foo' elements. I need to use XPath to select the specific element with the correct name so I can test if it exists using Casper.

This is what I'm doing currently:

this.test.assertExists(x('//*[@class="foo" and text()="Brand New Name"]'), 'new thing exists')

But this is not finding what I want, what am I doing wrong?

UPDATE 1

This is the Casper.JS failure message I receive, even though the xPath selector looks correct.

FAIL new category exists
#    type: assertExists
#    file: ../../../foo/test/casper/foo_manager/new_category.js
#    subject: false
#    selector: {"type":"xpath","path":"//*[@class=\"foo\" and contains(text(), \"Brand New Category\")]"

I have realized that there is actually a span in the element I am trying to select. I have tried to account for this, but I just can't get the xPath CasperJS selector to work. I have updated the xPath selector to a contains and it still won't work.

The selector looks like this:

this.test.assertExists(x('//*[@class="foo" and contains(text(), "Brand New Category")]'), 'new category exists')

The element in question looks like this:

<a href='#' class='foo' id='foo-bar'>
  Brand New Category
  <span>some text</span>
</a>

Upvotes: 3

Views: 1987

Answers (1)

Badacadabra
Badacadabra

Reputation: 8497

Your test should pass if you try this:

HTML (index.html)

<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <title>CasperJS and XPath</title>
</head>
<body>
  <ul>
    <li class="foo">Foo</li>
    <li class="foo">Bar</li>
    <li class="foo">Brand New Name</li>
  </ul>
</body>
</html>

JavaScript (xpath.js)

casper.test.begin('CasperJS and XPath', 1, function (test) {
  var x = require('casper').selectXPath;

  casper.start('index.html', function () {
    this.test.assertExists(x('//*[@class="foo" and text()="Brand New Name"]'), 'new thing exists');
  });

  casper.run(function () {
    test.done();
  });
});

Command

casperjs test xpath.js

Upvotes: 2

Related Questions