我目前正在 Typescript 中编写一个 React 组件,它使用 axios-hooks名为 useAxios 的钩子(Hook)。使用中的这个钩子(Hook)的一个例子是 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 Hook 的测试。我尝试创建底层 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 上多次提到,但我可以找到这个特定用例的解决方案。
非常感谢任何帮助!
最佳答案
我自己想出了如何做到这一点。为了测试自定义 Hook ,我执行了以下操作:
import * as useAxios from "axios-hooks"
jest.mock("axios-hooks")
const mockedAxios = useAxios as jest.Mocked<typeof useAxios>
it("Displays loading message", async () => {
// Explicitly define what should be returned
mockedAxios.default.mockImplementation(() => [
{
data: [],
loading: true,
error: undefined
},
() => undefined
])
const { getByText } = render(<Test />)
expect(getByText("Loading...")).toBeDefined()
})
关于reactjs - 如何测试使用自定义 TypeScript React Hook 的组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57926493/