Code Monkey home page Code Monkey logo

rquery's Introduction

Archived

This repository is no longer being actively developed. Many newer, more modern, and well-supported alternatives have become available since this project was first created.

rquery

A React tree traversal utility similar to jQuery, which can be useful for making assertions on your components in your tests.

Vision

chai-react was originally built to help with test assertions of React components. However, it quickly started adding too much complexity because it was attempting to solve two problems: 1) making assertions of properties/rendered content and 2) traversing the rendered React tree to make those assertions.

rquery is meant to take over the rendered tree traversing responsibility from chai-react, which will allow it to be used with any testing framework. It will also provide convenience wrappers for various common test actions, such as event dispatching.

React Version Support

  • For React v15, use rquery version 5+
  • For React v0.14, use rquery version 4.x

Setup

Node.js, Webpack, Browserify

var _ = require('lodash');
var React = require('react');
var ReactDOM = require('react-dom');
var TestUtils = require('react-addons-test-utils');
var $R = require('rquery')(_, React, ReactDOM, TestUtils);

Browser with Scripttags

Include React, lodash, and rquery in the page, then you get the $R global.

Sample usage:

<script src="https://fb.me/react-with-addons-0.14.1.js"></script>
<script src="https://fb.me/react-dom-0.14.1.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/3.6.0/lodash.min.js"></script>
<script src="rquery.js"></script>
<script>
var component = React.createClass({
  render: function () {
    return React.createElement('h1', {}, 'Hello, world!');
  }
});

var el = document.createElement('div');
document.body.appendChild(el);

var comp = ReactDOM.render(React.createElement(component), el);

var $r = $R(comp);

console.log($r.text()); // 'Hello, world!'
</script>

Usage

$R Factory

The $R factory method returns a new instance of an rquery object.

Example:

var $r = $R(component);

Class Methods

.extend

$R.extend({
  customMethod: function () {
    // your own custom method
  }
});

The extend method allows you to add extra methods to the rquery prototype. It does not allow you to override internal methods, though.

.isRQuery

$R.isRQuery('abc'); // false
$R.isRQuery($R([])); // true

Returns true if the provided argument is an instance of the rquery prototype.

Instance Methods

An instance of the rquery class contains an array of components, and provides an Array-like interface to directly access each component.

Example:

var $r = $R([component1, component2 /* , componentN */]);
$r.length === 2; // true
$r[0] === component1; // true
$r[1] === component2; // true

#find

$r.find(selector)

Returns a new rquery instance with the components that match the provided selector (see Selector documentation).

#prop

$r.prop('a')

Returns the value for the given prop for the first component in the scope. It throws an error if the scope has no components.

#style

$r.style('a')

Returns the value for the given style for the first component in the scope. The style value is loaded from the style property. It throws an error if the scope has no components.

#state

$r.state('a')

Returns the value for the given state for the first component in the scope. It throws an error if the scope has no components.

#nodes

$r.nodes()

Returns an array of each DOM node in the current scope.

#text

$r.text()

Returns the text contents of the component(s) in the $r object. Similar to jQuery's text() method (read-only).

#html

$r.html()

Returns the HTML contents of the component(s) in the $r object. Similar to jQuery's html() method (read-only).

#simulateEvent

simulateEvent(eventName, eventData)

Simulates triggering the eventName DOM event on the component(s) in the rquery object.

Event helpers

[eventName](eventData)

Convenience helper methods to trigger any supported React DOM event. See the React documentation to read about the events that are currently supported.

Selectors

Scope Selectors

Descendant Selector

Example:

$R(component).find('div p');

Description:

