A lightweight solution to testing fully-rendered React Components
$ npm install react-test-renderer
const render = require('react-test-renderer');
const stub = createStub();
render(<MyComponent onClick={stub}/>)
.find(element => element.type === 'button')
.simulate('click');
assert.ok(stub.called);
interface Searchable {
find(predicate: (element: RenderedElement) => boolean): RenderedElement;
findAll(predicate: (element: RenderedElement) => boolean): Array<RenderedElement>;
findComponent(component: ReactComponent): RenderedComponent;
findAllComponent(component: ReactComponent): RenderedComponent;
}
interface RenderedElement mixins Searchable {
type: string;
props: Object;
simulate(eventName: string, eventOpts?: Object): void;
}
interface RenderedComponent mixins Searchable {
root: RenderedElement;
refs: { [name: string]: RenderedElement };
}
interface RenderedTree mixins Searchable {}
function render(ReactElement): RenderedTree
Find an element:
var tree = render(
<section>
<h1>Hello World</h1>
<p>...</p>
</section>
);
var heading = tree.find(element => element.type === 'h1');
assert.equal(heading.type, 'h1');
assert.deepEqual(heading.props, {
children: 'Hello World'
});
Simulate an event on a component:
var stub = createStub();
var tree = render(
<section>
<button onClick={stub}>Click Me!</button>
</section>
);
tree.find(element => element.type === 'button')
.simulate('click');
assert.ok(stub.called);
Using jsdom you can run this test renderer entirely in Node. Just set this up before you run your tests:
$ npm install --save-dev jsdom
var jsdom = require('jsdom').jsdom;
global.window = jsdom(undefined, { url: 'about:blank' }).defaultView;
global.document = global.window.document;
Note: This was tested using jsdom@9