Parameterized Tests in Cypress

How to write parameterized tests in Cypress

Cypress is a testing framework for anything running on a web browser. I am using it to test this site and I’ve talked before about it in the post "This is Sapper".

In this post I won’t explain how to use Cypress, they have a pretty nice documentation: Getting started with Cypress.

I will stick to the parameterized tests topic.

Parameterized tests: Also known as dynamic tests, it is an useful technique where you can specify an input dataset and the test case will be repeated for each element in the dataset.

Explicit input data set

Since sometimes you can’t run the test for all the possible inputs, you can select a set of meaningful data to test.

Example checking that the relevant pages in the site have valid HTML syntax
describe('validate pages', () => {
    [ (1)
    ].forEach((url) => { (2)
        it(`should be valid HTML ${url}`, () => { (3)
  1. List with relevant pages to validate

  2. Iterate over the list of pages

  3. Test case execution for selected page

Test results
Figure 1. Test results

Generated input data set

Instead of explicitly define a data set, you can generate it, for example, creating a random data set.

Example checking that any generated random number is less than 0
describe('random', () => {
    const inputData = Array.from(Array(100)).map(x => Math.random()) (1)
    inputData.forEach(x => { (2)
        it(`should be valid ${x}`, () => { (3)
  1. It generates an array of 100 random numbers

  2. Iterate over the generated array

  3. Test case execution

Test results
Figure 2. Test results