反应酶+开玩笑如何进行提交测试

问题描述 投票:0回答:1
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.**
jestjs axios enzyme react-functional-component
1个回答
0
投票

您需要在测试文件中模拟axios.post()函数,以便axios.post()返回已解决的承诺。

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

© www.soinside.com 2019 - 2024. All rights reserved.