Current section: Testing Asynchronous Code 5 exercises

Awaiting Async Tests


00:00 I will start by going to the implementation of the test function that we have in set_up.ts file. Because our test, our callback, is an asynchronous function now, in order to await the promise introduced by the greet_by_response function, we also need to await it in the test, to even know its status, whether it's failing or passing, so we can properly report it in the console.

00:19 Because we're using the await keyword now, we need to mark the whole test function as asynchronous. Once we do that, we can run the tests, and we can see this failing test being correctly reported as failing. In fact, you can see that the order of this test is a little different. So the first and the third tests run first, and then this test, which is asynchronous, concludes the last.

00:39 Now we can take a look at this assertion, and we can see that it's failing. We're expecting "Hello, Patrick!" from here, but we're actually getting "Hello, Undefined!" So this strongly suggests that what we're passing as a username is not defined, or maybe we're accessing it incorrectly. So here, we are passing this response to the function, and it looks okay. So let's take

00:58 a look at the function itself. We're expecting to read the response body, store it in a user object, and access the firstName property. Now, that doesn't look right. I think in our test, we're actually using the the name property. So let's adjust it to be firstName, and rerun the tests.

01:13 With this change, the tests are passing correctly. You may be wondering, "Haven't I just learned that I should always trust the test?" That is true. You should always trust the expectations described in the test. But in this case, the expectation stays the same. The problem was in the testing setup.

01:29 In this mock response we prepared, in order for this readByResponse function to even run, we simply prepared a response with an object that was not compatible with what we have in the function. So it was accessing the property that doesn't exist. The big takeaway from this exercise is that remember that you should always await the synchronicity you introduce. Like this,

01:48 readByResponse function returns a promise. So make sure to await it to have this test pass reliably