Last active
June 3, 2020 12:54
-
-
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
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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, | |
| }; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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"; | |
| }; |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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