const handleSubmit = (e) => {
.preventDefault();
if (!/^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$/i.test(value)) {
setError(true);
return;
}
if (loading) return;
setError(false);
setLoading(true);
return Axios.post("/send-email", { value, messageHtml }).then(() => {
clearTimeout(timerId);
setSuccess(true);
setLoading(false);
setValue("");
timerId = setTimeout(() => {
setSuccess(false);
}, 5000);
}).catch(() => setLoading(false));
};
render(
<form onSubmit={handleSubmit} id="get-list-form" autoComplete="off">
<input
value={value}
required
onChange={handleChange}
className="input
placeholder="Enter your email "
type="text"
/>
<button type="submit" className={`button ${btnClass}`}>{btnMessage}</button>
</form>
);
我有此代码。这是一个功能组件。 以及如何测试handleSubmit函数?或拦截axios电话? 其调用onSubmit事件。 它调用了onSubmit事件。
wrapper.find('form') .simulate('submit', { preventDefault () {} });
**this code successfuly called onSubmit on form,
but i dont understand how to test axios call inside her.**
答案 0 :(得分:0)
您需要在测试文件中模拟axios.post()
函数,以便axios.post()
返回已解决的Promise。
import * as axios from 'axios';
import MyComponent from '../MyComponent';
jest.mock('axios');// this should come immediately after imports
test('MyComponent handle submit', ()=>{
axios.post.mockImplementationOnce(() => Promise.resolve());
// rest of your test
});
有关更多信息,请查看Jest mock functions doc
讨论了here导入后立即模拟axios的原因。