0

How to mock the fetch statement using jest

export default function Login() {
  function LoginUser() {
    const requestOptions = {
      method: 'POST',
      headers: {
        'Content-Type': 'application/json',
        Accept: 'application/json',
      },
      body: JSON.stringify({ username: username, password: password }),
    };
    fetch('http://localhost:8080/post', requestOptions)
      .then((response) => {
        if (response.status === 200) {
          console.log('succesfull');
        } else {
          throw new Error('Invalid credentials');
        }
      })
      .catch((err) => {
        console.log(err);
      });
  }

  <Button
    block
    size='lg'
    type='submit'
    onClick={LoginUser}
    disabled={!validateForm()}
  >
    Login
  </Button>;
}

The above code should be unit tested using mock jest on click the loginuser the function is fetch the post request.

bindu shree
  • 29
  • 1
  • 6
  • How about `global.fetch = jest.fn(/* your fetch mock here */)` as in [this post](https://stackoverflow.com/a/69871210/6243352) that happens to be React Native but still should solve the problem? – ggorlen Nov 30 '21 at 16:30
  • I need to mock localhost 8008/post – bindu shree Dec 01 '21 at 04:16

0 Answers0