Skip to content

Add section on unit testing middleware to docs #559

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

Merged
merged 2 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
49 changes: 49 additions & 0 deletions docs/recipes/WritingTests.md
Original file line number Diff line number Diff line change
Expand Up @@ -140,6 +140,55 @@ describe('todos reducer', () => {
});
```

### Middleware

Middleware functions wrap behavior of `dispatch` calls in Redux, so to test this modified behavior we need to mock the behavior of the `dispatch` call.

#### Example

```js
import expect from 'expect';
import * as types from '../../constants/ActionTypes';
import singleDispatch from '../../middleware/singleDispatch';

const fakeStore = fakeData => ({
getState() {
return fakeData;
}
});

const dispatchWithStoreOf = (storeData, action) => {
let dispatched = null;
const dispatch = singleDispatch(fakeStore(storeData))(actionAttempt => dispatched = actionAttempt);
dispatch(action);
return dispatched;
};

describe('middleware', () => {
it('should dispatch if store is empty', () => {
const action = {
type: types.ADD_TODO
};

expect(
dispatchWithStoreOf({}, action)
).toEqual(action);
});

it('should not dispatch if store already has type', () => {
const action = {
type: types.ADD_TODO
};

expect(
dispatchWithStoreOf({
[types.ADD_TODO]: 'dispatched'
}, action)
).toNotExist();
});
});
```

### Components

A nice thing about React components is that they are usually small and only rely on their props. That makes them easy to test.
Expand Down