Skip to content

Instantly share code, notes, and snippets.

@cyberplanner
Forked from mauricedb/Subject under test
Created May 30, 2022 23:10
Show Gist options
  • Save cyberplanner/8832b02571aefd1a5ca2584df0d8e809 to your computer and use it in GitHub Desktop.
Save cyberplanner/8832b02571aefd1a5ca2584df0d8e809 to your computer and use it in GitHub Desktop.
Testing stateful React hooks
import { useState } from 'react';
export function useCounter(initial = 0) {
const [count, setCount] = useState(initial);
return [count, () => setCount(count + 1)];
}
import { useCounter } from './Calculator';
const mockSetState = jest.fn();
jest.mock('react', () => ({
useState: initial => [initial, mockSetState]
}));
test('Can increment from 1 to 2', () => {
const [_, increment] = useCounter(1);
increment();
expect(mockSetState).toHaveBeenCalledWith(2);
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment