How to Handle Dynamic Values in Playwright API Snapshot Testing
In Playwright, you can handle dynamic API response values before using toMatchSnapshot(). Dynamic values such as timestamps, IDs, UUIDs, tokens, and generated dates can cause snapshot tests to fail even when the API response is correct.
There are several ways to handle dynamic values in Playwright snapshot testing.
1. Replace Dynamic Values with Static Values
This is the recommended approach. Modify the API response before comparing it with the saved snapshot.
import { test, expect } from '@playwright/test';
test('API snapshot validation', async ({ request }) => {
const response = await request.get('/api/users/101');
const body = await response.json();
// Replace dynamic values
body.id = '<ID>';
body.createdAt = '<TIMESTAMP>';
body.updatedAt = '<TIMESTAMP>';
body.token = '<TOKEN>';
await expect(body).toMatchSnapshot('user-response.json');
});
Expected Snapshot: user-response.json
{
"id": "<ID>",
"name": "Sumit",
"email": "sumit@example.com",
"createdAt": "<TIMESTAMP>",
"updatedAt": "<TIMESTAMP>",
"token": "<TOKEN>"
}
2. Handle Dynamic Values Using Regular Expressions
You can normalize dynamic strings using regular expressions before comparing the API response with the snapshot.
const body = await response.json();
body.id = '<ID>';
body.createdAt = body.createdAt.replace(
/\d{4}-\d{2}-\d{2}T[\d:.]+Z/,
'<TIMESTAMP>'
);
await expect(body).toMatchSnapshot('user-response.json');
Explanation:
\d{4}matches a four-digit year.\d{2}matches a two-digit month or day.- The regular expression identifies an ISO-style UTC timestamp.
- The matched timestamp is replaced with a fixed placeholder.
3. Remove Dynamic Properties
If certain properties are not important for snapshot validation, you can remove them from the response before taking the snapshot.
const body = await response.json();
delete body.id;
delete body.createdAt;
delete body.updatedAt;
delete body.token;
await expect(body).toMatchSnapshot('user-response.json');
This approach is useful when you want to compare only stable API response properties.
4. Handle Dynamic Values in Nested JSON
API responses often contain nested objects with dynamic properties. You can access and normalize nested properties before snapshot comparison.
Example API Response
{
"user": {
"id": 1024,
"name": "Sumit",
"createdAt": "2026-11-20T09:00:00Z"
},
"account": {
"accountId": "ACC12345",
"lastLogin": "2026-11-20T09:10:00Z"
}
}
Playwright Test
const body = await response.json();
// Normalize nested dynamic properties
body.user.id = '<USER_ID>';
body.user.createdAt = '<TIMESTAMP>';
body.account.accountId = '<ACCOUNT_ID>';
body.account.lastLogin = '<TIMESTAMP>';
await expect(body).toMatchSnapshot('user-response.json');
5. Create a Reusable Function for Dynamic Values
If multiple API tests contain dynamic properties, create a reusable normalization function. This avoids repeating the same normalization logic in every test.
snapshot.utils.ts
export function normalizeResponse(body: any) {
return {
...body,
id: '<ID>',
createdAt: '<TIMESTAMP>',
updatedAt: '<TIMESTAMP>',
token: '<TOKEN>'
};
}
Usage in Playwright Test
import { test, expect } from '@playwright/test';
import { normalizeResponse } from '../../utils/snapshot.utils';
test('Validate API response snapshot', async ({ request }) => {
const response = await request.get('/api/users/101');
const body = await response.json();
const normalizedBody = normalizeResponse(body);
await expect(normalizedBody).toMatchSnapshot('user-response.json');
});
Note: The above utility assumes that the response contains these properties. For APIs with different response structures, create separate normalizers or use a reusable nested-property normalization utility.
6. Validate Dynamic Values Separately
Sometimes you should not replace dynamic values without validating them. For example, validate that an ID is a number and a timestamp is a valid date before normalizing the response.
const body = await response.json();
// Validate dynamic values
expect(body.id).toEqual(expect.any(Number));
expect(body.createdAt).toEqual(expect.any(String));
expect(Number.isNaN(Date.parse(body.createdAt))).toBe(false);
// Normalize before snapshot
body.id = '<ID>';
body.createdAt = '<TIMESTAMP>';
await expect(body).toMatchSnapshot('user-response.json');
This approach ensures that dynamic properties are still validated even though their actual values are not compared against the snapshot.
7. Comparison of Approaches
| Approach | When to Use |
|---|---|
| Replace dynamic values | Best for maintaining stable API snapshots. |
| Regex normalization | When dynamic strings follow a known format. |
| Delete properties | When properties are irrelevant to regression testing. |
| Reusable function | When multiple API tests share normalization logic. |
| Validate separately | When dynamic values must still satisfy business rules. |
8. Recommended Project Structure
For a REST API automation framework using Playwright, create a reusable snapshot utility.
project/
│
├── tests/
│ └── api/
│ ├── user.spec.ts
│ ├── config.spec.ts
│ ├── user.spec.ts-snapshots/
│ │ └── user-response.json
│ └── config.spec.ts-snapshots/
│ └── config-response.json
│
└── utils/
└── snapshot.utils.ts
9. Best Practices for Playwright API Snapshot Testing
- Validate the HTTP status code before comparing snapshots.
- Validate dynamic values separately using assertions.
- Normalize dynamic values before using
toMatchSnapshot(). - Use reusable normalization functions for multiple API tests.
- Remove only properties that are genuinely irrelevant to regression testing.
- Update snapshots only when API changes are intentional.
- Avoid replacing important business values without validating them first.
10. Conclusion
For API regression testing, toMatchSnapshot() is useful when you want to validate the complete response structure and its stable values.
The recommended approach is to follow these three steps:
- Validate HTTP status code: Check that the API returns the expected status code.
- Validate dynamic values: Check IDs, timestamps, tokens, and other generated values separately.
- Normalize and compare: Replace dynamic values with static placeholders and compare the response using
toMatchSnapshot().
This approach provides stable API snapshots without losing important API validations.

No comments:
Post a Comment