Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/javascript/390.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 如何在名为onSubmit的jest中测试fetch_Javascript_Reactjs_Testing_Jestjs_Fetch - Fatal编程技术网

Javascript 如何在名为onSubmit的jest中测试fetch

Javascript 如何在名为onSubmit的jest中测试fetch,javascript,reactjs,testing,jestjs,fetch,Javascript,Reactjs,Testing,Jestjs,Fetch,我第一次使用jest进入React js应用程序的测试阶段,我发现很难测试在表单的onSubmit事件上实现的fetch是否已被调用。下面是我的元素和函数: <Formik initialValues={{ username: '', password: '' }} validationSchema={Yup.object().shape({ username: Yup.string

我第一次使用jest进入React js应用程序的测试阶段,我发现很难测试在表单的onSubmit事件上实现的fetch是否已被调用。下面是我的元素和函数:

<Formik
        initialValues={{
          username: '',
          password: ''
        }}
        validationSchema={Yup.object().shape({
          username: Yup.string().max(255).required('Username is required'),
          password: Yup.string().max(255).required('Password is required')
        })}
        onSubmit={(values) => {
            fetch(config.url.API_URL+'/api/login/', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json'
                },
                body: JSON.stringify(values)
            }).then(res => res.json())
                .then(res => {
                    if (res.Fail === "User does not exist") {
                        alert('Username e/o password not valid, please retry');
                    } else if (res.Fail === "Wrong password provided") {
                        alert('Wrong password, please retry');
                    }
                    else {
                        if (res.Success === "Vendor login successful") {
                            alert('Login Successful');
                            navigate('/dashboard', {replace: true});
                        } else {
                            alert('Customer Login Successful');
                        }
                    }
                })
        }}
      >
{
fetch(config.url.API_url+'/API/login/'{
方法:“POST”,
标题:{
“内容类型”:“应用程序/json”
},
正文:JSON.stringify(值)
}).then(res=>res.json())
。然后(res=>{
if(res.Fail==“用户不存在”){
警报(“用户名e/o密码无效,请重试”);
}否则如果(res.Fail==“提供了错误的密码”){
警报(“密码错误,请重试”);
}
否则{
如果(res.Success==“供应商登录成功”){
警报(“登录成功”);
导航('/dashboard',{replace:true});
}否则{
警报(“客户登录成功”);
}
}
})
}}
>
这是我的测试:

test('fetches data', () => {
  
  render(<Login />, container);
  
  
  const spy = jest.spyOn(global, 'fetch');

  const txtUsername = screen.getByTestId("txt-username").querySelector('input');
  const txtPassword = screen.getByTestId("txt-password").querySelector('input');
  const buttonLogin = screen.getByTestId("btn-login");
  const form = screen.getByTestId("form");
  

  fireEvent.change(txtUsername, { target: { value: "test_user" } });
  fireEvent.change(txtPassword, { target: { value: "test_pass" } });
  fireEvent.click(buttonLogin);        


  expect(txtPassword).toHaveValue("test_pass");
  expect(txtUsername).toHaveValue("test_user");
 
  expect(global.fetch).toHaveBeenCalledTimes(1);
  expect(global.fetch).toHaveBeenCalledWith('http://localhost:8000/api/login/');

  
  process.nextTick(() => { 
    global.fetch.mockClear(); 
    done(); 
  });
}); 
test('获取数据',()=>{
渲染(,容器);
const spy=jest.spyOn(全局“fetch”);
const txtUsername=screen.getByTestId(“txt用户名”).querySelector(“输入”);
const txtPassword=screen.getByTestId(“txt密码”).querySelector(“输入”);
const buttonLogin=screen.getByTestId(“btn登录”);
const form=screen.getByTestId(“表单”);
change(txtUsername,{target:{value:“test_user”});
change(txtPassword,{target:{value:“测试通过”}});
fireEvent.单击(按钮登录);
expect(txtPassword).toHaveValue(“测试通过”);
expect(txtUsername).toHaveValue(“测试用户”);
expect(global.fetch).toHaveBeenCalledTimes(1);
expect(global.fetch).toHaveBeenCalledWith('http://localhost:8000/api/login/');
process.nextTick(()=>{
global.fetch.mockClear();
完成();
});
}); 
我只想测试在事件单击submit按钮时调用fetch。在当前情况下,它告诉我从未调用fetch。

Checkout MSW()。我发现这是模拟API端点的最简单方法。