liveBook · Manning

Parameterized testing

As explained in The Art of Unit Testing 3e

A parameterized test is a test whose logic runs repeatedly with different values drawn from a parameter set or table.

When several tests exercise the same scenario with small input variations, parameterized testing runs one test definition repeatedly against a table of values. It reduces duplicated setup and assertions while keeping the behavior under test explicit. section 2.9 section 8.2.4

A parameterized test is not a license to combine unrelated cases. Keep one scenario throughout the table; use separate tests when the expected behavior or type of input changes. Generic tests can save code but become harder to read and debug. section 2.12 section 2.9

Practical choices include:

  • Use Jest's built-in test.each or its it.each alias when the same test should run for several values. section 2.9 section 2.12
  • Pass multiple values as rows such as [input, expected], letting the framework map each row to test arguments. section 2.9
  • Prefer a small parameter table over shared beforeEach setup when it makes each case easier to understand. section 2.12 section 8.2.4
Listing 2.22 Refactoring test.each
describe('one uppercase rule', () => {
  test.each([ ['Abc', true],                    #1
              ['aBc', true],
              ['abc', false]])                  #2
    ('given %s, %s ', (input, expected) => {    #3
      const result = oneUpperCaseRule(input);
      expect(result.passed).toEqual(expected);
    });
});
#1 Providing three arrays, each with two parameters
#2 A new false expectation for a missing uppercase character
#3 Jest maps the array values to arguments automatically.

A password uppercase-rule test uses rows containing an input and its expected result, covering both passing and failing cases. section 2.9

How The Art of Unit Testing 3e covers it

How deep it goes
Explains table-driven repetition, multiple parameters, alternatives, and the boundary between reuse and unreadable generic tests.
Examples
Uses uppercase-password validation and numeric sum tests to contrast repeated tests with table-driven cases.
What you can do after
Apply it via Jest's test.each or a vanilla JavaScript loop while keeping each parameter table focused on one scenario.
How it connects
Connects parameterized testing with Jest, test.each, it.each, beforeEach, unit tests, and test readability.

Also explained in

Compare how 2 books explain parameterized testing →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of The Art of Unit Testing 3e. The section links point to the parts of the book it draws on.