我有一个名为 useFetch 的自定义钩子(Hook),它只是获取数据并返回它,在我的组件测试中,我只想模拟这个钩子(Hook)以返回一些假数据,我该怎么做呢?
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;
无论如何我可以模拟 useFetch 以便在我的 Jest 测试中将 const config 设置为一些虚拟数据?
最佳答案
我建议将您的钩子(Hook)放在单独的文件中,比如说 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;
};
保持您的应用程序组件文件如下
import React from "react";
import { useFetch } from "./useFetch";
const App = () => {
const config = useFetch(`/api/url`);
return (
<div></div>
);
};
export default App;
通过上述拆分,您可以轻松地模拟您的钩子(Hook),示例测试文件如下
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
});
假设所有文件都在同一个目录中。
关于javascript - 如何从 React/Jest 中的自定义钩子(Hook)模拟返回数据?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61542482/