1

我正在尝试使用 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 之间的代码行。

请帮助我找出我做错了

4

1 回答 1

1

您需要在调用该deleteArticle方法之前使用 await,因为它是异步调用。函数在完成执行之前不会返回任何内容,await deleteArticleById(articleId);因此您需要等到它被执行。

test('should delete article', async () => {
    deleteArticleById.mockResolvedValue({});
    const { result } = renderHook(() => useArticleDelete())
    await result.current.deleteArticle()
    expect(result.current.articleId).toBeNull()
  })
于 2021-03-26T07:40:30.413 回答