We will now explore testing functions that return a Promise. Let’s return to the findRecipe() function altered slightly. Instead of passing the fetched data to a callback, the function will now return a Promise. We now can use this function, along with the await keyword, like so:

const recipe = await findRecipe('pesto'); console.log(recipe); /* Prints { 'Basil': '2 cups', 'Pine Nuts': '2 tablespoons', 'Garlic': '2 cloves', 'Olive Oil': '0.5 cups', 'Grated Parmesan': '0.5 cups' } */

Jest supports the use of the async and await keywords, making handling Promises a breeze! Our test for the findRecipe() function can now be written like so:

test("get the full recipe for pesto", async () => { //arrange const dish = "Pesto" const expectedRecipe = { 'Basil': '2 cups', 'Pine Nuts': '2 tablespoons', 'Garlic': '2 cloves', 'Olive Oil': '0.5 cups', 'Grated Parmesan': '0.5 cups' } //act const actualRecipe = await findRecipe(dish); //assertion expect(actualRecipe).toEqual(expectedRecipe); });

Remember, when using the async and await keywords, the async keyword is placed before the function that contains asynchronous code. In this case, that would be the callback passed to test(). Then, the await keyword is placed in front of the asynchronous function call findRecipe().

With the inclusion of the async/await keywords, Jest will wait for any await statement to resolve before continuing on.



We will now test the countryListLookup() function again. However now, this function has been altered slightly to simply return a Promise instead of a callback with the fetched data. The provided test() is written in a logical order however it is not set up to handle asynchronous code!

Verify this by running the test command. The test should fail as countryListLookup() will return an empty object.


Now that the false-negative has been identified, rewrite the test using the async/await syntax


Now let’s verify that the test does pass, by running the test command in the terminal!

Take this course for free

Mini Info Outline Icon
By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.

Or sign up using:

Already have an account?