How to Separate Test Data, Actions and Assertions in Playwright: Complete Practical Guide
Imagine that you are testing a login page using Playwright.
Your test needs three important things:
Username and password.
Actions to enter the credentials and click Login.
Assertions to verify whether login was successful.
A beginner may write everything inside one test file.
test('Login Test', async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', {
name: 'Login'
}).click();
await expect(page).toHaveURL(/dashboard/);
});
This test is simple and works.
But imagine that your application has 200 login-related scenarios, different user roles, multiple environments and several authentication conditions.
Managing all the data, actions and assertions in one place becomes difficult.
This is where separation of responsibilities becomes important.
Separating test data, actions and assertions means keeping input values, application interactions and expected results in clearly defined locations so that each part can be updated independently.
In this guide, you will learn how to organize these three important parts of Playwright automation using TypeScript, JSON files, Page Object Model and reusable functions.
What Are Test Data, Actions and Assertions in Playwright?
Before creating the framework, understand the three main components.
1. What is test data?
Test data is the information required to execute an automated test.
For a login test, it may contain:
Username
Password
User role
Expected result
Example:
const loginData = {
username: 'testuser',
password: 'password123'
};
2. What are test actions?
Test actions are the operations performed on the application.
Examples:
Open a webpage.
Enter a username.
Enter a password.
Click a button.
Select a product.
Submit a form.
Example:
await page.getByLabel('Username').fill('testuser');
await page.getByLabel('Password').fill('password123');
await page.getByRole('button', {
name: 'Login'
}).click();
3. What are assertions?
Assertions check whether the application behaves as expected.
For example:
Did the login succeed?
Is the dashboard visible?
Is the error message displayed?
Does the page contain the expected information?
Example:
await expect(page).toHaveURL(/dashboard/);
Think about a school examination.
Test data = Questions and answers.
Actions = Writing the answers.
Assertions = Checking whether the answers are correct.
All three have different responsibilities.
Why Should You Separate Test Data, Actions and Assertions?
Consider a real e-commerce application.
It contains:
50 user accounts.
100 product records.
20 checkout scenarios.
15 payment scenarios.
Multiple customer roles.
If all the data is hardcoded inside test files, updating a product price or user account may require changing multiple files.
This creates three major problems.
Problem 1: Difficult updates
Changing test credentials becomes time-consuming.
Problem 2: Code duplication
The same action may be repeated in several test cases.
Problem 3: Poor readability
Another developer may struggle to understand what the test is actually validating.
Separating responsibilities makes the code easier to read, reuse, debug and update.
Recommended Folder Structure for Separating Test Data, Actions and Assertions
Here is a practical Playwright framework structure.
playwright-project/
│
├── tests/
│ └── authentication/
│ └── login.spec.ts
│
├── pages/
│ └── LoginPage.ts
│
├── test-data/
│ └── login-data.json
│
├── actions/
│ └── login-actions.ts
│
├── assertions/
│ └── login-assertions.ts
│
├── fixtures/
│ └── test-fixtures.ts
│
├── playwright.config.ts
└── package.json
Let's understand each part with working examples.
Step 1: Separate Test Data into a JSON File
Create a file named:
test-data/login-data.json
Add the following information:
{
"validUser": {
"username": "testuser",
"password": "password123"
},
"invalidUser": {
"username": "wronguser",
"password": "wrongpassword"
}
}
Now the test data is stored separately from the automation logic.
You can import it into your test file.
import loginData from '../../test-data/login-data.json';
This makes it easier to update test values without changing the test steps.
Why should you use JSON for test data?
JSON is useful because:
It is easy to understand.
It supports structured information.
It works with JavaScript and TypeScript.
It allows multiple test scenarios.
It separates input values from test logic.
However, never store real passwords, access tokens or confidential customer information in a JSON file committed to a public or shared repository.
Use environment variables or a secure secrets manager for sensitive values.
Step 2: Separate Application Actions
Create a file named:
actions/login-actions.ts
This file contains reusable operations.
import { Page } from '@playwright/test';
export class LoginActions {
constructor(private page: Page) {}
async openLoginPage() {
await this.page.goto('/login');
}
async enterUsername(username: string) {
await this.page.getByLabel('Username').fill(username);
}
async enterPassword(password: string) {
await this.page.getByLabel('Password').fill(password);
}
async clickLogin() {
await this.page.getByRole('button', {
name: 'Login'
}).click();
}
async login(username: string, password: string) {
await this.openLoginPage();
await this.enterUsername(username);
await this.enterPassword(password);
await this.clickLogin();
}
}
What is happening here?
The LoginActions class contains the operations required for login.
Instead of repeating the same operations in different test files, you can reuse the class.
For example:
await loginActions.login('testuser', 'password123');
This single method performs the complete login workflow.
Why are reusable actions important?
Imagine that the login button changes its accessible name.
You can update the locator inside the action class instead of searching through every test file.
This reduces code duplication and improves maintainability.
Step 3: Separate Assertions into Their Own File
Create:
assertions/login-assertions.ts
This file contains the expected results.
import { Page, expect } from '@playwright/test';
export class LoginAssertions {
constructor(private page: Page) {}
async verifySuccessfulLogin() {
await expect(this.page).toHaveURL(/dashboard/);
}
async verifyLoginError() {
await expect(
this.page.getByText('Invalid username or password')
).toBeVisible();
}
}
Now your assertions are separate from the application actions.
For example:
await loginAssertions.verifySuccessfulLogin();
This makes the test intention clearer.
One important design rule: do not create an assertion class for every small test if a direct assertion is already easy to understand. Separate assertion helpers when they are reused or when they represent meaningful business-level validation.
Step 4: Combine Everything Inside the Test File
Now create:
tests/authentication/login.spec.ts
import { test } from '@playwright/test';
import loginData from '../../test-data/login-data.json';
import { LoginActions } from '../../actions/login-actions';
import { LoginAssertions } from '../../assertions/login-assertions';
test('User should login successfully', async ({ page }) => {
const loginActions = new LoginActions(page);
const loginAssertions = new LoginAssertions(page);
await loginActions.login(
loginData.validUser.username,
loginData.validUser.password
);
await loginAssertions.verifySuccessfulLogin();
});
test('Invalid user should see an error', async ({ page }) => {
const loginActions = new LoginActions(page);
const loginAssertions = new LoginAssertions(page);
await loginActions.login(
loginData.invalidUser.username,
loginData.invalidUser.password
);
await loginAssertions.verifyLoginError();
});
Now each part has a clear responsibility.
This is a practical way to make automation code easier to understand.
Step 5: How to Handle Multiple Test Data Scenarios
Large applications need multiple test scenarios.
For example, a login page may have:
Valid username and password.
Invalid username.
Invalid password.
Empty username.
Empty password.
Both fields empty.
You can organize these scenarios using an array.
Example:
const loginScenarios = [
{
name: 'Valid credentials',
username: 'testuser',
password: 'password123',
expected: 'success'
},
{
name: 'Invalid username',
username: 'wronguser',
password: 'password123',
expected: 'failure'
},
{
name: 'Invalid password',
username: 'testuser',
password: 'wrongpassword',
expected: 'failure'
}
];
Now create tests using a loop.
import { test, expect } from '@playwright/test';
for (const scenario of loginScenarios) {
test(`Login scenario: ${scenario.name}`, async ({ page }) => {
await page.goto('/login');
await page.getByLabel('Username').fill(scenario.username);
await page.getByLabel('Password').fill(scenario.password);
await page.getByRole('button', {
name: 'Login'
}).click();
if (scenario.expected === 'success') {
await expect(page).toHaveURL(/dashboard/);
} else {
await expect(
page.getByText('Invalid username or password')
).toBeVisible();
}
});
}
This technique is called data-driven testing.
It allows you to execute multiple test scenarios using different input values.
For larger frameworks, keep the scenario data in a separate JSON or TypeScript file.
Step 6: How to Use Page Object Model Alongside Actions
You may have one important question.
If Page Object Model already separates page interactions, why do we need a separate actions folder?
The answer is that both approaches can solve different organizational needs.
A page object usually represents a page or component and contains its locators and page-specific operations.
An action layer can represent reusable business workflows that involve one or more pages.
For example:
LoginPage.ts
Contains:
Username locator
Password locator
Login button locator
Page-specific login operations
LoginActions.ts
Contains:
Complete login workflow
Reusable business operations
Navigation across related steps when necessary
You do not need both layers in every project.
For a small application, Page Object Model may be sufficient.
For a larger application with complex workflows, a separate workflow or action layer can be useful.
Avoid creating unnecessary layers that make the framework harder to understand.
Step 7: Separate Environment Configuration from Test Data
Another important part of a maintainable framework is environment management.
Your application may have:
Development environment
Testing environment
Staging environment
Production environment
Do not hardcode URLs in every test.
Instead, use Playwright configuration.
Example:
import { defineConfig } from '@playwright/test';
export default defineConfig({
use: {
baseURL: process.env.BASE_URL || 'http://localhost:3000'
}
});
Now you can execute tests using a different environment URL.
Example:
BASE_URL=https://staging.example.com npx playwright test
This command uses the staging environment.
For Windows PowerShell:
$env:BASE_URL="https://staging.example.com"
npx playwright test
Do not use production environments for tests that create, update or delete real customer data unless the testing process is explicitly authorized and safely controlled.
Common Mistakes When Separating Test Data, Actions and Assertions
1. Keeping all information in the test file
This makes large test files difficult to maintain.
2. Creating too many helper files
Not every operation needs its own class or file.
Organize according to actual reuse and responsibility.
3. Mixing test data with expected results
Input values and expected outcomes have different purposes. Keep them clearly named and structured.
4. Using real customer data
Always use approved test accounts and controlled test information.
5. Creating generic functions that perform too many operations
A function should have a clear purpose.
6. Hiding assertions inside actions
Actions should normally perform operations, while tests or dedicated validation helpers should check expected outcomes.
7. Hardcoding secrets
Never commit confidential credentials or tokens to your source repository.
Best Practices for Large Playwright Automation Frameworks
Follow these practices:
Keep test data separate from test logic.
Use TypeScript types for structured test data.
Create reusable actions for repeated workflows.
Use page objects for page-specific behavior.
Keep assertions meaningful and readable.
Use environment variables for configuration.
Avoid unnecessary code duplication.
Use unique test data for parallel execution.
Document reusable framework components.
Review the framework regularly.
Frequently Asked Questions
1. Why should test data be separated from Playwright tests?
Separating test data makes it easier to update input values, create multiple scenarios and reuse the same data across tests.
2. What is the difference between test data and test actions?
Test data contains the information used during testing. Test actions are the operations performed on the application using that information.
3. What are assertions in Playwright?
Assertions verify whether the actual application behavior matches the expected result. For example, checking whether a dashboard is visible after login.
4. Should assertions be inside Page Object Model classes?
They can be included when they represent meaningful page-level validation, but avoid hiding all test expectations inside page objects. Keep important business expectations visible in the test.
5. Can Playwright read test data from JSON files?
Yes. Playwright projects using JavaScript or TypeScript can import JSON data and use it in automated test cases.
6. What is data-driven testing in Playwright?
Data-driven testing means executing the same test logic using different sets of input data to validate multiple scenarios.
7. Is Page Object Model enough for a large Playwright framework?
POM is a useful design pattern, but large projects may also need fixtures, configuration management, test data management, reusable utilities and workflow organization.
Conclusion
Separating test data, actions and assertions is an important step toward building a clean and maintainable Playwright automation framework.
When every component has a clear responsibility, developers can update test values, modify application interactions and change expected results without unnecessarily modifying unrelated code.
Start with a simple structure. Introduce additional layers when your application and testing requirements genuinely need them.
The goal is not to create the biggest framework. The goal is to create a framework that your team can understand, reuse and maintain confidently.

Comments
Post a Comment