Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save andiwinata/bee847c23913607ed0300f717da7f6fc to your computer and use it in GitHub Desktop.
Save andiwinata/bee847c23913607ed0300f717da7f6fc to your computer and use it in GitHub Desktop.
Enzyme vs react testing library on calling useEffect
export const usePolling = ({ pollFn, interval }: Params, deps: any[]) => {
useEffect(() => {
let timeout: number | undefined;
let isMounted = true;
const poller = async () => {
await pollFn();
// only do next polling if the function is still mounted
// i.e. it hasn't been replaced by new function because `deps` change
if (isMounted) {
timeout = window.setTimeout(() => {
poller();
}, interval);
}
};
poller();
return () => {
isMounted = false;
window.clearTimeout(timeout);
};
}, deps);
};
// For above hook
// This is for react testing library
test('testing library', () => {
const pollFnSpy = jest.fn().mockReturnValue(Promise.resolve());
const TestComponent = ({ dep }: { dep: string }) => {
usePolling(
{
pollFn: () => pollFnSpy(dep),
interval: 5000,
},
[dep],
);
return null;
};
const { rerender, unmount } = render(<TestComponent dep="value-1" />);
expect(pollFnSpy).toHaveBeenNthCalledWith(1, 'value-1'); // instantly after render
});
// This is for enzyme
test('enzyme', () => {
const pollFnSpy = jest.fn().mockReturnValue(delay(10));
const TestComponent = () => {
usePolling(
{
pollFn: pollFnSpy,
interval: 5,
},
[],
);
return null;
};
const wrapper = mount(<TestComponent />);
jest.advanceTimersByTime(1000); // need to wait
expect(pollFnSpy).toHaveBeenCalledTimes(1);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment