Testing Using Jest Table Syntax

Arjun Nayini
Arjun Nayini

1 minute read

When writing tests, especially longer integration tests, sometimes you want to run nearly the same test, but with a few key variables changed. Instead of copying and pasting your integration test into another it block and changing the small details, you can use the .each table syntax provided by Jest:

2  variable1             | variable2
3  ${"mystring"}         | ${true}
4  ${"otherstring"}      | ${false}          
6  "Testing a variety of cases",
7  ({
8    variable1,
9    variable2,
10  }: {
11    variable1: string;
12    variable2: boolean;
13  }) => {
14    // Test content...
15  }

The .each table syntax

allows you to paste in a string that represents the different test cases you want to run. The first row defines the names of variables that will be passed to each run of the test. Each subsequent row represents a test run where the provided values will be bound to the variable names.

In example above, two tests will be run where:

  1. variable1 = "mystring", variable2 = true
  2. variable1 = "otherstring", variable2 = false

This technique can make tests a lot more readable. Note that in the above snippet, you'll have access to the variables in the body of the test content.

In using .each, I've noticed that it is often best when you don't want to change too much of the test logic based on the variables. If your test ends up having a lot of if/else logic based on the variables, especially throughout the entire body of the test, I think it's better to just copy-paste as the additional complexity to read the test isn't worth it.

Share this post

Join the Engineering Newsletter

Receive new articles like this one in your inbox. We aim for quality overย quantity.