Subscribe

Jest and recurring actions

✍️

How to set up recurring actions for each test in Jest

4 Apr, 2022 · 2 min read

Sometimes you want to have Jest perform a recurring action between each task.

Some examples: Query a database, clear storage, clear mocked data, or reset a mocked route.

We don’t really want to be bothered with having this recurring code in each test, and luckily Jest has a solution for us.

Recurring actions

There are four functions we can hook into:

  • beforeEach: Runs before each test
  • afterEach: Runs after each test
  • beforeAll: Runs before all tests
  • afterAll: Runs after all tests

Let’s sketch an example. We have a database function to call, so the steps we want to achieve are:

  • create database
  • populate with mock data
  • re-populate for each test
  • remove database

This scenario is a perfect case for all four functions to hook into.

The first thing we want is to create our database, for which we’ll use the beforeAll function.

beforeAll(() => {
  return createDatabase();
});

The next step is to populate the database with demo data we can alter in our tests.

beforeEach(() => {
  return populateDatabase();
});

Our test might alter/remove/create elements in this database, so we want to clear it between each test.

afterEach(() => {
  return clearDatabase();
});

And once we are all done, we should remove the database so the next run will be fresh again.

afterAll(() => {
  return removeDatabase();
});

And that’s it, these four steps will now run at the needed times. To showcase this, let’s create this sample test file and see when each call is used.

test('user database has Chris', () => {
  expect(db.user.hasName('Chris')).toBeTruthy();
});

test('user database doesnt have Thomas', () => {
  expect(db.user.hasName('Thomas')).not.toBeTruthy();
});

The firing order is as follows:

  • beforeAll: Created the database
  • beforeEach: Populates database
  • Test 1 runs: Find user Chris
  • afterEach: Clear database
  • beforeEach: Populates database
  • Test 2 runs: Can’t find Thomas
  • afterEach: Clear database
  • afterAll: Remove database

And that’s the flow it will take.

We can quickly make our test more manageable and work in specific ways to ensure each test is solid and fresh.

Thank you for reading, and let’s connect!

Thank you for reading my blog. Feel free to subscribe to my email newsletter and connect on Facebook or Twitter

Spread the knowledge with fellow developers on Twitter
Tweet this tip
Powered by Webmentions - Learn more

Read next 📖

Testing library asFragment tests

18 Apr, 2022 · 2 min read

Testing library asFragment tests

Changing the default testing container

17 Apr, 2022 · 3 min read

Changing the default testing container

Join 2099 devs and subscribe to my newsletter