React酶+jest如何测试onSubmit
React enzyme + jest how to test onSubmit
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>
);
i have this code. this is a functional component.
and how can i test handleSubmit function?? or intercept axios call?
its called on onSubmit event.
its called on onSubmit event.
wrapper.find('form') .simulate('submit', { preventDefault () {} });
**this code successfuly called onSubmit on form,
but i dont understand how to test axios call inside her.**
您需要在您的测试文件中模拟 axios.post()
函数,以便 axios.post()
returns 一个已解决的承诺。
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
讨论导入后立即模拟 axios 的原因 here。
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>
);
i have this code. this is a functional component. and how can i test handleSubmit function?? or intercept axios call? its called on onSubmit event. its called on onSubmit event.
wrapper.find('form') .simulate('submit', { preventDefault () {} });
**this code successfuly called onSubmit on form,
but i dont understand how to test axios call inside her.**
您需要在您的测试文件中模拟 axios.post()
函数,以便 axios.post()
returns 一个已解决的承诺。
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
讨论导入后立即模拟 axios 的原因 here。