Skip to content

Commit e5b2a5b

Browse files
committed
Merge pull request reduxjs#607 from ghengeveld/patch-2
Explain unit testing decorated components.
2 parents 63c84f9 + a68768f commit e5b2a5b

File tree

1 file changed

+38
-0
lines changed

1 file changed

+38
-0
lines changed

docs/recipes/WritingTests.md

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -259,6 +259,44 @@ export default function jsdomReact() {
259259
260260
Call it before running any component tests. Note this is a dirty workaround, and it can be removed once [facebook/react#4019](https://github.com/facebook/react/issues/4019) is fixed.
261261
262+
#### Testing decorated React components
263+
264+
In order to achieve separation of concerns and create reusable components, we often wrap one component inside another using decorators. For example, consider the `App` component:
265+
266+
```js
267+
class App extends Component { /* ... */ }
268+
export default connect(select)(App);
269+
```
270+
271+
You would normally import the class like this:
272+
273+
```js
274+
import App from './App';
275+
```
276+
277+
Such component becomes hard to test because when you import the component, you're actually holding the wrapper component, not the App component itself. In order to be able to test the App component itself without having to deal with the decorator, it's recommended to also export the undecorated component:
278+
279+
```js
280+
export class App extends Component { /* ... */ }
281+
export default connect(select)(App);
282+
```
283+
284+
Since the default export is still the decorated component, the import statement pictured above will work as before so you won't have to change your application code. However, you can now import the undecorated App components in your test file like this:
285+
286+
```js
287+
import { App } from './App';
288+
```
289+
290+
And if you need both:
291+
292+
```js
293+
import Component, { App } from './App';
294+
```
295+
296+
> ##### A note on using ES6 exports with CommonJS `require`
297+
298+
> If you are using ES6 in your application sources, but write your tests in ES5. Babel handles the interchangeable use of ES6 `import` and CommonJS `require` through its [interop](http://babeljs.io/docs/usage/modules/#interop) capability to run two module formats side-by-side, but the behavior is [slightly different](https://github.com/babel/babel/issues/2047). If you add a second export beside your default export, you can no longer import the default using `require("./App.js")`. Instead you have to use `require("./App.js").default`.
299+
262300
### Glossary
263301
264302
- [React Test Utils](http://facebook.github.io/react/docs/test-utils.html): Test utilities that ship with React.

0 commit comments

Comments
 (0)