使用 react-hooks-testing-library 测试自定义钩子

Test custom hook with react-hooks-testing-library

我正在尝试使用 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;

这是我的测试

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()
  })
});

测试“应该删除文章”已编写,但它们没有覆盖 useArticleDelete 挂钩中 deleteArticle 函数中 try..catch 之间的代码行。

请帮我看看我做错了什么

您需要在调用 deleteArticle 方法之前使用 await,因为它是异步调用。在完成 await deleteArticleById(articleId); 的执行之前,函数将 return 什么都没有,所以你需要等到它被执行。

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