From 7edcaf2db18951263f7ab7f9fe357606ac24217e Mon Sep 17 00:00:00 2001 From: David Idol Date: Mon, 17 Aug 2015 11:38:42 -0700 Subject: [PATCH 1/2] Add section on unit testing middleware to docs --- docs/recipes/WritingTests.md | 49 ++++++++++++++++++++++++++++++++++++ 1 file changed, 49 insertions(+) diff --git a/docs/recipes/WritingTests.md b/docs/recipes/WritingTests.md index e2f15596ee..af2f765643 100644 --- a/docs/recipes/WritingTests.md +++ b/docs/recipes/WritingTests.md @@ -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))(action => dispatched = action); + 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. From b8d831d34b2626940cb3c9791ab4ac6df865dadc Mon Sep 17 00:00:00 2001 From: David Idol Date: Mon, 24 Aug 2015 11:41:51 -0700 Subject: [PATCH 2/2] Update WritingTests.md Rename conflicting variable --- docs/recipes/WritingTests.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/recipes/WritingTests.md b/docs/recipes/WritingTests.md index af2f765643..6a501e0026 100644 --- a/docs/recipes/WritingTests.md +++ b/docs/recipes/WritingTests.md @@ -159,7 +159,7 @@ const fakeStore = fakeData => ({ const dispatchWithStoreOf = (storeData, action) => { let dispatched = null; - const dispatch = singleDispatch(fakeStore(storeData))(action => dispatched = action); + const dispatch = singleDispatch(fakeStore(storeData))(actionAttempt => dispatched = actionAttempt); dispatch(action); return dispatched; };