Home > Mobile >  How do you test a React function component state with Jest?
How do you test a React function component state with Jest?

Time:10-06

I am only starting with unit testing now and the course I am following has the following syntax for a test:

expect(app.state().gifts).toEqual([])

This is the syntax for the use of class components but that will be deprecated soon so I am using React function components instead.

How do you accomplish the same test with hooks?

Thanks

CodePudding user response:

You can use react-hooks-testing-library and test your hooks as well. Basic Hooks

Example :

useDisclosure.ts

import * as React from 'react';

export const useDisclosure = (initial = false) => {
  const [isOpen, setIsOpen] = React.useState(initial);
  const open = React.useCallback(() => setIsOpen(true), []);
  const close = React.useCallback(() => setIsOpen(false), []);
  const toggle = React.useCallback(() => setIsOpen((state) => !state), []);

  return { isOpen, open, close, toggle };
};

useDisclosure.test.ts

import { renderHook, act } from '@testing-library/react-hooks';
import { useDisclosure } from '../useDisclosure';

test('should open the state', () => {
  const { result } = renderHook(() => useDisclosure());
  expect(result.current.isOpen).toBe(false);
  act(() => {
    result.current.open();
  });
  expect(result.current.isOpen).toBe(true);
});

test('should close the state', () => {
  const { result } = renderHook(() => useDisclosure());
  expect(result.current.isOpen).toBe(false);
  act(() => {
    result.current.close();
  });
  expect(result.current.isOpen).toBe(false);
});

test('should toggle the state', () => {
  const { result } = renderHook(() => useDisclosure());
  expect(result.current.isOpen).toBe(false);
  act(() => {
    result.current.toggle();
  });
  expect(result.current.isOpen).toBe(true);
  act(() => {
    result.current.toggle();
  });
  expect(result.current.isOpen).toBe(false);
});

test('should define initial state', () => {
  const { result } = renderHook(() => useDisclosure(true));
  expect(result.current.isOpen).toBe(true);
  act(() => {
    result.current.toggle();
  });
  expect(result.current.isOpen).toBe(false);
});
  • Related