我有一个名为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;
反正我还能模拟useFetch以便在Jest测试中将const config设置为一些虚拟数据吗?
答案 0 :(得分: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;
};
按如下方式保存您的应用程序组件文件
import React from "react";
import { useFetch } from "./useFetch";
const App = () => {
const config = useFetch(`/api/url`);
return (
<div></div>
);
};
export default App;
通过上述拆分,您可以轻松地模拟您的钩子,如下所示是示例测试文件
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
});
假设所有文件都在同一目录中。