【发布时间】:2020-01-15 11:58:42
【问题描述】:
我目前正在 Typescript 中编写一个 React 组件,它使用一个名为 useAxios 的 axios-hooks 钩子。这个钩子的一个使用例子是here:
export const App = () => {
const [{ data, loading, error }, refetch] = useAxios(
"https://api.myjson.com/bins/820fc"
);
if (loading) return <p>Loading...</p>;
if (error) return <p>Error!</p>;
return (
<div>
<button onClick={e => refetch()}>refetch</button>
<pre>{JSON.stringify(data, null, 2)}</pre>
</div>
);
};
const rootElement = document.getElementById("root");
render(<App />, rootElement);
我试图弄清楚如何编写一个可以模拟 useAxios 钩子的测试。我尝试创建底层 axios 组件的模拟,但无法正常工作:
import React from "react"
import { render } from "@testing-library/react"
import { Test } from "../test"
import useAxios from "axios-hooks"
jest.mock("axios-hooks")
const mockedAxios = useAxios as jest.Mocked<typeof useAxios>
it("Displays loading", () => {
// How to mock the return values in the following line?
// mockedAxios.
const { getByText } = render(<Test />)
expect(getByText("Loading...")).toBeDefined()
})
我知道我不应该模拟作为底层依赖项的 axios,我应该能够模拟 useAxios,但无论如何我都会尝试。
我意识到这个问题在 SO 上已经被多次提及,但我可以找到解决这个特定用例的方法。
非常感谢任何帮助!
【问题讨论】:
-
如果你
jest.mock("axios-hooks")和后来的useAxious.mockResolvedValue(dataToRespond)会发生什么?还是您需要基于 URL 的动态模拟? -
当我使用打字稿时,我似乎无法做到这一点。我认为有办法使用 TS 做到这一点?
-
所以问题特定于 TS 中的类型检查,对吧?对我来说,它看起来像是测试运行,但模拟并没有在这样的事情上工作
-
@skyboyer 我用示例测试更新了我的问题。我试图弄清楚如何模拟 TS 中的钩子返回值。
标签: reactjs typescript jestjs axios react-hooks