【问题标题】:React enzyme + jest how to test onSubmitReact 酶 + jest 如何测试 onSubmit
【发布时间】:2020-07-15 08:44:03
【问题描述】:
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.**

【问题讨论】:

  • 为 Axios.post 创建一个模拟函数并让它返回一个已解决的承诺。

标签: jestjs axios enzyme react-functional-component


【解决方案1】:

您需要在您的测试文件中模拟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

【讨论】:

  • 嗨 tnh 寻求帮助,但是,我写了这段代码,返回 axios.post("/send-email").then(() => { expect(wrapper.find(Spinner)).toHaveLength (0); expect(wrapper.contains(

    成功!检查您的电子邮件以访问纽约市的 1000 名投资银行家。

    )).toBe(true); });并得到错误(无法读取未定义的属性'then')
  • it("如果成功获取则显示成功消息", () => { const wrapper = mount(); axios.post.mockImplementationOnce(() => Promise.resolve()); wrapper.find("input").simulate("change", { target: { value: "email@email.com" } }); expect(wrapper.find("input"). prop("value")).toBe("email@email.com"); wrapper.find("button").simulate("submit", { preventDefault() { } }); expect(wrapper.find(Spinner )).toHaveLength(1); return axios.post("/send-email").then(() => { expect(wrapper.find(Spinner)).toHaveLength(0); }); });
猜你喜欢
  • 1970-01-01
  • 2019-04-21
  • 2020-09-14
  • 2019-11-15
  • 2017-11-26
  • 1970-01-01
  • 2019-01-07
  • 2018-09-28
  • 2018-10-24
相关资源
最近更新 更多