Mock responses

Loading "Mock Responses"
Our getAuthToken() function depends on the response returned from the server quite singificantly. For starters, there's a validation layer to handle error responses:
if (response.status === 401) {
  throw new Error('Authentication failed: invalid credentials')
}

if (!response.ok) {
  throw new Error('Authentication failed: network error')
}
Then, there's a successful, "happy path" scenario handling, where we read the response body as JSON and return the token property from the response body:
const json = await response.json()

return {
  token: json.token,
}
And we need to test all of those scenarios!
But let's start from the beginning. Let's start from the happy path.
If the server returns a 200 response, our function will read its body and return some of its properties. That's a great intention to put into test.
For that intention to happen, the POST https://api.example.com/auth request must be (1) intercepted; and (2) mocked. Wait, those two steps are precisely what request handlers are for!
πŸ‘¨β€πŸ’Ό In this exercise, create a new request handler in handlers.ts for the request made by the getAuthToken() function. Respond to that request with a mocked JSON response containing { token: 'abc-123' } in its body. And, finally, finish the test at to validate the getAuthToken() function returning the right token from the received response. Verify your solution by running npm test.

Access Denied

You must login or register for the workshop to view and run the tests.

Check out this video to see how the test tab works.