xpath-react
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
; const Foo = <ul> <li>bar</li> <li>baz</li> </ul>; const result = ; resultstringValue; // => "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
; ; { const renderer = ; renderer; return renderer;} Component { return <div> <p>Hello world!</p> </div> ; } const output = ; ; // => ReactElement { type: "p", ... }; // => "Hello world!"; // => 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.
Component { return <div> <Foo /> </div> ; } const output = ; ; // => 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.