Skip to contentPlayForge

How should I organise test data in Playwright?

Written by Jatin Thacker, Automation Architect · Updated

Keep fixed test data in its own files, such as a JSON file under test-data/, and import it into the tests that need it. Tests then describe behaviour, and a price or a SKU changes in one place.

This answer is one piece of Chapter 21: Test Data.

  • Data-Driven Testing Patterns
  • Reading and Writing Excel Test Data
  • Many Users and Roles in One Spec
  • Building the Test Layer

The first test data problem is usually not volume, it is scatter. The same SKU and price get typed into ten specs, the price changes, and nine get updated. A data file gives each value one home and a name, such as products.grinder.

A reasonable starting layout is a test-data/ folder next to your tests, with one JSON file per area of the app. JSON is easy for anyone on the team to read and edit, including people who do not write the tests. In an ES module project, you import it with an import attribute: import products from './test-data/products.json' with { type: 'json' }.

Two cautions. Data that a test creates, like a new order, should be created by that test rather than stored, so tests do not depend on each other. And secrets, such as real passwords, do not go in these files; they come from environment variables.

In the example, the test reads the grinder's SKU, name and price from the file, then checks the catalogue card shows the same heading and ₹11,900.

test-data.spec.js(https://practice.learnplayforge.com)
// test-data/products.json: // { // "grinder": { "sku": "MRD-1003", "name": "Halcyon Burr Grinder", "price": "₹11,900" }, // "kettle": { "sku": "MRD-1001", "name": "Aurora Pour-Over Kettle", "price": "₹4,290" } // } import { test, expect } from '@playwright/test'; import products from './test-data/products.json' with { type: 'json' }; test('the grinder card shows the price from the data file', async ({ page }) => { const { sku, name, price } = products.grinder; await page.goto('/catalog.html?mock=static&seed=42&autologin=1'); const card = page.locator(`article[data-sku="${sku}"]`); await expect(card.getByRole('heading')).toHaveText(name); await expect(card.getByTestId('product-price')).toHaveText(price); });
Output
1 passed (2.5s)
Test yourself
In an ES module Playwright project, which line imports products.json as data?

AI can write the test now. The job is knowing whether it checks anything. That's what the course teaches, one chapter at a time.

163 lessons · 226 drills · start free

← All questions

Training a team? Talk to us.