Network errors

I will start by implementing the error handling for network errors in get-auth-token.ts module.
Unlike error responses, network errors will reject the fetch promise. This means that I can handle those errors in the catch callback attached to that promise:
const response = await fetch('https://api.example.com/auth', {
  method: 'POST',
  headers: {
    'Content-Type': 'application/json',
  },
  body: JSON.stringify(credentials),
}).catch((error) => {
  throw new Error('Authentication failed: network error', { cause: error })
})
πŸ¦‰ I am setting the original error as the cause property of the consumer-facing error for debugging purposes.
Next, let's mock the network error in the test.
In the get-auth-token.test.ts, I will head to the new empty test case and add a runtime handler that will always respond with a network error:
test('handles network errors', async () => {
  server.use(
    http.post('https://api.example.com/auth', () => {
      return Response.error()
    }),
  )
})
With this request handler, any request to the POST https://api.example.com/auth endpoint within this test will result in a network error. Note that I'm not trying to make the responses input-dependent, and instead introducing behavior-driven test cases to provide clarity and isolation for the tested code.
Finally, I will add an assertion for the getAuthToken() promise to verify that it rejects with the correct error message:
await expect(() =>
  getAuthToken({
    email: 'kody@epicweb.dev',
    password: 'supersecret123',
  }),
).rejects.toThrow('Authentication failed: network error')

Access Denied

You must login or register for the workshop to view the diff.

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