Skip to content

Instantly share code, notes, and snippets.

@Oliver-ke
Forked from mauricedb/Subject under test
Created March 9, 2021 11:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Oliver-ke/6e98b095716a8ff6bec011eb5a2ec17d to your computer and use it in GitHub Desktop.
Save Oliver-ke/6e98b095716a8ff6bec011eb5a2ec17d 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);
});
@Oliver-ke
Copy link
Author

Mocking useState in a component with using useState

import * as React from 'react';

describe('Some message', () => {
    const setState = jest.fn();
    // eslint-disable-next-line @typescript-eslint/no-explicit-any
    const useStateMock: any = (initState: any) => [initState, setState];

    afterEach(() => {
      jest.clearAllMocks();
    });

    it('Is a test where we want to mock useState', () => {
          jest.spyOn(React, 'useState').mockImplementation(useStateMock);
          const wrapper = shallow(<Component {...props} />);
          // trigger setState somehow
          expect(setState).toHaveBeenCalledTimes(1);
          // Other tests here
    });
});

@Oliver-ke
Copy link
Author

more examples

import React, { useState as useStateMock } from 'react';

jest.mock('react', () => ({
  ...jest.requireActual('react'),
  useState: jest.fn(),
}));

describe('testing useState mocked', () => {
  const setState = jest.fn();
  const useStateMock = (initState: any) => [initState, setState];

  jest.spyOn(React, 'useState').mockImplementation(useStateMock);

  afterEach(() => {
    jest.clearAllMocks();
  });

  // your tests goes here
});

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