Back to Blog

MERN Jest Testing (Part 4)

Sayed Farid Qattali

Jest Assertion

An assertion is a boolean expression. It is used to test a logical expression. An assertion is true if the logical expression that is being tested is true, otherwise, it is false. In assertion, we need to check that values meet certain conditions. Assertions decide if a test passes or fails. Hence, assertions are a crucial part of writing tests.

Assertions in jest are carried out with the global expect method of Jest.

expect(value): accepts a value as its argument. The argument should be the value that our code produces.

In Jest, a matcher function is used with expect to assert something about a value. A matcher can optionally accept an argument which is the correct expected value. There are different type of matcher functions in Jest, which are discussed in a separate section.

In the two below examples, we have written simple tests not related to the repo for illustration purposes. You will encounter many examples of assertion in Jest, in the following sections.

Example 1

In the following example, we are going to write a test that checks if 1+2 is equal to 3:

it("should check if 1+2 is equal to 3", () => {

In the above snippet, expect(1+2).toEqaul(3) is the assertion which is consist of two parts:

  1. expect(1+2) which is expect method and its argument is what we want to be tested and
  2. toEqual(3) which is the matcher function checking for equality and its argument is our expected outcome. Now because 1+2 is equal to 3 and our test purpose was to assert this, the test passes.

Example 2

In the following example, we are going to write a test that checks an object has our desired attributes:

it("should check if user object has firstname, lastname, and email", () => {
	const user = {
		firstname: "John",
		lastname: "Doe",
		email: ""



In the above snippet, we have write 3 assertions within our test block checking if the user object firstname, lastname, and email attributes are defined. We have used toBeDefined matcher function which accepts no argument for checking if an attribute is defined or not. Now because the user object has all the 3 attributes, this test passes successfully.

You can write any number of assertions within the it block for checking different values.

Share on social media: