Em Elkan
Learning Notes

Learning Notes

Data-Driven Testing with Cypress

Em Elkan's photo
Em Elkan
·May 29, 2022·

2 min read

What is Data-Driven Testing? Data-Driven Testing is where the test data is located and imported from another source such as a CSV or JSON file rather than being hardcoded in a test script. This method allows test scripts to be DRY ("Don't repeat yourself") and easily executed with different combinations of test data.

Cypress Fixtures

Cypress has the ability to store and import test data from files normally located in the fixtures folder. See below for an example fixture file:

products.json

[
  {
    "product": "Sauce Labs Backpack",
    "description": "carry.allTheThings() with the sleek, streamlined Sly Pack that melds uncompromising style with unequaled laptop and tablet protection."
  },
  {
    "product": "Sauce Labs Bike Light",
    "description": "A red light isn't the desired state in testing but it sure helps when riding your bike at night. Water-resistant with 3 lighting modes, 1 AAA battery included."
  },
  {
    "product": "Sauce Labs Bolt T-Shirt",
    "description": "Get your testing superhero on with the Sauce Labs bolt T-shirt. From American Apparel, 100% ringspun combed cotton, heather gray with red bolt."
  },
  {
    "product": "Sauce Labs Fleece Jacket",
    "description": "It's not every day that you come across a midweight quarter-zip fleece jacket capable of handling everything from a relaxing day outdoors to a busy day at the office."
  },
  {
    "product": "Sauce Labs Onesie",
    "description": "Rib snap infant onesie for the junior automation engineer in development. Reinforced 3-snap bottom closure, two-needle hemmed sleeved and bottom won't unravel."
  },
  {
    "product": "Test.allTheThings() T-Shirt (Red)",
    "description": "This classic Sauce Labs t-shirt is perfect to wear when cozying up to your keyboard to automate a few tests. Super-soft and comfy ringspun combed cotton."
  }
]

We can import the fixture file to use the data it contains in our test script. Instead of writing out the same test multiple times we can use a single test to cycle through each entry in the fixture file.

import data from "../fixtures/products.json";

describe("All the products", () => {
  beforeEach(() => {
    cy.login("standard_user", "secret_sauce");
  });

  data.forEach((entry) => {
    it("Contains product " + entry.product, () => {
      cy.get("body")
        .should("contain", entry.product)
        .and("contain", entry.description);
    });
  });
});

How it looks in the test runner:

LLxqnur0oq.png

Resources

 
Share this