So we covered the basics of setting Jest up in a Javascript project and testing some basic functions.

Now let’s have a look at expanding our knowledge by testing more matchers.

Matchers are fantastic, they essentially help translate your code into bitesize, readable, english words / sentences. For example the matcher ‘toBe.’ Does exactly what it says, it compares values or checks the identity of object instances. Essentially it is better than using the strict equality operator ‘===’ during testing.

For a full list of matchers follow this link.


In the previous blog, I looked briefly at .toBe, .toEqual, .not. So, I am going to move on to some slightly different ones for this blog and next week will be testing async functions.

Let’s say we have written a function that is expected to add a new student to an array.

Image for post

Here we have a basic function, a basic student array and then I am calling the function at the bottom. So I want to test that an item with a specific structure and values is contained within the students array after calling the function! Aka. does Isak’s object get added to the students array.

Perfect, there’s a matcher for this. It’s called .toContainEqual.

So firstly, we need to set up our basic test block.

Image for post

note array and new student object are purely there to represent what will be added in.

  • Line 2 is using the inbuilt method test and has a callback function and a string that is used to primarily describe what you are testing. In this case, does the students array contain the newly added student.
  • Line 3 is using the expect method which will look at the array and see if it contains the new student object.

Now that we have written our test block with some pseudocode, let’s start building out the function in our test.

Image for post

Firstly, I need to import the method we have written from the correct Javascript file. So this line of code is essentially saying import the function, addName from the Javascript file called ‘main’. You will also need to export the function from the main file.

#javascript #software-testing #jest #javascript-testing #testing

Jest — Advancing the Basics
1.35 GEEK