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.