Skip to content

Commit e1faa7a

Browse files
committed
Merge pull request #559 from idolize/patch-2
Add section on unit testing middleware to docs
2 parents 0b99c45 + b8d831d commit e1faa7a

File tree

1 file changed

+49
-0
lines changed

1 file changed

+49
-0
lines changed

docs/recipes/WritingTests.md

Lines changed: 49 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -140,6 +140,55 @@ describe('todos reducer', () => {
140140
});
141141
```
142142
143+
### Middleware
144+
145+
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.
146+
147+
#### Example
148+
149+
```js
150+
import expect from 'expect';
151+
import * as types from '../../constants/ActionTypes';
152+
import singleDispatch from '../../middleware/singleDispatch';
153+
154+
const fakeStore = fakeData => ({
155+
getState() {
156+
return fakeData;
157+
}
158+
});
159+
160+
const dispatchWithStoreOf = (storeData, action) => {
161+
let dispatched = null;
162+
const dispatch = singleDispatch(fakeStore(storeData))(actionAttempt => dispatched = actionAttempt);
163+
dispatch(action);
164+
return dispatched;
165+
};
166+
167+
describe('middleware', () => {
168+
it('should dispatch if store is empty', () => {
169+
const action = {
170+
type: types.ADD_TODO
171+
};
172+
173+
expect(
174+
dispatchWithStoreOf({}, action)
175+
).toEqual(action);
176+
});
177+
178+
it('should not dispatch if store already has type', () => {
179+
const action = {
180+
type: types.ADD_TODO
181+
};
182+
183+
expect(
184+
dispatchWithStoreOf({
185+
[types.ADD_TODO]: 'dispatched'
186+
}, action)
187+
).toNotExist();
188+
});
189+
});
190+
```
191+
143192
### Components
144193
145194
A nice thing about React components is that they are usually small and only rely on their props. That makes them easy to test.

0 commit comments

Comments
 (0)