Finds all elements that are descendants of a parent component/node. Note that the root element of a component will be matched as a descendant of it (e.g. MyComponent > div will match <div> at root of MyComponent#render).

Child Selector

Example:

$R(component).find('div > p');

Description:

Finds all elements that are children (direct descendant) of a parent component/node.

Union Selector

Example:

$R(component).find('div, p');

Description:

Matches a union of all selectors on both sides of the ,.

Not Selector

Example:

$R(component).find('div :not(p)');

Description:

Matches all elements that do not match the nested selector. NB: Note the difference between div :not(p) and div:not(p). The latter will match nothing as the :not is being applied directly on the div. However, div :not(p) applies a descendant scope selector first, which means it will match all elements that are descendants of div but not a p.

Element/Component Selectors

Component Selector

Example:

$R(component).find('MyComponentName');
$R(component, 'MyButton');

Description:

Traverses the tree to find components based on their displayName value. NB: the selector must start with an upper-case letter, to signify a CompositeComponent vs. a DOM component.

DOM Tag Selector

Example:

$R(component).find('div');
$R(component, 'p');

Description:

Traverses the tree to find DOM components based on their tagName. NB: the selector must start with a lower-case letter, to signify a CompositeComponent vs. a DOM component.

DOM Class Selector

Example:

$R(component).find('.button');
$R(component, '.green');

Description:

Traverses the tree to find components with classNames that contain the specified class.

Index Selector

Example:

$R(component).find('div[2]'); // matches the third div

Description:

Matches the element at the given index. This is shorthand for .at(index) on the rquery object.

Attribute Selector

Example:

$R(component).find('[target]');
$R(component, '[onClick]');

Description:

Traverses the tree to find components that have a value defined for the given property name.

Note: Although these are labeled as attribute selectors, they are really property selectors. In other words, they match properties being passed to a DOM/Composite component, not actual DOM attributes being rendered.

Attribute Value Selectors

Example:

$R(component).find('[target="_blank"]');
$R(component, '[href="http://www.github.com/"]');

Supported Operators:

rquery supports the CSS Selectors level 3 spec:

  • [att="val"]: equality
  • [att~="val"]: whitespace-separated list
  • [att|="val"]: namespace-prefixed (e.g. val or val-*)
  • [att^="val"]: prefix
  • [att$="val"]: suffix
  • [att*="val"]: substring

Description:

Traverses the tree to find components with a property value that matches the given key/value pair.

Note: Although these are labeled as attribute selectors, they are really property selectors. In other words, they match properties being passed to a DOM/Composite component, not actual DOM attributes being rendered. For complex property values (e.g. arrays, objects, etc.), the value matchers are less useful as rquery doesn't currently support any complex value matching.

Note: All values must be provided as double-quoted strings. [att="val"] is valid, but [att=val] and [att='val'] are not.

Usage with Test Suites

The rquery interface is meant to be generic enough to use with any assertion library/test runner.

Sample usage with Chai BDD style assertions:

expect($R(component).find('MyComponent')).to.have.length(1);

rquery's People

Contributors

dignifiedquire avatar greengremlin avatar jonboiser avatar percyhanna avatar undr avatar valscion avatar vmakhaev avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar

rquery's Issues

Can't find child component using Shallow Rendering.

Hello,

I can't find a component using Shallow Rendering with $R(component).find('MyComponentName').
It just returns a rquery object with a length of zero. Does this work with Shallow Rendering?
Thanks!

Add more CSS-style selectors

  • ' ': Descendent selector
  • '>': Child selector
  • ',': Union selector
  • '?=': Extended attribute selectors (e.g. ~=, |=, ^=, $=, *=)

Doesn't work with shallow rendering

I've tried using this on a component attained through shallow rendering, and though the initial $R(component) call seems to work, running a find() doesn't seem to work at all.

Is shallow rendering currently supported?

"TypeError: Cannot read property 'getAttribute' of null" form component without dom node

I have error in my test

TypeError: Cannot read property 'getAttribute' of null
    at rquery_getReactId (/Users/dperetyagin/work/pwdocker/Pushwoosh/Web/new/src/js/views/applications/application/__tests__/deeplinks-test.js:35083:41 <- webpack:///~/rquery/rquery.js?f17e:70:0)
    at componentDepth (/Users/dperetyagin/work/pwdocker/Pushwoosh/Web/new/src/js/views/applications/application/__tests__/deeplinks-test.js:35071:26 <- webpack:///~/rquery/rquery.js?f17e:58:0)

I did some research and came to the conclusion that the cause is component Collapse from react-bootstrap
ReactDOM.findDOMNode() for this component returns null, because the component have not any dom node.

Extending RQuery?

First off, this is a great library. This is what I was expecting to see when I looked at React TestUtils the first time. Thank you!

I'm interested in adding some convenience functions to RQuery. I don't think everyone will need them, so I didn't really want to send a pull request. I was thinking of having something more like a jquery extension. My question, is this intended to be extendable? I seem to be able to add functions easily enough like this:

$R.rquery.prototype.innerHTML = -> (this.components.map (c) -> c.getDOMNode().innerHTML).join('')
now I can use my function like so:

$comp.find('.renderedWikiText').innerHTML()

I just didn't want to find out I'm hacking in an unexpected way and not be able to upgrade because you closed access to the prototype. Any other downsides to this?

Clicking doesn't work as expected

Hey there, nice work with rquery. I either found a bug or I'm not really sure if I'm using this right
It's a simple components that has a inner component which has a state

    it('it should open a dropdown onClick', () => {
        var date      = moment().toDate();
        var callback  = sinon.spy();
        var component = TestUtils.renderIntoDocument(
            <MyComponent
                date={date}
                onChange={callback} />
        );

        // Click the Button -> doesn't work
        $R(component).find('a').ensureClick();
        component = $R(component).findComponent(MyInnerComponent).get(0);
        expect(component.state.open).to.equal(true);

        // Click the Button -> works
        component = TestUtils.findRenderedComponentWithType(component, MyInnerComponent);
        var button = TestUtils.findRenderedDOMComponentWithTag(component, 'a');
        TestUtils.Simulate.click(button);
        expect(component.state.open).to.equal(true);
    });

npm@latest gives version 2.0.9 of the library

Hi,

I've really enjoyed using rquery for a long time now in our quite large project, and it's been working splendidly, thanks!

I just tried to upgrade my version of rquery with npm install --save-dev rquery@latest and it seems that you've published version 2.0.9, probably accidentally, as the "latest" module.

https://docs.npmjs.com/cli/dist-tag#purpose

By default, the latest tag is used by npm to identify the current version of a package, and npm install <pkg> (without any @<version> or @<tag> specifier) installs the latest tag. Typically, projects only use the latest tag for stable release versions, and use other tags for unstable versions such as prereleases.

When publishing new versions, you probably need to set the --tag option manually when running npm publish with 2.x and 3.x branches :)

can't find component in subqueries

        class MyLink extends React.Component {
            render() {
                return <a href={this.props.href}>{this.props.text}</a>;
            }
        }

        class MyComponent extends React.Component {
            render() {
                return(
                    <div className="row">
                        <div className="col">
                            <MyLink href="http://google.com/" text="Google"/>
                        </div>
                    </div>
                );
            }
        }

        const component = TestUtils.renderIntoDocument(<MyComponent/>);
        const $r = $R(component);

        $r.find('MyLink').length.should.be.equal(1); // => ok
        $r.find('.col').find('MyLink').length.should.be.equal(1); // => why?

Difficulty initializing from Travis CI

rquery works fine in my local dev environment, karma and webpack (and is very helpful, thx!).
However when I try to run the tests under Travis (continuous integration service) I see the following error.

22 03 2016 14:00:48.500:DEBUG [web-server]: serving (cached): /home/travis/build/betteroutcomes/boc-pro/tests.webpack.js
  Uncaught TypeError: Cannot read property 'TestUtils' of undefined
  at /home/travis/build/betteroutcomes/boc-pro/tests.webpack.js:37072

It seems, looking at the source, that this line is failing:

https://github.com/percyhanna/rquery/blob/master/rquery.js#L13

I added some logs to the test, to try to understand the initialization better:

var React= require('react');
var ReactDOM = require('react-dom');
var TestUtils = require('react-addons-test-utils');
var _ = require('lodash');
console.log(typeof require);
console.log(typeof exports);
console.log(typeof module);
var $R = require('rquery')(_, React, ReactDOM, TestUtils);

but the result doesn't help explain what is going on:

Chromium 45.0.2454 (Ubuntu 0.0.0) LOG: 'function' 
Chromium 45.0.2454 (Ubuntu 0.0.0) LOG: 'object'
Chromium 45.0.2454 (Ubuntu 0.0.0) LOG: 'object'
Chromium 45.0.2454 (Ubuntu 0.0.0) ERROR
  Uncaught TypeError: Cannot read property 'TestUtils' of undefined    
    at /home/travis/build/betteroutcomes/boc-pro/tests.webpack.js:37072 

Any suggestions as to what might be the problem? (Thanks in advance)

find with css-style selectors

It seems the selectors work with elements, for instance "div a" but normal css selectors like ".button.delete" don't seem to work with find. Are there plans for this?

Lodash is undefined in nodejs

ReferenceError: _ is not defined
      at getDescendents (/project/path/node_modules/rquery/rquery.js:25:12)

Looks like you need to _ = require('lodash') in the node js module setup, and should be added as a real dependency in package.json

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.