DEV Community

Dimitris Stoikidis
Dimitris Stoikidis

Posted on

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;
}
Enter fullscreen mode Exit fullscreen mode

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);
});
Enter fullscreen mode Exit fullscreen mode

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

import { name, draw, reportArea, reportPerimeter } from './modules/square.js';
Enter fullscreen mode Exit fullscreen mode

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.

// 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);
}

Enter fullscreen mode Exit fullscreen mode

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.
// 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;
}
Enter fullscreen mode Exit fullscreen mode

Mock Basic

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");
});
Enter fullscreen mode Exit fullscreen mode

Mocking injected dependencies

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);
});
Enter fullscreen mode Exit fullscreen mode

Mocking modules

Mock a function with jest.fn

import * as app from "./app";
import * as math from "./math";

math.add = jest.fn();
math.subtract = jest.fn();

test("calls math.add", () => {
  app.doAdd(1, 2);
  expect(math.add).toHaveBeenCalledWith(1, 2);
});

test("calls math.subtract", () => {
  app.doSubtract(1, 2);
  expect(math.subtract).toHaveBeenCalledWith(1, 2);
});
Enter fullscreen mode Exit fullscreen mode

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.

import * as app from "./app";
import * as math from "./math";

// Set all module functions to jest.fn
jest.mock("./math.js");

test("calls math.add", () => {
  app.doAdd(1, 2);
  expect(math.add).toHaveBeenCalledWith(1, 2);
});

test("calls math.subtract", () => {
  app.doSubtract(1, 2);
  expect(math.subtract).toHaveBeenCalledWith(1, 2);
});
Enter fullscreen mode Exit fullscreen mode

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.

import * as app from "./app";
import * as math from "./math";

test("calls math.add", () => {
  const addMock = jest.spyOn(math, "add");

  // calls the original implementation
  expect(app.doAdd(1, 2)).toEqual(3);

  // and the spy stores the calls to add
  expect(addMock).toHaveBeenCalledWith(1, 2);
});
Enter fullscreen mode Exit fullscreen mode

Restore the original implementation

// restore the original implementation
  addMock.mockRestore();
Enter fullscreen mode Exit fullscreen mode

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

setTimeout(function(){ console.log("Hello"); }, 3000);
Enter fullscreen mode Exit fullscreen mode
  • 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
const foo = () => console.log("First");
const bar = () => setTimeout(() => console.log("Second"), 0);
const baz = () => console.log("Third");
Enter fullscreen mode Exit fullscreen mode

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.

test("this shouldn't pass", () => {
  setTimeout(() => {
    // this should fail:
    expect(false).toBe(true);
  });
});
Enter fullscreen mode Exit fullscreen mode

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:

//uppercase.js
function uppercase(str, callback) {
  callback(str.toUpperCase())
}
module.exports = uppercase

//uppercase.test.js
const uppercase = require('./src/uppercase')

test(`uppercase 'test' to equal 'TEST'`, (done) => {
  uppercase('test', (str) => {
    expect(str).toBe('TEST')
    done()
  }
})
Enter fullscreen mode Exit fullscreen mode

Promises

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

//uppercase.js
const uppercase = str => {
  return new Promise((resolve, reject) => {
    if (!str) {
      reject('Empty string')
      return
    }
    resolve(str.toUpperCase())
  })
}
module.exports = uppercase

//uppercase.test.js
const uppercase = require('./uppercase')
test(`uppercase 'test' to equal 'TEST'`, () => {
  return uppercase('test').then(str => {
    expect(str).toBe('TEST')
  })
})
Enter fullscreen mode Exit fullscreen mode

Async/await

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

//uppercase.test.js
const uppercase = require('./uppercase')
test(`uppercase 'test' to equal 'TEST'`, async () => {
  const str = await uppercase('test')
  expect(str).toBe('TEST')
})
Enter fullscreen mode Exit fullscreen mode

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.....
describe('first set', () => {
  beforeEach(() => {
    //do something
  })
  afterAll(() => {
    //do something
  })
  test(/*...*/)
  test(/*...*/)
})

describe('second set', () => {
  beforeEach(() => {
    //do something
  })
  beforeAll(() => {
    //do something
  })
  test(/*...*/)
  test(/*...*/)
})
Enter fullscreen mode Exit fullscreen mode

Links

Top comments (0)

Some comments may only be visible to logged-in visitors. Sign in to view all comments.