Skip to content

Instantly share code, notes, and snippets.

@mauricedb
Last active December 7, 2023 14:46
Show Gist options
  • Save mauricedb/eb2bae5592e3ddc64fa965cde4afe7bc to your computer and use it in GitHub Desktop.
Save mauricedb/eb2bae5592e3ddc64fa965cde4afe7bc 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);
});
@sjpox
Copy link

sjpox commented Nov 16, 2023

You may consider using renderHook (testing-library/react). I find it easy to use.

Here is the sample code:

const { result } = renderHook(() => {
      const [isOpen, setIsOpen] = useState(true)
      return { isOpen, setIsOpen }
    })

    const renderValue = await act(() => {
      return render(
        <ProductFormDialog
          isOpen={result.current.isOpen}
          setIsOpen={result.current.setIsOpen}
        />
      )
    })

    const displayValue = renderValue.getByTestId('header-container').textContent
    expect(displayValue).toEqual('Header')

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment