Blog>
Snippets

Unit Testing with UnknownAction

Illustrate how to write unit tests for your reducers and middleware that ensure UnknownAction is handled as expected.
const unknownAction = { type: 'UNKNOWN_ACTION' };

function reducer(state = {}, action) {
    switch (action.type) {
        // ... other action handlers
        default:
            return state;
    }
}

// Unit test case
describe('Reducer', () => {
    it('should return the initial state for unknown action', () => {
        const initialState = {};
        const action = unknownAction;
        const state = reducer(initialState, action);
        expect(state).toEqual(initialState);
    });
});
Defines a unit test for a reducer that checks how an unknown action (an action not defined in the reducer) is handled. It expects the reducer to return the initial state when the 'UNKNOWN_ACTION' is dispatched.
const applyMiddlewareMock = (middleware, store, action) => {
    const dispatch = jest.fn();
    const next = jest.fn();

    const invokeMiddleware = () => middleware(store)(next)(action);

    return { dispatch, next, invokeMiddleware };
};

// A middleware example with a checker for UNKNOWN_ACTION
const unknownActionMiddleware = store => next => action => {
    if (action.type === 'UNKNOWN_ACTION') {
        // Perform specific logic for unknown actions
        // For this test case, we'll just call next without any side-effects
        return next(action);
    }
    return next(action);
};

// Unit test for the unknownActionMiddleware
describe('unknownActionMiddleware', () => {
    it('passes unknown actions without side effects', () => {
        const { next, invokeMiddleware } = applyMiddlewareMock(unknownActionMiddleware, {}, unknownAction);
        invokeMiddleware();
        expect(next).toHaveBeenCalledWith(unknownAction);
    });
});
Defines a unit test for middleware that checks how an unknown action is passed through the middleware chain. It mocks the `store` and `next` functions to verify that the `next` is called with the unknown action, meaning that the middleware doesn't interfere with the action.