Dynamically generate test cases with Jest
As long as you know which cases you want to test up-front (for example, you're not trying to generate them after a network request) you can use Jest to batch out multiple cases at once.
The syntax looks like this
test.each([])("test name", () => {})
Single argument per test
If you use the wildcard %s
in your test name, it will inject the first string in your test case. The following test spec will generate five different tests.
1test.each([2 'FULL_TIME',3 'PART_TIME',4 'SELF_EMPLOYED',5 'UNEMPLOYED',6 'RETIRED',7])('can set employment type to %s', (type) => {89 // Test content here10}),11
1test("can set employment type to FULL_TIME", () => {2 const type = "FULL_TIME"34 // Test content here5})67test("can set employment type to PART_TIME", () => {8 const type = "PART_TIME"910 // Test content here11})1213test("can set employment type to SELF_EMPLOYED", () => {14 const type = "SELF_EMPLOYED"1516 // Test content here17})1819test("can set employment type to UNEMPLOYED", () => {20 const type = "UNEMPLOYED"2122 // Test content here23})2425test("can set employment type to RETIRED", () => {26 const type = "RETIRED"2728 // Test content here29})30
Multiple arguments per test
Each item in the array can itself be an array of arguments.
In the test name, you can use %s multiple times in order to print out the argument.
1test.each([2 ['FULL_TIME', 'FULL_TIME'],3 ['FULL_TIME', 'PART_TIME'],4 ['FULL_TIME', 'SELF_EMPLOYED'],5 ['FULL_TIME', 'UNEMPLOYED'],6 ['FULL_TIME', 'RETIRED'],7 ['PART_TIME', 'FULL_TIME'],8 ['PART_TIME', 'PART_TIME'],9 ['PART_TIME', 'SELF_EMPLOYED'],10 ['PART_TIME', 'UNEMPLOYED'],11 ['PART_TIME', 'RETIRED'],12 ['SELF_EMPLOYED', 'FULL_TIME'],13 ['SELF_EMPLOYED', 'PART_TIME'],14 ['SELF_EMPLOYED', 'SELF_EMPLOYED'],15 ['SELF_EMPLOYED', 'UNEMPLOYED'],16 ['SELF_EMPLOYED', 'RETIRED'],17 ['UNEMPLOYED', 'FULL_TIME'],18 ['UNEMPLOYED', 'PART_TIME'],19 ['UNEMPLOYED', 'SELF_EMPLOYED'],20 ['UNEMPLOYED', 'UNEMPLOYED'],21 ['UNEMPLOYED', 'RETIRED'],22 ['RETIRED', 'FULL_TIME'],23 ['RETIRED', 'PART_TIME'],24 ['RETIRED', 'SELF_EMPLOYED'],25 ['RETIRED', 'UNEMPLOYED'],26 ['RETIRED', 'RETIRED'],27])('can set employment type from %s to %s', ([ firstType, secondType ]) => {2829 // Test content here30}),31
1test("can set employment type from FULL_TIME to FULL_TIME", () => {2 const firstType = "FULL_TIME"3 const secondType = "FULL_TIME"45 // Test content here6})78test("can set employment type from FULL_TIME to PART_TIME", () => {9 const firstType = "FULL_TIME"10 const secondType = "PART_TIME"1112 // Test content here13})1415test("can set employment type from FULL_TIME to SELF_EMPLOYED", () => {16 const firstType = "FULL_TIME"17 const secondType = "SELF_EMPLOYED"1819 // Test content here20})2122// …and so on 22 more times23