Jest - Core Concepts



In this chapter, we'll cover the core concepts of Jest, a popular JavaScript testing framework. You'll learn how to use Jest's matchers and functions to test different data types, making sure your code behaves as expected.

Core Concepts of Jest

Jest Matchers

Matchers in Jest are functions that help you verify if your test values meet certain conditions. They are used with the expect() function to make assertions and ensure your code behaves as expected.

Types of Matchers

Below are the main types of matchers in Jest:

Equality Matchers

Equality matchers help you check if two values are equal in different ways.

  • .toBe(): This checks if two values are strictly equal (using ===). It's mainly used for comparing primitive values like numbers, strings, or booleans.
test('checks if values are strictly equal', () => {
    
    // Passes, because 5 === 5
    expect(5).toBe(5);    
    
    // Passes, because both strings are exactly the same
    expect('Hello').toBe('Hello'); 
});
  • .toEqual(): This compares objects or arrays to see if all their properties or elements are equal, even if they're nested.
  • test('checks if objects and arrays are deeply equal', () => {
        
        // Passes, because both objects are identical
        expect({ name: 'Alice' }).toEqual({ name: 'Alice' });  
        
        // Passes, because arrays have the same elements
        expect([1, 2, 3]).toEqual([1, 2, 3]);  
    });

    Truthiness Matchers

    Truthiness matchers help you check whether a value is truthy or falsy.

    • .toBeTruthy(): This checks if a value is truthy, meaning it evaluates to true in a Boolean context. For example, non-empty strings and non-zero numbers are truthy.
    test('checks if value is truthy', () => {
        
        // Passes, because non-empty strings are truthy
        expect('Hello').toBeTruthy();  
        
        // Passes, because 1 is truthy
        expect(1).toBeTruthy();         
    });
  • .toBeFalsy(): This checks if a value is falsy. Falsy values include false, 0, null, undefined, and empty strings.
  • test('checks if value is falsy', () => {
        
        // Passes, because 0 is falsy
        expect(0).toBeFalsy();     
        
        // Passes, because an empty string is falsy     
        expect('').toBeFalsy();         
    });
  • .toBeNull(): This checks if a value is exactly null.
  • test('checks if value is undefined', () => {
        let value;
        
        // Passes, because value is undefined
        expect(value).toBeUndefined();  
    });
  • .toBeUndefined(): This checks if a value is exactly undefined.
  • test('checks if value is undefined', () => {
        let value;
        
        // Passes, because value is undefined
        expect(value).toBeUndefined();  
    });
  • .toBeDefined(): This checks if a value is not undefined.
  • test('checks if value is defined', () => {
        const value = 10;
        
        // Passes, because value is defined (it is 10)
        expect(value).toBeDefined();    
    });

    Comparison Matchers

    Comparison matchers check if one value is greater than, less than, or equal to another.

    • .toBeGreaterThan(): Verifies if one value is greater than another.
    test('checks if a number is greater than another', () => {
        
        // Passes, because 10 is greater than 5
        expect(10).toBeGreaterThan(5);  
    });
  • .toBeLessThan(): Verifies if one value is smaller than another.
  • test('checks if a number is less than another', () => {
        
        // Passes, because 3 is less than 5
        expect(3).toBeLessThan(5);      
    });
  • .toBeGreaterThanOrEqual(): Verifies if one value is greater than or equal to another.
  • test('checks if a number is greater than or equal to another', () => {
        
        // Passes, because 10 is equal to 10
        expect(10).toBeGreaterThanOrEqual(10);  
        
        // Passes, because 15 is greater than 10
        expect(15).toBeGreaterThanOrEqual(10);  
    });
  • .toBeLessThanOrEqual(): Verifies if one value is smaller than or equal to another.
  • test('checks if a number is less than or equal to another', () => {
        
        // Passes, because 3 is less than 5
        expect(3).toBeLessThanOrEqual(5);   
        
        // Passes, because 5 is equal to 5
        expect(5).toBeLessThanOrEqual(5);   
    });
  • .toBeNull(): Checks if a value is exactly null.
  • test('checks if value is null', () => {
        const value = null;
        
        // Passes, because value is exactly null
        expect(value).toBeNull();       
    });

    Array Matchers

    Array matchers check if an array contains specific elements or matches conditions.

    • .toContain(): Checks if an array contains a specific element.
    test('checks if an array contains a specific element', () => {
    
        // Passes, because 2 is in the array
        expect([1, 2, 3]).toContain(2);  
        
        // Passes, because 'banana' is in the array
        expect(['apple', 'banana']).toContain('banana');  
    });
  • .toContainEqual(): Checks if an array contains an object with the same values as another.
  • test('checks if an array contains an object with equal values', () => {
        const users = [{ name: 'John' }, { name: 'Jane' }];
        
        // Passes, because an object with name 'John' exists in the array
        expect(users).toContainEqual({ name: 'John' }); 
    });

    Function Matchers

    Function matchers check the behavior of functions, particularly if they throw errors.

    • .toThrow(): Checks if a function throws any error when called.
    test('checks if function throws an error', () => {
        const throwError = () => { throw new Error('Oops!'); };
        
        // Passes, because the function throws an error
        expect(throwError).toThrow();    
    });
  • .toThrowError(): Checks if a function throws a specific error message.
  • test('checks if function throws a specific error', () => {
        const throwError = () => { throw new Error('Specific error'); };
        
        // Passes, because the error message matches
        expect(throwError).toThrowError('Specific error');  
    });

    Jest Expect Functions

    The expect() function in Jest is used to create assertions within your tests. It's the foundation of every test, allowing you to compare the actual result of your code against an expected value.

    Syntax

    expect(actualValue).matcher(expectedValue)

    How expect() Works?

    • actualValue: The actual value or output you want to test.
    • matcher: A method like .toBe(), .toEqual(), or .toContain() that checks your condition.
    • expectedValue: The value you expect to get from your code.

    Example

    const result = 5 + 5;
    
    // Passes because 5 + 5 equals 10
    expect(result).toBe(10);

    Explanation

    • expect(result): Creates an expectation for the result value.
    • .toBe(10): Checks if result is strictly equal to 10. If it is, the test passes.

    This is the basic structure of how Jest's expect() function is used to test your code.

    Jest Testing Primitives

    In Jest, testing primitive values such as numbers, strings, and booleans is simple. You can use matchers like .toBe() to check if these primitive values match the expected results.

    Testing Numbers

    For testing numbers, you can use the .toBe() matcher to check if the value is exactly equal to what you expect.

    Example: To verify the sum of two numbers.

    // Passes because 10 + 5 equals 15
    expect(10 + 5).toBe(15);

    Testing Strings

    Strings are also tested using the .toBe() matcher to check for exact matches.

    Example: To check if two strings are identical

    // Passes because the strings are exactly the same
    expect('hello').toBe('hello');  
    

    Testing Booleans

    Booleans can be tested to check whether they are truthy or falsy.

    • .toBeTruthy(): is used to check if a value is truthy (i.e., evaluates to true).
    • .toBeFalsy(): is used to check if a value is falsy (i.e., evaluates to false).

    Example

    // Passes because true is truthy
    expect(true).toBeTruthy(); 
    
    // Passes because false is falsy
    expect(false).toBeFalsy();

    Jest Testing Objects

    When testing objects in Jest, it's important to check that their properties match the expected values. You can use different matchers depending on the level of comparison.

    Deep Equality

    Here, .toEqual() verifies that the user object has the exact same properties and values as the expected object.

    • .toEqual(): Use .toEqual() to check if two objects or arrays are exactly the same, including all properties and values.
    const user = { name: 'Alice', age: 25 };
    expect(user).toEqual({ name: 'Alice', age: 25 });  // Passes

    Partial Matching

    In this case, .toMatchObject() checks that the user object contains the name property with the value 'Alice', but it doesn't require the full object to match.

    • .toMatchObject(): Use .toMatchObject() to check if an object contains specific properties, without needing to match the entire object.
    expect(user).toMatchObject({ name: 'Alice' });  // Passes

    Property Matching

    Here, .toHaveProperty() checks that the user object contains the name property and also verifies that the age property has the value 25.

    • .toHaveProperty(): Use .toHaveProperty() to check if an object has a specific property, and optionally check its value.
    expect(user).toHaveProperty('name');  // Passes
    expect(user).toHaveProperty('age', 25);  // Passes

    Jest Testing Arrays

    In Jest, you can test arrays using matchers like .toContain(), .toHaveLength(), and .toEqual() to verify their contents and properties.

    Checking if an Array Contains a Value

    To test if an array contains a specific element, use .toContain() method.

    const numbers = [1, 2, 3, 4];
    
    // Passes because the array contains 3
    expect(numbers).toContain(3); 

    Checking the Length of an Array

    You can verify the number of elements in an array using .toHaveLength() method.

    // Passes because the array has 4 elements
    expect(numbers).toHaveLength(4);

    Checking Array Equality

    To check if two arrays are exactly equal (i.e., have the same elements in the same order), use .toEqual() method.

    // Passes because the arrays are equal   
    expect([1, 2, 3]).toEqual([1, 2, 3]);
    Advertisements