reactjs - 如何测试使用自定义 TypeScript React Hook 的组件?

标签 reactjs typescript jestjs axios react-hooks

我目前正在 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/

相关文章:

javascript - 如何开 Jest 测试 DPI

javascript - 如何使用 Enzyme 和 Jest 测试 Formik Fields?

javascript - 为什么这里要大写 React 呢?从 'react' 导入 * 作为 React

reactjs - React-Native-Web 与 ReactJS

reactjs - 如何在 React 函数中返回 JSON

javascript - 如何判断一个特定模块是 CommonJS 模块还是 ES6 模块?

angular - 从 api 响应创建可观察数组

javascript - 箭头函数和bind()的区别

ios - 如何在 React Native 中使用 AsyncStorage 正确获取 Item?

javascript - 使用 jest 模拟其他模块中的函数依赖关系