【发布时间】:2021-05-12 13:19:11
【问题描述】:
所以我正在尝试测试 onSubmit 函数是否在单击按钮时被触发 - 我这样做的方法是通过测试 onSubmit 函数的内部获取调用(axios post 方法)
测试
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();
});
});
错误
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]}
函数
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>
);
};
我已经添加了整个测试和组件代码,所以帮助会更容易。 提前致谢
(添加 onChange + onSubmit 函数)
【问题讨论】:
-
有时 Formik 需要一些滴答声才能通过验证和一切——您是否尝试过将这种期望包装在
await waitFor()中? -
试过了,还是不行。
-
在你的组件代码中,
onSubmit函数来自哪里?
标签: reactjs testing jestjs react-testing-library