如何在 React/Jest 中模拟来自自定义挂钩的返回数据?

off*_*ton 6 javascript reactjs jestjs

我有一个名为 useFetch 的自定义钩子,它只是获取数据并返回它,在我的组件测试中,我想模拟这个钩子以返回一些假数据,我该怎么做呢?

import React, { useEffect, useState } from 'react';

export const useFetch = (url: string) => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
      } catch (error) {
        console.log(error);
      }
    };

    fetchData();
  }, [url]);

  return data;
};

const App = () => {
  const config = useFetch(`/api/url`);

  return (
    <div></div>
  );
};

export default App;

Run Code Online (Sandbox Code Playgroud)

无论如何,我可以模拟 useFetch 以便在我的 Jest 测试中将 const config 设置为一些虚拟数据吗?

Aja*_*jax 2

我建议将你的钩子放在单独的文件中,假设useFetch.js包含

import { useEffect, useState } from "react";

export const useFetch = (url: string) => {
  const [data, setData] = useState();

  useEffect(() => {
    const fetchData = async () => {
      try {
        const res = await fetch(url);
        const json = await res.json();
        setData(json);
      } catch (error) {
        console.log(error);
      }
    };

    fetchData();
  }, [url]);

  return data;
};

Run Code Online (Sandbox Code Playgroud)

保留您的应用程序组件文件,如下所示

import React from "react";

import { useFetch } from "./useFetch";


const App = () => {
  const config = useFetch(`/api/url`);

  return (
    <div></div>
  );
};

export default App;

Run Code Online (Sandbox Code Playgroud)

通过上面的拆分,您可以轻松模拟您的钩子,示例测试文件如下

import React from "react";
import { render } from "@testing-library/react";
import App from "./App";


// mock config
const mockConfig = {
    data: "mock data"
};

// this will mock complete file, we have provided mock implementation
// for useFetch function
jest.mock("./useFetch", () => ({
    useFetch: () => mockConfig
}));

test("should render with mock useFetch", () => {
    const { getByText } = render(<App />);
    // test logic goes here
});


Run Code Online (Sandbox Code Playgroud)

假设所有文件都在同一目录中。