- [Instructor] Asynchronous code is very common
in front end applications.
This makes it very important to learn
how to test the parts of your code base
that you want asynchronously.
For this purpose, a new function, async print,
have been added to the utilities model.
This function mocks an asynchronous process
by printing out the hello world string
two seconds after it is invoked.
The async function without a promise that resolves a string.
Let's go ahead and test this function's behavior.
To follow along with this video,
you need the 02_06b branch of the project.
So make sure you are on the 02_06b branch.
Go into the test folder and create a new file
with the name async.js.
Inside the test file, import the async print function.
Next, we'll be writing a test case
that checks that the asynchronous function
prints the string hello world as expected.
Inside a test case scaffold,
we call the asynchronous function and use the promise API
to get its results.
Make sure you return the promise
by adding the return keyword
just before the async print function call.
This is important for jest to terminate the process
after executing the test.
Now that we have the result in the data variable,
we can post it to test it with the expect method
and the to be matcher.
Good, now save the file
and head over to the command line to run the test.
As we can see, our tests pass as expected.
Do take into consideration that the time it takes
for the asynchronous process to complete
is included in the total time it takes to test to complete.
Using the thenable promise syntax
is one way to work with asynchronous tests and jest.
Another way to test asynchronous code and jest
is to use the async await syntax.
Let's head back to our test file
and write the async await version
of the test case we just ran.
Back in the test file,
let's comment out the first test case that we have written.
Now, write another test case exactly like the previous one,
but this time, we'll be adding the async keyword.
The async keyword will be added
just before the call back function.
Now regard the test using expect to assert the result
of the async print function call.
Because we're testing under asynchronous function,
the await keyword needs to proceed the expect call.
Next, we need a matcher to test the output of the function.
For promised based async functions,
the expect function as a resolves property
that needs to be called
before calling the matcher function.
The resolves property as a fluent API
that can be changed to any of the available matchers.
Just like the previous version of the test,
we use the to be matcher
to assert the expected string output of hello world.
Save this file and return to the CLI to run the test.
As expected, we have passing tests once again.
Feel free to choose the syntax you prefer.
After all, it's just syntax.
One syntax does not have functional advantage
over the other.