Skip to content

Latest commit

 

History

History
153 lines (113 loc) · 3.65 KB

README.md

File metadata and controls

153 lines (113 loc) · 3.65 KB

xpath-react

Build Status Code Climate Test Coverage

xpath-react is a library that allows you to query the virtual DOM of React with XPath 1.0 expressions and thus testing it without a real DOM.

Table of Contents

Installation

The package can be installed with npm.

$ npm install xpath-react

React is a peer dependency and is expected to be available. The library is compatible with both react-15.5.x and react-16.x.x.

$ npm install react

Usage

The library provides a basic evaluate method that you might commonly know as Document.evaluate. Additionally, a convenience method exist to make usage more practical, as evaluate is a bit cumbersome. A practical example can be found in example/.

evaluate()

XPathResult evaluate (
  DOMString expression,
  ReactElement contextNode,
  XPathNSResolver resolver,
  XPathResultType type,
  XPathResult result
)

This method works in the same way as Document.evaluate, but accepts a ReactElement instead of a Node.

Example

import { evaluate, XPathResult } from "xpath-react";

const Foo = (
  <ul>
    <li>bar</li>
    <li>baz</li>
  </ul>
);

const result = evaluate("string(.//li[1])", Foo, null, XPathResult.STRING_TYPE);

result.stringValue; // => "bar"

find()

(ReactElement | String | Number | Boolean) find (
  ReactElement element,
  DOMString expression
)

Finds React elements inside another element. It can also be used to query for string, number and boolean values (e.g. attributes, element counts and conditions, respectively).

Example
import ShallowRenderer from "react-test-renderer/shallow";

import { find } from "xpath-react";

function shallow (component) {
  const renderer = new ShallowRenderer();
  renderer.render(component);
  return renderer.getRenderOutput();
}

class Foo extends React.Component {
  render() {
    return (
      <div>
        <p>Hello world!</p>
      </div>
    );
  }
}

const output = shallow(<Foo />);

find(output, ".//p"); // => ReactElement { type: "p", ... }
find(output, "string(.//p)"); // => "Hello world!"
find(output, "count(.//p)"); // => 1
find(output, "count(.//p) = 1"); // => true

You can also use it to assert presence of unrendered child components, as shown below. This assumes that the child component has a displayName property.

class Bar extends React.Component {
  render() {
    return (
      <div>
        <Foo />
      </div>
    );
  }
}

const output = shallow(<Bar />);

find(output, "count(.//Foo)"); // => 1

Known issues & limitations

  • An abstract document node is created internally around the context node provided by the user. This can however not be returned, meaning that the following XPath expression would yield an error.

    /self::node()
    
  • Namespaces are not supported because JSX does not support them.