Simplifying the Test Structure
Learn to simplify the middleware test structure from the previous lesson.
To avoid duplicating the test setup before every it()
clause, we can use Jest’s beforeEach()
method to combine the setup in one place:
describe('sample middleware', () => {
let next, dispatch, getState, middleware;
// using beforeEach
beforeEach(() => {
next = jest.fn();
dispatch = jest.fn();
getState = jest.fn();
middleware = sampleMiddleware({ dispatch, getState })(next);
});
it('should process action', () => {
const sampleAction = { type: 'SAMPLE_ACTION' };
// pass sampleAction through the middleware
middleware(sampleAction);
// test
expect(next.mock.calls).toEqual([[sampleAction]]);
};
};
Our middleware will be rebuilt before each test using this structure. All the mocked functions will be reset, keeping the testing code itself as short as possible.
Get hands-on with 1400+ tech skills courses.