Skip to content

Instantly share code, notes, and snippets.

@JoshuaKGoldberg
Created January 13, 2020 15:20
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 JoshuaKGoldberg/d1ceed94fac7e8ba50e7a80813542250 to your computer and use it in GitHub Desktop.
Save JoshuaKGoldberg/d1ceed94fac7e8ba50e7a80813542250 to your computer and use it in GitHub Desktop.
useGlobals
describe("Cheese", () => {
it("renders milk when aging is not yet complete", () => {
const wrapped = mount(<Cheese />);
expect(wrapped.text()).toBe("🥛");
});
it("renders cheese when aging has completed", () => {
const wrapped = mount(<Cheese />);
const { clock } = useGlobals();
act(() => clock.tick(1000));
wrapped.rerender();
expect(wrapped.text()).toBe("🧀");
});
});
const Cheese = () => {
const [aged, setAged] = useState(false);
const { clearTimeout, setTimeout } = useGlobals();
useEffect(() => {
const handle = setTimeout(setAged, 1000, true);
return () => clearTimeout(handle);
}, [aged, clearTimeout, setAged, setTimeout]);
return <>{aged ? "🧀" : "🥛"}</>;
};
export default Cheese;
import { createClock } from "lolex";
const globals = (() => {
if (process.env.NODE_ENV !== "test") {
return { clearTimeout, setTimeout };
}
const clock = createClock();
return {
...clock,
clock
};
})();
export const useGlobals = () => globals;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment