mkonav
mkonav

Reputation: 13

Test custom hook with react-hooks-testing-library

I am trying to write tests for this custom hook using react-hooks-testing-library.

import { deleteArticleById } from '../../API/articles/deleteArticleById';
const useArticleDelete = () => {
  const [articleId, setArticleId] = useState(null);
  const setArticleIdToDelete = id => {
    setArticleId(id);
  };

  const deleteArticle = useCallback(
    async () => {
      if (!articleId) {
        return;
      }

      try {
        await deleteArticleById(articleId);
        setArticleId(null);
      } catch (e) {
        console.log(e);
      }
    },
    [articleId]
  );

  return { articleId, setArticleIdToDelete, deleteArticle };
};

export default useArticleDelete;

Here are my tests

import { renderHook, act } from '@testing-library/react-hooks'
import { deleteArticleById } from '../../API/articles/deleteArticleById';
import useArticleDelete from './useArticleDelete';

jest.mock('../../API/articles/deleteArticleById');

describe('useArticleDelete', () => {
  test('should use ArticleDelete', () => {
    const { result } = renderHook(() => useArticleDelete())
    act(() => {
      result.current.setArticleIdToDelete(1)
    })
    expect(result.current.articleId).toBe(1)
  });

  test('should delete article', async () => {
    deleteArticleById.mockResolvedValue({});
    const { result } = renderHook(() => useArticleDelete())
    act(() => {
      result.current.deleteArticle()
    })
    expect(result.current.articleId).toBeNull()
  })
});

Test "should delete article" is written, but the they don't cover lines of code between try..catch in deleteArticle function in useArticleDelete hook.

Please help my out to find out that i'm doing wrong

Upvotes: 1

Views: 1486

Answers (1)

Yadab
Yadab

Reputation: 1883

You need to use await before you call the deleteArticle method as it is an async call. Function will return nothin until it finished the execution of await deleteArticleById(articleId); so you need to wait until it gets executed.

test('should delete article', async () => {
    deleteArticleById.mockResolvedValue({});
    const { result } = renderHook(() => useArticleDelete())
    await result.current.deleteArticle()
    expect(result.current.articleId).toBeNull()
  })

Upvotes: 1

Related Questions