← Back to library
Playwrightauthadvancedv1.20+
Simulate token expiry and refresh
Return a 401 on the first API call, then a valid response on the retry to verify token-refresh logic.
1test('app refreshes token on 401', async ({ page }) => {
2 let callCount = 0;
3
4 await page.route('**/api/data', async (route) => {
5 callCount++;
6 if (callCount === 1) {
7 // First call returns Unauthorized
8 await route.fulfill({ status: 401, body: JSON.stringify({ error: 'Unauthorized' }) });
9 } else {
10 // Second call succeeds after the app has refreshed the token
11 await route.fulfill({ status: 200, body: JSON.stringify({ items: ['a', 'b'] }) });
12 }
13 });
14
15 await page.goto('/dashboard');
16
17 await expect(page.getByText('a')).toBeVisible();
18 expect(callCount).toBe(2); // confirm the retry happened
19});#401#token refresh#intercept#retry