Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Explain unit testing decorated components. #607

Merged
merged 4 commits into from
Aug 26, 2015
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
38 changes: 38 additions & 0 deletions docs/recipes/WritingTests.md
Original file line number Diff line number Diff line change
Expand Up @@ -259,6 +259,44 @@ export default function jsdomReact() {

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.

#### Testing decorated React components

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:

```js
class App extends Component { /* ... */ }
export default connect(select)(App);
```

You would normally import the class like this:

```js
import App from './App';
```

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:

```js
export class App extends Component { /* ... */ }
export default connect(select)(App);
```

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:

```js
import { App } from './App';
```

And if you need both:

```js
import Component, { App } from './App';
```

> ##### A note on using ES6 exports with CommonJS `require`

> 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`.

### Glossary

- [React Test Utils](http://facebook.github.io/react/docs/test-utils.html): Test utilities that ship with React.
Expand Down