Home > Web Front-end > JS Tutorial > Introduction to Jest: Unit Testing, Mocking, and Asynchronous Code

Introduction to Jest: Unit Testing, Mocking, and Asynchronous Code

Linda Hamilton
Release: 2024-11-01 00:23:28
Original
676 people have browsed it

Introduction to Jest: Unit Testing, Mocking, and Asynchronous Code

Introduction to Jest

Jest is a library for testing JavaScript code.

It’s an open source project maintained by Facebook, and it’s especially well suited for React code testing, although not limited to that: it can test any JavaScript code. Its strengths are:

  • it’s fast
  • it can perform snapshot testing
  • it’s opinionated, and provides everything out of the box without requiring you to make choices
export default function sum(a, n) {
  return a + b;
}
Copy after login
Copy after login
Copy after login
Copy after login

divide.test.js

import sum from './sum';

// Describe the test and wrap it in a function.
it('adds 1 + 2 to equal 3', () => {
  const result = sum(1, 2);

  // Jest uses matchers, like pretty much any other JavaScript testing framework.
  // They're designed to be easy to get at a glance;
  // here, you're expecting `result` to be 3.
  expect(result).toBe(3);
});
Copy after login
Copy after login
Copy after login
Copy after login

Matchers

A matcher is a method that lets you test values.

  • toBe compares strict equality, using ===
  • toEqual compares the values of two variables. If it’s an object or array, it checks the equality of all the properties or elements
  • toBeNull is true when passing a null value
  • toBeDefined is true when passing a defined value (opposite to the above)
  • toBeUndefined is true when passing an undefined value
  • toBeCloseTo is used to compare floating values, avoiding rounding errors
  • toBeTruthy true if the value is considered true (like an if does)
  • toBeFalsy true if the value is considered false (like an if does)
  • toBeGreaterThan true if the result of expect() is higher than the argument
  • toBeGreaterThanOrEqual true if the result of expect() is equal to the argument, or higher than the argument
  • toBeLessThan true if the result of expect() is lower than the argument
  • toBeLessThanOrEqual true if the result of expect() is equal to the argument, or lower than the argument
  • toMatch is used to compare strings with regular expression pattern matching
  • toContain is used in arrays, true if the expected array contains the argument in its elements set
  • toHaveLength(number): checks the length of an array
  • toHaveProperty(key, value): checks if an object has a property, and optionally checks its value
  • toThrow checks if a function you pass throws an exception (in general) or a specific exception
  • toBeInstanceOf(): checks if an object is an instance of a class

Dependencies

A dependency is a piece of code that your application depends on. It could be a function/Object in our project or a third-party dependency (ex axios)

A piece of code becomes a true dependency when your own application cannot function without it.

For example, if you implement a feature in your application to send email or make api requests or build a configuration object etc

There are two ways that we can add dependencies in our code in a js project:

Imports

export default function sum(a, n) {
  return a + b;
}
Copy after login
Copy after login
Copy after login
Copy after login

Dependency Injection

Just a fancy term on a simple concept.

If your function needs some functionality from an external dependency, just inject it as an argument.

import sum from './sum';

// Describe the test and wrap it in a function.
it('adds 1 + 2 to equal 3', () => {
  const result = sum(1, 2);

  // Jest uses matchers, like pretty much any other JavaScript testing framework.
  // They're designed to be easy to get at a glance;
  // here, you're expecting `result` to be 3.
  expect(result).toBe(3);
});
Copy after login
Copy after login
Copy after login
Copy after login

Unit Testing

Unit tests are written and run by software developers to ensure that a section of an application (known as the "unit") meets its design and behaves as intended.

We want to test our code in isolation, we don't care about the actual implementation of any dependencies.
We want to verify

  • that our unit of code works as expected
  • returns the expected results
  • calls any collaborators(dependencies) as it should

And that is where mocking our dependencies comes into play.

Mocking

In unit testing, mocks provide us with the capability to stub the functionality provided by a dependency and a means to observe how our code interacts with the dependency.

Mocks are especially useful when it's expensive or impractical to include a dependency directly into our tests, for example, in cases where your code is making HTTP calls to an API or interacting with the database layer.

It is preferable to stub out the responses for these dependencies, while making sure that they are called as required. This is where mocks come in handy.

By using mock functions, we can know the following:

  • The number of calls it received.
  • Argument values used on each invocation.
  • The “context” or this value on each invocation.
  • How the function exited and what values were produced.

Mocking in Jest

