如何使用开玩笑和酶在内部使用多个API调用测试使用效果
我想用两个API调用测试使用效果,如下所示。我如何嘲笑API致电或在这种情况下如何监视 Fetchcountry & fetchstates 函数,然后如何
使用jest&酶
import React, { useEffect, useState } from "react";
import fetchCountry from "../fetchCountry";
import fetchState from '../fetchState';
const App = () => {
const [country, setCountry] = useState();
const [state, setStates] = useState();
useEffect(() => {
loadData()
}, []);
const loadData = async()=>{
const country = await fetchCountry('Japan');
const states = await fetchState(country.code)
setCountry(country);
setStates(states)
}
fetchcountry.js(虚拟实施)
const fetchCountry = (countryName) => {
const requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
return fetch(`https://restcountries.com/v2/name/${countryName}`, requestOptions).then(res=>res.ok && res.json());
};
export default fetchCountry;
fetchstate.js
const fetchState = (countryCode) => {
const requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
return fetch(`https://restcountries.com/v2/name/${countryCode}`, requestOptions).then(res=>res.ok && res.json());
};
export default fetchState;
I want to test useEffect with two api calls as shown below. How can I mock api call or in this case how can I spy on fetchCountry & fetchStates functions and then how to test setCountry and setStates functions
using Jest & Enzyme
import React, { useEffect, useState } from "react";
import fetchCountry from "../fetchCountry";
import fetchState from '../fetchState';
const App = () => {
const [country, setCountry] = useState();
const [state, setStates] = useState();
useEffect(() => {
loadData()
}, []);
const loadData = async()=>{
const country = await fetchCountry('Japan');
const states = await fetchState(country.code)
setCountry(country);
setStates(states)
}
fetchCountry.js (dummy implementation)
const fetchCountry = (countryName) => {
const requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
return fetch(`https://restcountries.com/v2/name/${countryName}`, requestOptions).then(res=>res.ok && res.json());
};
export default fetchCountry;
fetchState.js
const fetchState = (countryCode) => {
const requestOptions = {
method: "GET",
headers: { "Content-Type": "application/json" }
};
return fetch(`https://restcountries.com/v2/name/${countryCode}`, requestOptions).then(res=>res.ok && res.json());
};
export default fetchState;
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
实际上,您不需要测试usestate钩子。它是React的一部分,已经由其维护者进行了测试。
让我们回到
fetchcountry
和fetchstate
。在您的测试中:
You actually don't need to test useState hook. It is a part of React and it is already tested by its maintainers.
Let's come back to
fetchCountry
andfetchState
.In your test: