Jest 19 ๐ Parameterized Tests โ test.each and the %$ placeholder in v30
Writing repetitive test blocks for variations of the same underlying logic creates maintenance bottlenecks, redundant code, and bloated test suites. Parameterized testing solves this duplication by allowing developers to define a single test specification executed across a matrix of input data and expected outputs. Jest provides native parameterized support through the test.each and describe.each APIs, accepting either nested arrays or Spock-style tagged template literals.
In Jest 30, parameterized testing receives major enhancements, including the introduction of the %$ printf formatting placeholder. While %# provides a zero-based index for identifying test iterations, %$ outputs a human-readable, one-based test case number. This chapter explores array-based tables, tagged template literals, formatting tokens, and the v30 %$ test-numbering mechanism.
Key point: Jest’s test.each enables data-driven test execution over arrays or tagged template literals, while Jest 30 introduces the %$ placeholder to inject 1-based test case numbers directly into test titles for precise reporting.
Why X exists
The test duplication problem.
Writing separate test functions for every input permutation creates thousands of lines of boilerplate code that are tedious to refactor when requirements change.
The copy-paste error trap.
Duplicating test blocks frequently leads to copy-paste mistakes where assertions or input parameters are forgotten or misconfigured across similar test cases.
The test readability deficit.
Cluttering test files with twenty near-identical it blocks obscures the core business logic being verified under test.
The reporting ambiguity challenge.
Standard parameterized loops (forEach) lump failures into a single generic test block, making it difficult to isolate which specific data set caused a test regression.
The 1-based indexing gap.
Legacy zero-based index tokens (%#) often confuse non-technical stakeholders reading test reports who expect test case numbers to start at one rather than zero.
a. Array Tables and Positional Formatting Tokens
Jest allows developers to supply parameterized data as an array of arrays, where each inner array represents a single row of arguments passed into the test callback. To distinguish test iterations in test runners and logs, Jest supports printf-style formatting tokens embedded within the test title string.
TypeScript
import { describe, expect, test } from '@jest/globals';
const taxTestCases = [
['Standard', 100, 20, 120],
['Reduced', 100, 5, 105],
['Zero', 100, 0, 100],
];
describe('Tax Calculation Suite', () => {
test.each(taxTestCases)(
'calculates total for %s tier with base %d and rate %d',
(tier, base, rate, expected) => {
// Perform calculation using row arguments
const result = base + (base * rate) / 100;
expect(result).toBe(expected);
}
);
});
The %s token formats string arguments, while %d formats numeric values. When Jest executes this block, it generates three distinct test titles dynamically, replacing the placeholders with the actual primitive values from each row. If any case fails, the test runner identifies the exact row parameters responsible for the failure.
b. Spock-Style Tagged Template Literals
When test matrices grow complex or involve numerous parameters, nested arrays can become difficult to read. Jest provides tagged template literals as an alternative syntax inspired by Spock framework data tables. A template string header defines column names separated by pipe symbols (|), followed by rows of expressions using ${} syntax.
TypeScript
import { describe, expect, test } from '@jest/globals';
describe('String Sanitization Tagged Tables', () => {
test.each`
input | expected
${' hello '} | ${'hello'}
${'WORLD! '} | ${'WORLD!'}
${' foo bar '} | ${'foo bar'}
`('sanitizes input "$input" to "$expected"', ({ input, expected }) => {
// Apply trimming transformation on injected property object
const sanitized = input.trim();
expect(sanitized).toBe(expected);
});
});
Using tagged template literals automatically maps each row into an object whose keys correspond to the column header names. This approach eliminates positional argument mismatch errors and allows developers to reorder columns safely without rewriting parameter signatures in the test callback.
c. Jest 30 Enhancements and the %$ Test Case Number Placeholder
Prior to Jest 30, tracking specific test rows relied on %#, which evaluated to a zero-based index (0, 1, 2). While functional, zero-based indices often required mental offset calculations during debugging. Jest 30 introduces the %$ placeholder token, which injects a human-friendly, one-based test case number (1, 2, 3) directly into test titles.
TypeScript
import { describe, expect, test } from '@jest/globals';
const payloadScenarios = [
{ payload: { type: 'admin', quota: 100 }, valid: true },
{ payload: { type: 'guest', quota: -1 }, valid: false },
{ payload: { type: 'system', quota: 0 }, valid: true },
];
describe('Payload Validation Suite (Jest 30)', () => {
test.each(payloadScenarios)(
'TestCase %$ validates payload type $payload.type correctly',
({ payload, valid }) => {
// Evaluate quota constraint validity
const isValid = payload.quota >= 0;
expect(isValid).toBe(valid);
}
);
});
The %$ token integrates seamlessly with object property path traversal (such as $payload.type). When the test suite runs, Jest outputs explicit titles like TestCase 1 validates payload type admin correctly, providing immediate clarity on test iteration order and data binding.
Complete Example Session
TypeScript
// ============================================
// PART 1: MODULE IMPORT SETUP
// ============================================
import { describe, expect, test } from '@jest/globals';
TypeScript
// ============================================
// PART 2: CORE UTILITY FUNCTION UNDER TEST
// ============================================
export function calculateShippingCost(weightKg: number, isExpress: boolean): number {
if (weightKg <= 0) throw new Error('Invalid weight');
const baseRate = weightKg * 5;
return isExpress ? baseRate + 15 : baseRate;
}
TypeScript
// ============================================
// PART 3: ARRAY-BASED TEST MATRIX DATA
// ============================================
const standardShippingMatrix = [
[2, false, 25],
[2, true, 40],
[10, false, 65],
];
TypeScript
// ============================================
// PART 4: TAGGED TEMPLATE LITERAL TABLE
// ============================================
const expressShippingTable = `
weight | express | expectedCost
${1} | ${true} | ${20}
${5} | ${true} | ${40}
${10} | ${false}| ${50}
`;
TypeScript
// ============================================
// PART 5: OBJECT ARRAY FOR JEST 30 %$ FORMATTING
// ============================================
const j30Scenarios = [
{ weight: 3, express: false, expected: 30 },
{ weight: 4, express: true, expected: 35 },
];
TypeScript
// ============================================
// PART 6: ARRAY-BASED TEST EXECUTION BLOCK
// ============================================
describe('Standard Shipping Array Suite', () => {
test.each(standardShippingMatrix)(
'calculates weight %d kg (express: %s) to cost %d',
(weight, express, expected) => {
expect(calculateShippingCost(weight as number, express as boolean)).toBe(expected);
}
);
});
TypeScript
// ============================================
// PART 7: TAGGED TEMPLATE TEST EXECUTION BLOCK
// ============================================
describe('Express Shipping Tagged Table Suite', () => {
test.each(expressShippingTable)(
'table calculation for weight $weight yields $expectedCost',
({ weight, express, expectedCost }) => {
expect(calculateShippingCost(weight, express)).toBe(expectedCost);
}
);
});
TypeScript
// ============================================
// PART 8: JEST 30 %$ TEST CASE NUMBERING BLOCK
// ============================================
describe('Jest 30 Placeholder Suite', () => {
test.each(j30Scenarios)(
'TestCase %$ verifies weight $weight cost correctly',
({ weight, express, expected }) => {
expect(calculateShippingCost(weight, express)).toBe(expected);
}
);
});
TypeScript
// ============================================
// PART 9: ERROR BOUNDARY VALIDATION
// ============================================
describe('Shipping Error Validation', () => {
test.each([-1, 0])('throws error for invalid weight %d', (invalidWeight) => {
expect(() => calculateShippingCost(invalidWeight, false)).toThrow('Invalid weight');
});
});
TypeScript
// ============================================
// PART 10: SUITE FINALIZATION
// ============================================
// All test matrices executed successfully across parameterized contexts
This ten-part sequence demonstrates a complete parameterized testing architecture, covering array matrices, Spock tables, Jest 30 %$ index numbering, and error boundary validation.
Quick Reference
Parameterized Formatting Tokens
| Token | Data Type / Meaning | Output Example |
%s | String value | "Standard" |
%d / %i | Number / Integer | 42 |
%f | Floating-point value | 3.14 |
%j | JSON string representation | {"id":1} |
%o | Object formatting | {a: 1} |
%p | Pretty-format output | Complex structures |
%# | Zero-based test index | 0, 1, 2 |
%$ | One-based test number (Jest 30) | 1, 2, 3 |
%% | Literal percent sign | % |
Syntax Formats
| API Syntax | Structure | Best Suited For |
test.each([...]) | Nested array of row values | Simple primitive parameter matrices |
test.each\…“ | Tagged template literal table | Multi-variable complex business rules |
describe.each(...) | Parameterized suite wrapper | Running entire suites across environments |
Best Practices
โ Do This:
TypeScript
test.each(cases)('processes %s correctly', (input) => { ... }); // โ
โ Don’t Do This:
TypeScript
cases.forEach(([input]) => { test(`processes ${input}`, () => { ... }); }); // โ
โ Do This:
TypeScript
test.each`
input | output
${'a'} | ${'A'}
`('transforms $input', ({ input, output }) => { ... }); // โ
โ Don’t Do This:
TypeScript
test.each([['a', 'A']])('transforms %s', (i, o) => { ... }); // โ
โ Do This:
TypeScript
test.each(scenarios)('TestCase %$ validates $name', ({ name }) => { ... }); // โ
โ Don’t Do This:
TypeScript
test.each(scenarios)('test case validates $name', ({ name }) => { ... }); // โ
โ Do This:
TypeScript
const cases = [[1, 2], [3, 4]] as const; // โ
โ Don’t Do This:
TypeScript
const cases: any[] = [[1, 2], [3, 4]]; // โ
Common Pitfalls
| Pitfall | Why It Happens | Fix |
| Unmatched placeholder count | Number of format tokens (%s, %d) does not match row parameter count | Ensure every positional token has a corresponding parameter in the test callback |
| TypeScript type inference errors on table rows | Default TypeScript type widening interprets table arrays as generic any[] | Cast arrays using as const or provide explicit tuple typing for rows |
| Using object property injection with array syntax | Attempting to use $property syntax when passing a raw array instead of an object row | Pass an array of objects or use Spock template literals for property mapping |
Misinterpreting zero-based index %# | Expecting %# to start at 1 for human-readable reports | Switch to Jest 30’s %$ placeholder for 1-based test numbering |
| Template literal expression type mismatch | Forgetting ${} wrapper around primitive values inside tagged template tables | Wrap all literal values in ${} inside template table cells |
Confusing %% with argument consumption | Including %% expecting it to consume a row parameter | Note that %% outputs a literal percent sign without consuming parameters |
Real-World Examples
1. Defining an Array-Based Matrix for Currency Conversion
TypeScript
const currencyCases = [
['USD', 'EUR', 0.92],
['EUR', 'USD', 1.09],
];
test.each(currencyCases)('converts %s to %s at rate %f', (from, to, rate) => {
expect(getRate(from, to)).toBe(rate);
});
2. Using Tagged Template Literals for Access Control Rules
TypeScript
test.each`
role | resource | allowed
${'admin'}| ${'users'} | ${true}
${'guest'}| ${'users'} | ${false}
`('$role access to $resource is $allowed', ({ role, resource, allowed }) => {
expect(checkAccess(role, resource)).toBe(allowed);
});
3. Implementing Jest 30 %$ Placeholder for Reporting Clarity
TypeScript
const testMatrix = [{ input: 'A' }, { input: 'B' }];
test.each(testMatrix)('TestCase %$ processes input $input', ({ input }) => {
expect(processInput(input)).toBeDefined();
});
4. Parameterizing Describe Suites Across Database Drivers
TypeScript
describe.each(['postgres', 'mysql', 'sqlite'])('Driver: %s', (driver) => {
test('connects successfully', () => {
expect(initConnection(driver)).resolves.toBe(true);
});
});
5. Formatting JSON Objects via %j in Test Titles
TypeScript
const jsonCases = [[{ id: 1 }, true], [{ id: null }, false]];
test.each(jsonCases)('validates payload %j yields %s', (payload, valid) => {
expect(validateJson(payload)).toBe(valid);
});
6. Handling Floating-Point Calculations with %f Tokens
TypeScript
const mathCases = [[0.1, 0.2, 0.3]];
test.each(mathCases)('adds %f and %f to equal %f', (a, b, expected) => {
expect(a + b).toBeCloseTo(expected);
});
7. Validating Empty and Null Input Boundaries
TypeScript
test.each([null, undefined, ''])('rejects empty input %p', (val) => {
expect(() => sanitize(val)).toThrow();
});
8. Injecting Nested Object Properties in Template Literals
TypeScript
const users = [{ user: { profile: { age: 20 } } }];
test.each(users)('user age $user.profile.age is adult', ({ user }) => {
expect(user.profile.age >= 18).toBe(true);
});
9. Escaping Literal Percent Signs Using %%
TypeScript
const discountCases = [[10, '10%%']];
test.each(discountCases)('applies discount of %d with label %s', (val, lbl) => {
expect(formatDiscount(val)).toBe(lbl);
});
10. Combining %# Indexing with Custom Failure Messages
TypeScript
test.each([10, 20])('test item %# processes correctly', (val) => {
expect(processItem(val)).toBeTruthy();
});
Visual
Parameterized Test Execution Flow
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 1. Define Data Source (Array Matrix or Spock Table) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 2. test.each Iterates Over Each Row Definition โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 3. Format Title Placeholders (%s, %d, %$ Test Number) โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ 4. Execute Test Callback and Report Individual Case โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Array Table Indexing Architecture
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Row Index 0 โโโบ [ 'Standard', 100, 20, 120 ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Row Index 1 โโโบ [ 'Reduced', 100, 5, 105 ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโค
โ Row Index 2 โโโบ [ 'Zero', 100, 0, 100 ] โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Jest 30 Placeholder Resolution Pipeline
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Test Title String: "TestCase %$ validates $payload" โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Resolve %$ Token โโโบ Injects 1-based Iteration Number โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโฌโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ
โผ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
โ Resolve $Variable โโโบ Evaluates Object Property Path โ
โโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโโ
Summary
| Item | Value |
| Concept | Parameterized Testing in Jest |
| Core API | test.each and describe.each |
| Data Structures | Nested arrays or tagged template literal tables |
| Positional Tokens | %s, %d, %f, %j, %o, %p |
| Indexing Tokens | %# (zero-based index), %$ (one-based test number in v30) |
| Object Property Injection | $variable or $path.to.property syntax |
| Literal Escape | %% for percent symbols |
| Suite Parameterization | describe.each for multi-suite matrices |
| Readability Benefit | Eliminates test duplication and boilerplate loops |
| Reporting Clarity | Isolates failures per data row instantly |
Key takeaways:
- Eliminate duplication. Use
test.eachto execute identical assertion logic across multiple data variations without copy-pasting test blocks. - Choose the right syntax. Opt for nested arrays for simple primitive lists, or Spock-style tagged template tables for complex multi-variable matrices.
- Leverage Jest 30 numbering. Utilize the
%$placeholder token to inject human-friendly, 1-based test case numbers into test titles for clearer reporting. - Format with precision. Apply printf tokens like
%s,%d, and%jto embed exact input values directly into generated test names. - Inject object paths. Reference nested object keys seamlessly using
$variable.propertysyntax inside template literal test titles. - Avoid manual loops. Never wrap assertions in manual
forEachloops; nativetest.eachensures robust error isolation and distinct test reporting.
Remember: Parameterized testing transforms bloated, repetitive test suites into concise, data-driven specifications. By mastering array matrices, Spock template tables, and Jest 30’s %$ test-numbering placeholder, engineering teams can maintain maximum test coverage with minimal code maintenance overhead.
Stop using slow, ad-bloated tool sites! ๐คฎ
๐ Search “KandZ Tools” on Google to use many professional utilities for free.
KandZ.me is the ultimate minimalist hub for:
โ
Finance (Mortgage, Interest, Inflation)
โ
Tech (Base64, JSON, Dev Suite, IP)
โ
Health (BMI, BMR, TDEE)
โ
Productivity (Timer, Workspace, QR)
โก๏ธ Fast & Private
๐ No data leaves your device
๐ 100% Free
๐ Use it now: https://tools.kandz.me
๐ Bookmark itโyouโll need it later!