我有一个 React 组件,它向我的 api 发送到recipes/search
端点的 post 请求。
const recipeSearch = ({ setRecipes }) => {
const [flavorType, setFlavorType] = useState({
flavor_type: 'Sour',
});
const { flavor_type } = flavorType;
const [loading, setLoading] = useState(false);
const onChange = (e) => setFlavorType({ ...flavorType, [e.target.name]: e.target.value });
const onSubmit = (e) => {
e.preventDefault();
const config = {
headers: {
'Content-Type': 'application/json',
},
};
setLoading(true);
axios
.post(
`${process.env.REACT_APP_API_URL}/recipes/search/`,
{
flavor_type,
},
config
)
.then((res) => {
setLoading(false);
setRecipes(res.data);
window.scrollTo(0, 0);
})
.catch(() => {
setLoading(false);
window.scrollTo(0, 0);
});
};
return (
<div data-testid='RecipeSearch'>
<form onSubmit={(e) => onSubmit(e)}>
<div>
<div>
<div>
<label htmlFor='flavor_type'>Choose Flavor</label>
<select name='flavor_type' onChange={(e) => onChange(e)} value={flavor_type}>
<option value='Sour'>Sour</option>
<option>Sweet</option>
<option>Salty</option>
</select>
</div>
<div>
{loading ? (
<div>
<Loader type='Oval' color='#424242' height={50} width={50} />
</div>
) : (
<button type='submit'>Search</button>
)}
</div>
</div>
</div>
</form>
<div>{testing}</div>
</div>
);
};
recipeSearch.propTypes = {
setRecipes: PropTypes.func.isRequired,
};
export default recipeSearch;
提交表单onSubmit
后,将调用该函数,该函数又将请求发布到我的后端 api
axios
.post(
`${process.env.REACT_APP_API_URL}/recipes/search/`,
{
flavor_type,
},
config
)
我想测试该请求是否确实发送到了正确的 url。
我正在使用 React 测试库,并且想知道使用该jest-mock-axios
库执行此操作的正确方法是什么