There are several ways to create mock functions.

  • The jest.fn method allows us to create a new mock function directly.
  • If you are mocking an object method, you can use jest.spyOn.
  • And if you want to mock a whole module, you can use jest.mock.

The jest.fn method is, by itself, a higher-order function.

It's a factory method that creates new, unused mock functions.

Functions in JavaScript are first-class citizens, they can be passed around as arguments.

Each mock function has some special properties. The mock property is fundamental. This property is an object that has all the mock state information about how the function was invoked. This object contains three array properties:

  • Calls [arguments of each call]
  • Instances ['this' value on each call]
  • Results [the value that the function exited], the results property has type(return or throw) and value
    • The function explicitly returns a value.
    • The function runs to completion with no return statement (which is equivalent to returning undefined
    • The function throws an error.
export default function sum(a, n) {
  return a + b;
}
Copy after login
Copy after login
Copy after login
Copy after login
  • https://codesandbox.io/s/implementing-mock-functions-tkc8b

Mock Basic

import sum from './sum';

// Describe the test and wrap it in a function.
it('adds 1 + 2 to equal 3', () => {
  const result = sum(1, 2);

  // Jest uses matchers, like pretty much any other JavaScript testing framework.
  // They're designed to be easy to get at a glance;
  // here, you're expecting `result` to be 3.
  expect(result).toBe(3);
});
Copy after login
Copy after login
Copy after login
Copy after login

Mocking injected dependencies

import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
Copy after login
Copy after login

Mocking modules

Mock a function with jest.fn

// Constructor Injection

// DatabaseManager class takes a database connector as a dependency
class DatabaseManager {
    constructor(databaseConnector) {
        // Dependency injection of the database connector
        this.databaseConnector = databaseConnector;
    }

    updateRow(rowId, data) {
        // Use the injected database connector to perform the update
        this.databaseConnector.update(rowId, data);
    }
}

// parameter injection, takes a database connector instance in as an argument; easy to test!
function updateRow(rowId, data, databaseConnector) {
    databaseConnector.update(rowId, data);
}

Copy after login
Copy after login

This type of mocking is less common for a couple reasons:

  • jest.mock does this automatically for all functions in a module
  • jest.spyOn does the same thing but allows restoring the original function

Mock a module with jest.mock

A more common approach is to use jest.mock to automatically set all exports of a module to the Mock Function.

// 1. The mock function factory
function fn(impl = () => {}) {
  // 2. The mock function
  const mockFn = function(...args) {
    // 4. Store the arguments used
    mockFn.mock.calls.push(args);
    mockFn.mock.instances.push(this);
    try {
      const value = impl.apply(this, args); // call impl, passing the right this
      mockFn.mock.results.push({ type: 'return', value });
      return value; // return the value
    } catch (value) {
      mockFn.mock.results.push({ type: 'throw', value });
      throw value; // re-throw the error
    }
  }
  // 3. Mock state
  mockFn.mock = { calls: [], instances: [], results: [] };
  return mockFn;
}
Copy after login
Copy after login

Spy or mock a function with jest.spyOn

Sometimes you only want to watch a method be called, but keep the original implementation. Other times you may want to mock the implementation, but restore the original later in the suite.

test("returns undefined by default", () => {
  const mock = jest.fn();

  let result = mock("foo");

  expect(result).toBeUndefined();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledTimes(1);
  expect(mock).toHaveBeenCalledWith("foo");
});
Copy after login
Copy after login

Restore the original implementation

const doAdd = (a, b, callback) => {
  callback(a + b);
};

test("calls callback with arguments added", () => {
  const mockCallback = jest.fn();
  doAdd(1, 2, mockCallback);
  expect(mockCallback).toHaveBeenCalledWith(3);
});
Copy after login
Copy after login

Javascript and the Event Loop

JavaScript is single-threaded: only one task can run at a time. Usually that’s no big deal, but now imagine you’re running a task which takes 30 seconds.. Ya.. During that task we’re waiting for 30 seconds before anything else can happen (JavaScript runs on the browser’s main thread by default, so the entire UI is stuck).
It’s 2020, no one wants a slow, unresponsive website.

Luckily, the browser gives us some features that the JavaScript engine itself doesn’t provide: a Web API. This includes the DOM API, setTimeout, HTTP requests, and so on. This can help us create some async, non-blocking behavior

export default function sum(a, n) {
  return a + b;
}
Copy after login
Copy after login
Copy after login
Copy after login
  • Call Stack - When we invoke a function, it gets added to something called the call stack.
  • WebAPI - setTimeout is provided by the WebAPI, takes a callback function and sets up a timer without blocking the main thread
  • Queue - when the timer finishes, the callback gets added into the Queue
  • Event Loop - checks if the call-stack is empty, checks if there are any callbacks to be executed in the Queue, and moves to the call stack to be executed
import sum from './sum';

// Describe the test and wrap it in a function.
it('adds 1 + 2 to equal 3', () => {
  const result = sum(1, 2);

  // Jest uses matchers, like pretty much any other JavaScript testing framework.
  // They're designed to be easy to get at a glance;
  // here, you're expecting `result` to be 3.
  expect(result).toBe(3);
});
Copy after login
Copy after login
Copy after login
Copy after login

Testing asynchronous code with Jest

Jest typically expects to execute the tests’ functions synchronously.

If we do an asynchronous operation, but we don't let Jest know that it should wait for the test to end, it will give a false positive.

import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
Copy after login
Copy after login

Asynchronous Patterns
There are several patterns for handling async operations in JavaScript; the most used ones are:

  • Callbacks
  • Promises & Async/Await

Testing Callbacks

You can’t have a test in a callback, because Jest won’t execute it - the execution of the test file ends before the callback is called. To fix this, pass a parameter to the test function, which you can conveniently call done. Jest will wait until you call done() before ending that test:

// Constructor Injection

// DatabaseManager class takes a database connector as a dependency
class DatabaseManager {
    constructor(databaseConnector) {
        // Dependency injection of the database connector
        this.databaseConnector = databaseConnector;
    }

    updateRow(rowId, data) {
        // Use the injected database connector to perform the update
        this.databaseConnector.update(rowId, data);
    }
}

// parameter injection, takes a database connector instance in as an argument; easy to test!
function updateRow(rowId, data, databaseConnector) {
    databaseConnector.update(rowId, data);
}

Copy after login
Copy after login

Promises

With functions that return promises, we return a promise from the test:

// 1. The mock function factory
function fn(impl = () => {}) {
  // 2. The mock function
  const mockFn = function(...args) {
    // 4. Store the arguments used
    mockFn.mock.calls.push(args);
    mockFn.mock.instances.push(this);
    try {
      const value = impl.apply(this, args); // call impl, passing the right this
      mockFn.mock.results.push({ type: 'return', value });
      return value; // return the value
    } catch (value) {
      mockFn.mock.results.push({ type: 'throw', value });
      throw value; // re-throw the error
    }
  }
  // 3. Mock state
  mockFn.mock = { calls: [], instances: [], results: [] };
  return mockFn;
}
Copy after login
Copy after login

Async/await

To test functions that return promises we can also use async/await, which makes the syntax very straightforward and simple:

test("returns undefined by default", () => {
  const mock = jest.fn();

  let result = mock("foo");

  expect(result).toBeUndefined();
  expect(mock).toHaveBeenCalled();
  expect(mock).toHaveBeenCalledTimes(1);
  expect(mock).toHaveBeenCalledWith("foo");
});
Copy after login
Copy after login

Tips

  • We need to have a good understanding of what our function does and what we are about to test
  • Think about the behaviour of the code that we are testing
  • Set the stage:
    • Mock/Spy on any dependencies
    • Is our code interacting with global objects? we can mock/spy on them too
    • Are our tests interacting with the DOM? we can build some fake elements to work with
    • Structure your tests
    • Given ...
    • When I call ....
    • Then ... I expect.....
const doAdd = (a, b, callback) => {
  callback(a + b);
};

test("calls callback with arguments added", () => {
  const mockCallback = jest.fn();
  doAdd(1, 2, mockCallback);
  expect(mockCallback).toHaveBeenCalledWith(3);
});
Copy after login
Copy after login

Links

  • https://medium.com/@rickhanlonii/understanding-jest-mocks-f0046c68e53c
  • https://jestjs.io/docs/en/mock-functions
  • https://codesandbox.io/s/implementing-mock-functions-tkc8b
  • https://github.com/BulbEnergy/jest-mock-examples
  • https://dev.to/lydiahallie/javascript-visualized-event-loop-3dif
  • https://jestjs.io/docs/en/asynchronous
  • https://www.pluralsight.com/guides/test-asynchronous-code-jest

The above is the detailed content of Introduction to Jest: Unit Testing, Mocking, and Asynchronous Code. For more information, please follow other related articles on the PHP Chinese website!

source:dev.to
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template