Skip to content

Instantly share code, notes, and snippets.

@yoavniran
Last active June 3, 2020 12:54
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save yoavniran/a57adbcacce98e60922d5941f46ab461 to your computer and use it in GitHub Desktop.
Save yoavniran/a57adbcacce98e60922d5941f46ab461 to your computer and use it in GitHub Desktop.
helper to test custom hook (especially if it's using useEffect) with React, Jest & Enzyme
import React from "react";
import { isFunction } from "lodash";
import { mount } from "enzyme";
export default (hook, props) => {
let wrapper, hookResult, hookParams, error;
if (isFunction(props)) {
hookParams = props;
props = {};
}
const Comp = (props) => {
try {
hookResult = hook(...(hookParams ? hookParams() : [props]));
}
catch (ex) {
error = ex;
}
return null;
};
//have to use mount() because shallow() doesnt support useEffect - https://github.com/airbnb/enzyme/issues/2086
wrapper = mount(<Comp {...props} />);
return {
wrapper,
getHookResult: () => hookResult,
getError: () => error,
};
};
import { useEffect } from "react";
import { registerToServiceEvent, unRegisterFromServiceEvent} from "services/myService";
const myCustomHook = (p1, p2) => {
useEffect(() => {
registerToServiceEvent(p1, p2);
return () => {
unRegisterFromServiceEvent(p1, p2);
};
}, [p1, p2]);
return "value";
};
jest.mock("services/myService", ()=>({
registerToServiceEvent: jest.fn(),
unRegisterFromServiceEvent:jest.fn(),
}));
import { registerToServiceEvent, unRegisterFromServiceEvent} from "services/myService";
it("should run my custom hook", () => {
const param1 = "a",
param2 = "b";
const { getHookResult } = testCustomHook(() => myCustomHook(param1, param2));
expect(getHookResult()).toBe("value");
expect(registerToServiceEvent).toHaveBeenCalledWith(param1, param2);
expect(unRegisterFromServiceEvent).toHaveBeenCalledWith(param1, param2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment