1. 页面不要直接依赖 axios ,抽象一个 requestService 出来
interface RequestService {
get<T>(url: string): Promise<T>;
}
class UserService {
constructor(private request: RequestService) {}
getUser(id: string) {
return this.request.get<{ name: string }>(`user/${id}`);
}
}
function useService() {
return new UserService({} as any);
}
const Page: React.FC<{ id: string }> = (props) => {
const service = useService();
const [name, setName] = useState();
useEffect(() => {
service.getUser(
props.id).then((response) => {
setName(name);
});
}, [
props.id]);
return <div>{name}</div>;
};
2. 可以直接对 axios 进行集成测试。 本地起一个 node 服务,拿 AxiosRequestService 去请求这个服务。
或者是利用 httpbin 等在线服务
interface RequestService {
get<T>(url: string): Promise<T>;
}
class AxiosRequestService implements RequestService {
get() {
axios.get('......');
}
}