Created
January 13, 2020 15:20
-
-
Save JoshuaKGoldberg/d1ceed94fac7e8ba50e7a80813542250 to your computer and use it in GitHub Desktop.
useGlobals
This file contains 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
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("🧀"); | |
}); | |
}); |
This file contains 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
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; |
This file contains 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 { 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