Awaiting Promises
Loading "Handling Promises in Tests"
Run locally for transcripts
In our application, we use the
greet()
function a lot in conjunction with fetching the user from a server. To simplify this usage, we've introduced a new function called greetByResponse()
that accepts a Fetch API Response
instance representing the user response from the server.export async function greetByResponse(response: Response) {
const user = await response.json()
return greet(user.firstName)
}
So now, whenever we need to greet a fetched user, we can use this new function:
fecth('/api/user')
.then(response => greetByResponse(response))
.then(greeting => render(greeting))
Next, we've added a test case for the
greetByResponse()
function. Since it's marked as async
, it will return a promise when run. We will account for that promise by making the test callback async
and await
'ing the result of the greetByResponse()
function call in the test:test('returns a greeting message for the given user response', async () => {
const response = Response.json({ name: 'Patrick' })
expect(await greetByResponse(response)).toBe('Hello, Patrick! Happy, Monday.')
})
All the tests are passing once we run them but there's also some assertion error printed after the tests. It looks suspiciously related to
greetByResponse()
.โ returns a greeting message for the given name
โ returns a greeting message for the given user response
โ returns a congratulation message for the given name
Error: Expected Hello, undefined! Happy, Monday. to equal to Hello, Patrick! Happy, Monday.
The issue here is that the
test()
function doesn't wait for the test to finish (in our case, for the greetByResponse()
function to finish reading the user response body as JSON) so it prints a successful run even if the test fails!๐จ Your task for this exercise is to adjust the
test()
function to support the callback()
being asynchronous and have the newly added test pass.