so I am trying to test that the onSubmit function is getting triggered if the button is clicked - the way im doing this is through testing the internals of the onSubmit function is getting calles (axios post method)
the test
describe('RecipeSearch', () => {
test('submit button should return post function to recipes/search/', () => {
let mock = new MockAdapter(axios);
userEvent.selectOptions(screen.getByRole('combobox'), 'Sweet');
userEvent.click(screen.getByText('Search'));
const config = {
headers: {
'Content-Type': 'application/json',
},
};
const searchRecipes = mock.onPost(
`${process.env.REACT_APP_API_URL}/recipes/search/`,
{ flavor_type: 'Sweet' },
{ config }
);
expect(searchRecipes).toHaveBeenCalled();
});
});
the Error
expect(received).toHaveBeenCalled()
Matcher error: received value must be a mock or spy function
Received has type: object
Received has value: {"abortRequest": [Function abortRequest], "abortRequestOnce": [Function abortRequestOnce], "networkError": [Function networkError], "networkErrorOnce": [Function networkErrorOnce], "passThrough": [Function passThrough], "reply": [Function reply], "replyOnce": [Function replyOnce], "timeout": [Function timeout], "timeoutOnce": [Function timeoutOnce]}
the function
const recipeSearch = (props) => {
const [formData, setFormData] = useState({
flavor_type: 'Sour',
});
const { flavor_type } = formData;
const [loading, setLoading] = useState(false);
const onChange = (e) => setFormData({ ...formData, [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);
props.setRecipes(res.data);
window.scrollTo(0, 0);
})
.catch((err) => {
setLoading(false);
window.scrollTo(0, 0);
});
};
return (
<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>
<button type='submit'>Search</button>
</div>
</div>
</div>
</form>
);
};
i have added the whole test and the component code so helping would be easier. thanks in advance
(added the onChange + onSubmit functions)
await waitFor()
? – LarryonSubmit
function come from? – Intensity