Search
 
SCRIPT & CODE EXAMPLE
 
CODE EXAMPLE FOR JAVASCRIPT

how to test useState in jest

import { useState } from 'react';

export function useCounter(initial = 0) {
  const [count, setCount] = useState(initial);

  return [count, () => setCount(count + 1)];
}
Unit test
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);
});
 
PREVIOUS NEXT
Tagged: #test #useState #jest
ADD COMMENT
Topic
Name
4+9 =