How to test middleware by jest?

2019-03-06 10:52发布

问题:

I need to add functions onMount and onUnmount to middleware and test that they are correct. How I can do it? I can use jest, enzyme

import { set, open } from "./";
export function middleware(
    options,
) {
    return ({ dispatch }) => (next) => {
        return (action) => {
            const onMount = () => {
                if (options) {
                    options.mount();
                }
                dispatch(set(true));
            };
            const onUnmount = () => {
                if (legacyOptions) {
                    options.unmount();
                }
                dispatch(set(false));
            };
            open({
                onMount: onMount,
                onUnmount: onUnmount,
            )}
        }

    }
    return next(action);
}

My test file. I created this middleware. How to test this functions?

const openMock = jest.fn();
jest.mock("./", () => ({
    open: openMock,
}));

const { next, store } = create();
const invoke = (action) => middleware()(store)(next)(action);
invoke(init());
expect(openMock).toHaveBeenCalledTimes(1);