Learn

Now that Jest is installed and configured it is time to set up our first unit test. A unit test is designed to test the smallest unit of your code, like a single function.

Let’s consider testing some functions from a module called recipes.js. This module has two functions we’d like to test:

  • findRecipe() takes a name of a recipe and makes an API call to find the specified recipe. When the request resolves, the provided callback is executed with the fetched data. The data will be an object containing ingredients and their quantities for the recipe.
  • getIngredients() converts an object retrieved using findRecipe() into an array of just the ingredients.

Below, we can see an example of how these functions might be used (the actual implementation of them isn’t important):

import { findRecipe, getIngredients } from './recipes.js'; findRecipe('pesto', (recipe) => { console.log(recipe); /* Prints { 'Basil': '2 cups', 'Pine Nuts': '2 tablespoons', 'Garlic': '2 cloves', 'Olive Oil': '0.5 cups', 'Grated Parmesan': '0.5 cups' } */ console.log(getIngredients(recipe)); // Prints ["Basil", "Pine Nuts", "Garlic", "Olive Oil", "Grated Parmesan"] });

When unit testing, each function should be tested in isolation. In Jest, we do this by creating separate containers for our testing logic using the test() function.

The test() function takes three arguments:

  1. A string describing what is being tested
  2. A callback function containing assertions and other testing logic
  3. An optional timeout in milliseconds that specifies how long a test should wait before automatically aborting. If unspecified, this defaults to 5000 ms.

If we wanted to test the functions from the recipes module, we could use the test() function to create containers for each, like so:

//file: __tests__/recipes.test.js // import the functions to test import { findRecipe, getIngredients } from "./recipes.js"; test("Get the full recipe for Pesto", async () => { // testing logic for findRecipe() omitted... }, 10000); test("Get only the ingredients list for Pesto", () => { // testing logic for getIngredients() omitted... });

Let’s look at the tests in this example.

  • With the first argument of test(), we state the purpose of the test - to get the recipe for Pesto. This string shouldn’t explain the implementation of the function being tested, only the desired result.
  • A callback function is passed as the second argument to test(). Inside is where we will write our testing logic (we will cover this soon in more detail in the next exercise). Since the function being tested makes an asynchronous API call, this callback is marked as async (again, we’ll come back to this).
  • Lastly, with the third argument, we specify that we want to see if this operation can be carried out in under 10000ms (10 seconds) since making the API call may take some time.
  • The second test() follows the same pattern, however, the function being tested is not asynchronous so the async keyword is omitted from the callback function. Also, by leaving out the third argument, we are using the default 5000ms timeout.

Each time we create a new test() function call, we create a separate entry in our testing output when we run npm test. Running the npm test command for the example above would produce this output:

Jest test output

Now it’s your turn to try!

Instructions

1.

Since we will now begin writing tests for languageSpoken object, you will notice that its methods have been imported to the language_spoken.test.js file. We will begin by testing the countryExtractor() function.

First, call the test() function. For now, you can call the function without any arguments.

2.

Next, we’ll add a description. The countryExtractor() function is designed to take an array of country objects containing their name, capital, etc…, and convert it to an array of just the country names. For example:

const countriesAllData = [ {name: "Argentina", capital: "Buenos Aires"}, {name: "Belize", capital: "Belmopan"}, {name: "Bolivia", capital: "Sucre"} ] const countryNames = countryExtractor(countriesAllData) console.log(countryNames); // Prints ["Argentina","Belize","Bolivia"]

In the test() function call you just made, describe the test by passing in a string as the first argument. Check out the hint for an optional suggestion!

3.

Next, we’ll need a place to put our testing logic. Pass an empty (for now) arrow function as the second argument to test().

In the next exercise we will fill in this callback function.

4.

For the third and final parameter, let’s force Jest to use the default timeout.

5.

Now run the npm test command in your terminal. At this point, you should see a successful test output. Since the test contains no errors or failed assertions, it passes!

Take this course for free

By signing up for Codecademy, you agree to Codecademy's Terms of Service & Privacy Policy.
Already have an account?