In part 1 we looked at setting up our environment for unit testing, here we will look at some simple unit tests.

Basic Test Structure

Within any unit test you have 3 steps or stages, these are:

  • Arrange
  • Act
  • Assert

I’ve summarised these sections as I understand them below, but bear in mind, I’m just very good at pretending I know what I’m doing!

Arrange

This is the section where we set everything up for the test, but don’t execute the test (yet) – this can be something as simple as initialising the System Under Test (SUT), and creating expected outputs, to creating mocks (more on this later).

Act

In this section we carry out the action we are testing – we are only testing an individual unit1 so this should be fairly simple (i.e. one or two lines to call the function we are testing)

Assert

Finally, we make sure the result is what we expect. It really is that simple.

Example

It’s better to give an example, let’s test the function below:

export function add(num1, num2) {
    return num1 + num2;
}

Obviously, there are no real error checks to make sure the correct parameter types are passed in, but this is supposed to be a simple example

The test would be set up as follows:

import {describe, it, expect} from '@jest/globals';
//We assume the above code is saved in a file called add.js
import { add } from './add.js';

// We want to describe what unit we're testing here
// this is purely so us humans know what's going on
// when we use multiple tests in our test suite
describe('addition test', () => {
  // As well as providing a name for the test
  it('Should equal 3 when 1 and 2 are given as parameters',
    () => {
      // Arrange
      const expected = 3; // The result we expect
      // Act
      const result = add(1, 2);
      // Assert
      expect(result).toEqual(3);
    });
});

Obviously, this is a very contrived example, but it gets the basics “in the bag” as it were.

In the next part, we’ll look at some more interesting features, like spying on object methods and properties, and maybe mocking (although that may be for another part).

As always, feel free to comment, question, or just let me know your thoughts on this post, or any other.

  1. A unit is a single part or aspect of the application ↩︎

One response to “Unit testing? Surely you Jest! – Part 2”

  1. […] Now that we’ve set up our project, and as this is quite a long process, I’ll continue in part 2. […]

    Like