我正在尝试使用 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 之间的代码行。
请帮助我找出我做错了