Congrats on writing your first unit test! In the last exercise, you used the expect()
assertion function along with the .toEqual()
matcher method. Let’s learn about a few more common matcher methods.
Take a look at the file below where we’ve now added a number of new assertions to test the getIngredients()
method from the recipes
module.
//file: __tests__/recipes.test.js // import the function to test import { getIngredients } from "./recipes.js"; test("Get only the ingredients list for Pesto", () => { //arrange const pestoRecipe = { 'Basil': '2 cups', 'Pine Nuts': '2 tablespoons', 'Garlic': '2 cloves', 'Olive Oil': '0.5 cups', 'Grated Parmesan': '0.5 cups' }; const expectedIngredients = ["Basil", "Pine Nuts", "Garlic", "Olive Oil", "Grated Parmesan"]; //act const actualIngredients = getIngredients(pestoRecipe); //assertions expect(actualIngredients).toBeDefined(); expect(actualIngredients).toEqual(expectedIngredients); expect(actualIngredients.length).toBe(5); expect(actualIngredients[0] === "Basil").toBeTruthy(); expect(actualIngredients).not.toContain("Ice Cream"); });
Let’s go over the matchers used in this example:
.toBeDefined()
is used to verify that a variable is notundefined
. This is often the first thing checked..toEqual()
is used to perform deep equality checks between objects..toBe()
is similar to .toEqual() but is used to compare primitive values..toBeTruthy()
is used to verify whether a value is truthy or not..not
is used before another matcher to verify that the opposite result is true.toContain()
is used when we want to verify that an item is in an array. In this case, since the.not
matcher is used, we are verifying that"Ice Cream"
is NOT in the array.
As mentioned in the previous lesson, there are many different matches. Rather than memorizing all of them, you should consult the complete list in the Jest documentation.
Instructions
Lets put our new-found knowledge to use and write some more tests for our countryExtractor()
function. Based on the provided inputObject
, we expect the first value of the actualValue
array to be "Argentina"
.
Inside the test()
function, write an assertion to validate that the first value of the actualValue
array is "Argentina"
.
Now, directly under the previous assertion, let’s write a test to verify that the actualValue
array contains the string "Belize"
.
Let’s write another assertion that expects the following statement to return true
: actualValue[2] === "Bolivia"
Let’s now write one more final assertion to verify that the actualValue
is an array that only contains 3 items, therefore it should NOT have a value at index 3
.
Directly under the previously written assertion, write an assertion that verifies that actualValue[3]
is NOT defined.
Now that we have set up all of our testing logic we can run the test to verify that everything is running smoothly. Run the test command in the terminal.