Mock responses
Loading "Mock Responses"
Run locally for transcripts
Our
getAuthToken()
function significantly depends on the response returned from the server. 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 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 a 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 returns the right token
from the received response. Verify your solution by running npm test
.