Testing Using Jest Table Syntax
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:
1describe.each`
2 variable1 | variable2
3 ${"mystring"} | ${true}
4 ${"otherstring"} | ${false}
5`(
6 "Testing a variety of cases",
7 ({
8 variable1,
9 variable2,
10 }: {
11 variable1: string;
12 variable2: boolean;
13 }) => {
14 // Test content...
15 }
16)
The .each
table syntax
In example above, two tests will be run where:
variable1 = "mystring", variable2 = true
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.
You can also define the table as an array of arrays or array of dictionaries.