You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
69 lines
2.1 KiB
69 lines
2.1 KiB
8 years ago
|
---
|
||
|
id: shallow-renderer
|
||
|
title: Shallow Renderer
|
||
|
permalink: docs/shallow-renderer.html
|
||
|
layout: docs
|
||
|
category: Reference
|
||
|
---
|
||
|
|
||
|
**Importing**
|
||
|
|
||
|
```javascript
|
||
8 years ago
|
import ShallowRenderer from 'react-test-renderer/shallow'; // ES6
|
||
|
var ShallowRenderer = require('react-test-renderer/shallow'); // ES5 with npm
|
||
8 years ago
|
```
|
||
|
|
||
8 years ago
|
## Overview
|
||
8 years ago
|
|
||
8 years ago
|
When writing unit tests for React, shallow rendering can be helpful. Shallow rendering lets you render a component "one level deep" and assert facts about what its render method returns, without worrying about the behavior of child components, which are not instantiated or rendered. This does not require a DOM.
|
||
8 years ago
|
|
||
8 years ago
|
For example, if you have the following component:
|
||
8 years ago
|
|
||
|
```javascript
|
||
|
function MyComponent() {
|
||
|
return (
|
||
|
<div>
|
||
|
<span className="heading">Title</span>
|
||
|
<Subcomponent foo="bar" />
|
||
|
</div>
|
||
|
);
|
||
|
}
|
||
|
```
|
||
|
|
||
|
Then you can assert:
|
||
|
|
||
|
```javascript
|
||
8 years ago
|
import ShallowRenderer from 'react-test-renderer/shallow';
|
||
|
|
||
|
// in your test:
|
||
|
const renderer = new ShallowRenderer();
|
||
|
renderer.render(<MyComponent />);
|
||
|
const result = renderer.getRenderOutput();
|
||
8 years ago
|
|
||
|
expect(result.type).toBe('div');
|
||
|
expect(result.props.children).toEqual([
|
||
|
<span className="heading">Title</span>,
|
||
|
<Subcomponent foo="bar" />
|
||
|
]);
|
||
|
```
|
||
|
|
||
|
Shallow testing currently has some limitations, namely not supporting refs.
|
||
|
|
||
8 years ago
|
> Note:
|
||
|
>
|
||
|
> We also recommend checking out Enzyme's [Shallow Rendering API](http://airbnb.io/enzyme/docs/api/shallow.html). It provides a nicer higher-level API over the same functionality.
|
||
|
|
||
|
## Reference
|
||
|
|
||
|
### `shallowRenderer.render()`
|
||
|
|
||
|
You can think of the shallowRenderer as a "place" to render the component you're testing, and from which you can extract the component's output.
|
||
|
|
||
7 years ago
|
`shallowRenderer.render()` is similar to [`ReactDOM.render()`](/docs/react-dom.html#render) but it doesn't require DOM and only renders a single level deep. This means you can test components isolated from how their children are implemented.
|
||
8 years ago
|
|
||
|
### `shallowRenderer.getRenderOutput()`
|
||
|
|
||
|
After `shallowRenderer.render()` has been called, you can use `shallowRenderer.getRenderOutput()` to get the shallowly rendered output.
|
||
8 years ago
|
|
||
8 years ago
|
You can then begin to assert facts about the output.
|