Skip to content

Instantly share code, notes, and snippets.

@goncalobo
Created February 26, 2019 13:59
Show Gist options
  • Save goncalobo/ace875af564d4fd585651abd86f65cd2 to your computer and use it in GitHub Desktop.
Save goncalobo/ace875af564d4fd585651abd86f65cd2 to your computer and use it in GitHub Desktop.
Workaround to test a custom hook API (https://codesandbox.io/s/jvo251qqwy)
import React, { useState, useEffect } from "react";
import { act } from "react-dom/test-utils";
import ShallowRenderer from "react-test-renderer/shallow";
import Enzyme, { shallow } from "enzyme";
import Adapter from "enzyme-adapter-react-16";
Enzyme.configure({ adapter: new Adapter() });
// Custom Hook API being subject to testing
import useCustomHook from "shared/hooks/useCustomHook";
const HookAPITestHelper = ({
hook,
hookProps: props,
method,
methodArgs: args
}) => {
const [firstRender, setFirstRender] = useState(true);
const API = hook(props);
useEffect(() => {
if (firstRender) {
setFirstRender(false);
}
});
if (firstRender) {
if (method && API[method]) {
API[method](args);
}
setFirstRender(false);
} else {
return <div data-test="hook-api" {...API} />;
}
};
describe("useCustomHook", () => {
let container;
beforeEach(() => {
container = document.createElement("div");
document.body.appendChild(container);
});
afterEach(() => {
document.body.removeChild(container);
container = null;
});
it("onClick should set custom variable to true", () => {
const renderer = new ShallowRenderer();
act(() => {
renderer.render(
<HookAPITestHelper method="onClick" hook={useCustomHook} />
);
}, container);
const output = renderer.getRenderOutput();
const api = shallow(output);
expect(api.props().variable).toBe(true);
});
});
import React, { useState } from "react";
export default function useCustomHook(props) {
const [variable, setCustomVariable] = useState(false);
function onClick(e) {
setCustomVariable(true);
}
return {
// Methods
onClick,
// State Variables
variable
};
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment