Testing custom redux middleware

How is unit test middleware custom middleware? I have this simple function that should send an action after a given timeout, but ... I have no idea how to approach it. I do not find sufficient resources to solve this problem.

const callAPiTimeoutMiddleware = store => next => (action) => { if (action[CALL_API]) { if (action[CALL_API].onTimeout) { setTimeout(() => { store.dispatch({ type: action[CALL_API].onTimeout }); }, DEFAULT_TIMEOUT_LENGTH); } } return next(action); } 

These are my tests based on the blog post mentioned in the accepted answer:

 describe('callAPiTimeoutMiddleware', () => { describe('With [CALL_API] symbol', () => { it('should dispatch custom action', () => { const clock = sinon.useFakeTimers(); const fakeStore = { dispatch: sinon.spy() }; const fakeNext = sinon.spy(); const fakeAction = { [CALL_API]: { endpoint: 'endPoint', method: 'METHOD', types: ['REQUEST_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'], onTimeout: 'TIMEOUT_TYPE', }, }; callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction); clock.tick(99000); expect(fakeStore.dispatch.calledOnce).toEqual(true); }); it('should call next action', () => { const fakeStore = { dispatch: sinon.spy() }; const fakeNext = sinon.spy(); const fakeAction = { [CALL_API]: { endpoint: 'endPoint', method: 'METHOD', types: ['REQUEST_TYPE', 'SUCCESS_TYPE', 'FAILURE_TYPE'], onTimeout: 'TIMEOUT_TYPE', }, }; callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction); expect(fakeNext.calledOnce).toEqual(true); }); }); describe('Without [CALL_API] symbol', () => { it('should NOT dispatch anything', () => { const clock = sinon.useFakeTimers(); const fakeStore = { dispatch: sinon.spy() }; const fakeNext = sinon.spy(); const fakeAction = { type: 'SOME_TYPE' }; callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction); clock.tick(99000); expect(fakeStore.dispatch.calledOnce).toEqual(false); }); it('should call next action', () => { const fakeStore = { dispatch: sinon.spy() }; const fakeNext = sinon.spy(); const fakeAction = { type: 'SOME_TYPE' }; callAPiTimeoutMiddleware(fakeStore)(fakeNext)(fakeAction); expect(fakeNext.calledOnce).toEqual(true); }); }); }); 
+5
source share
1 answer

The redux-thunk written unit tests. You can refer to here

He uses only mocha and teas.

And here he talks about how you can write unit tests for your redux application.

Nice blog about middleware environments and how to write unit tests for them.

+5
source

Source: https://habr.com/ru/post/1261568/


All Articles