简体   繁体   中英

How can I mock error message when submit form with post method?

The project I just joined does not use an API from the backend but must create mock data by itself through the Axios-mock-adapter. I am making a form to change the password, if the inputs entered are correct, submit it will display successfully, if the inputs are not correct, an error will be displayed (eg input is not blank, the password is not matched...) How to do that?

.onPost("/user/changepassword"), {
      // How can I pass the values of the inputs
    })
    .reply(() => {
       // How can I check the value of the inputs: empty, password input does not match...
      if (conditions are ok) {
        return [200, MOCK_RESPONSE.SUCCESS];
      } else {
        return [200, MOCK_RESPONSE.ERROR];
      }
    });

You can try this code:

var mock = new AxiosMockAdapter(axios);
mock.onPost(/\/api\/*/).reply(config => {
  var params = Object.fromEntries(new URLSearchParams(config.data));
  if (params.name === 'tommy') {
    return [200, {success:true}];
  } else {
    return [200, {success:false}];
  }
})
axios.post('/api', (new URLSearchParams({name: 'tommy'})).toString()).then((res) => {
  console.log(res.data)
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM