Introduction to Jest: Unit Testing, Mocking, and Asynchronous Code
Nov 01, 2024 am 12:23 AMIntroduction 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; }
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); });
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; }
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); });
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; }
- 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); });
Mocking injected dependencies
import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
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); }
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; }
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"); });
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); });
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; }
- 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); });
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';
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); }
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; }
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"); });
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); });
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!

Hot AI Tools

Undress AI Tool
Undress images for free

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

JavaScript's garbage collection mechanism automatically manages memory through a tag-clearing algorithm to reduce the risk of memory leakage. The engine traverses and marks the active object from the root object, and unmarked is treated as garbage and cleared. For example, when the object is no longer referenced (such as setting the variable to null), it will be released in the next round of recycling. Common causes of memory leaks include: ① Uncleared timers or event listeners; ② References to external variables in closures; ③ Global variables continue to hold a large amount of data. The V8 engine optimizes recycling efficiency through strategies such as generational recycling, incremental marking, parallel/concurrent recycling, and reduces the main thread blocking time. During development, unnecessary global references should be avoided and object associations should be promptly decorated to improve performance and stability.

There are three common ways to initiate HTTP requests in Node.js: use built-in modules, axios, and node-fetch. 1. Use the built-in http/https module without dependencies, which is suitable for basic scenarios, but requires manual processing of data stitching and error monitoring, such as using https.get() to obtain data or send POST requests through .write(); 2.axios is a third-party library based on Promise. It has concise syntax and powerful functions, supports async/await, automatic JSON conversion, interceptor, etc. It is recommended to simplify asynchronous request operations; 3.node-fetch provides a style similar to browser fetch, based on Promise and simple syntax

JavaScript data types are divided into primitive types and reference types. Primitive types include string, number, boolean, null, undefined, and symbol. The values are immutable and copies are copied when assigning values, so they do not affect each other; reference types such as objects, arrays and functions store memory addresses, and variables pointing to the same object will affect each other. Typeof and instanceof can be used to determine types, but pay attention to the historical issues of typeofnull. Understanding these two types of differences can help write more stable and reliable code.

Hello, JavaScript developers! Welcome to this week's JavaScript news! This week we will focus on: Oracle's trademark dispute with Deno, new JavaScript time objects are supported by browsers, Google Chrome updates, and some powerful developer tools. Let's get started! Oracle's trademark dispute with Deno Oracle's attempt to register a "JavaScript" trademark has caused controversy. Ryan Dahl, the creator of Node.js and Deno, has filed a petition to cancel the trademark, and he believes that JavaScript is an open standard and should not be used by Oracle

Which JavaScript framework is the best choice? The answer is to choose the most suitable one according to your needs. 1.React is flexible and free, suitable for medium and large projects that require high customization and team architecture capabilities; 2. Angular provides complete solutions, suitable for enterprise-level applications and long-term maintenance; 3. Vue is easy to use, suitable for small and medium-sized projects or rapid development. In addition, whether there is an existing technology stack, team size, project life cycle and whether SSR is needed are also important factors in choosing a framework. In short, there is no absolutely the best framework, the best choice is the one that suits your needs.

IIFE (ImmediatelyInvokedFunctionExpression) is a function expression executed immediately after definition, used to isolate variables and avoid contaminating global scope. It is called by wrapping the function in parentheses to make it an expression and a pair of brackets immediately followed by it, such as (function(){/code/})();. Its core uses include: 1. Avoid variable conflicts and prevent duplication of naming between multiple scripts; 2. Create a private scope to make the internal variables invisible; 3. Modular code to facilitate initialization without exposing too many variables. Common writing methods include versions passed with parameters and versions of ES6 arrow function, but note that expressions and ties must be used.

Promise is the core mechanism for handling asynchronous operations in JavaScript. Understanding chain calls, error handling and combiners is the key to mastering their applications. 1. The chain call returns a new Promise through .then() to realize asynchronous process concatenation. Each .then() receives the previous result and can return a value or a Promise; 2. Error handling should use .catch() to catch exceptions to avoid silent failures, and can return the default value in catch to continue the process; 3. Combinators such as Promise.all() (successfully successful only after all success), Promise.race() (the first completion is returned) and Promise.allSettled() (waiting for all completions)

CacheAPI is a tool provided by the browser to cache network requests, which is often used in conjunction with ServiceWorker to improve website performance and offline experience. 1. It allows developers to manually store resources such as scripts, style sheets, pictures, etc.; 2. It can match cache responses according to requests; 3. It supports deleting specific caches or clearing the entire cache; 4. It can implement cache priority or network priority strategies through ServiceWorker listening to fetch events; 5. It is often used for offline support, speed up repeated access speed, preloading key resources and background update content; 6. When using it, you need to pay attention to cache version control, storage restrictions and the difference from HTTP caching mechanism.
