1

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

1 Answer 1

1

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()
  })
Sign up to request clarification or add additional context in comments.

2 Comments

Thank you. But what about if deleteArticleById returns an error. Is it a right way to test this? test('should throw error', async () => { deleteArticleById.mockRejectedValue(new Error) const { result } = renderHook(() => useArticleDelete()) try { await result.current.deleteArticle() } catch (e) { expect(e).toBeInstanceOf(Error) } })
Thats right you can test it like you said

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.