我有一个名为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,让const config在我的Jest测试中设置为一些假数据?
我建议将你的钩子放在单独的文件中,比如说 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
});
假设所有的文件都在同一个目录下。