I have a React component that does a post request to my api to the recipes/search
endpoint.
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;
When the form is submitted the onSubmit
function is called which in turn does post request to my backend api
axios
.post(
`${process.env.REACT_APP_API_URL}/recipes/search/`,
{
flavor_type,
},
config
)
I want to test that the request is indeed sent to the correct url.
I am using the React Testing Library and would like to know what is the correct way to do this using the jest-mock-axios
library
Aucun commentaire:
Enregistrer un commentaire