【发布时间】:2021-06-17 09:26:30
【问题描述】:
所以我正在尝试测试 onSubmit 函数在单击搜索按钮后的处理方式。
我尝试测试的方法是测试 onSubmit 函数的内部结构。
所以我基本上是在尝试测试 axios 请求的行为。 (如果调用成功)
在测试中,我模拟了 axios 请求并将数据传递给它,并尝试查看它是否在单击搜索按钮后被调用,由于某种原因,我在此测试中不断收到错误。
我会感谢任何可以帮助我的人。
测试
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 = ({ setRecipes }) => {
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);
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>
);
};
【问题讨论】:
标签: reactjs unit-testing jestjs integration-testing react-testing-library