Loading
Current section: Testing Asynchronous Code 5 exercises
Problem

Testing with Async Side Effects

Transcript

00:00 So far, you've been dealing with a synchronicity that you control because you declare it. So as an example, in this greetByResponse function, the whole function is returned a promise so you can await it. And even when you're testing promise rejections, you can still await this promise to reject. But sometimes there is a synchronicity and side effects that lie outside of your control. Let me give you an example.

00:19 So our application grows, and now it has the whole notification manager to handle user greetings. Basically, imagine it like a manager that shows notifications in the UI. And this class has a showNotification method that accepts a response and then passes it to the greetByResponse function that you're familiar with. So once this function finishes reading the response body

00:38 and gets the username, it returns a greeting text, which then is being pushed to this notifications array. And this push can really represent any side effect. For example, a UI update when you update react state is a side effect. You don't know how fast it's going to occur and the actual DOM elements will be rendered.

00:55 Or maybe you're accessing the DOM API directly in your code, which is also a side effect that returns no promises. So if we tried to write the automated test for this manager by creating the manager and then calling this showNotification method with a mock response, we can then try to assert the first notification that's being pushed, which is supposed to be for Kate,

01:14 to be, "Hello, Kate. Happy Monday." If we run this test, we will see that this assertion fails. In fact, it expects undefined to equal to our greeting message, which means that the whole left side of this expect call was undefined. This happens because reading the response body takes time. So when this expect statement runs,

01:33 the notifications array is still empty. But here's a pickle. There's no promises returned to await. And this will be the task for you to solve in this exercise. You will orchestrate this test properly by using a new function called waitFor so you can await the state transition when this greeting message actually appears in the notifications array.