21 / 66 · 09 Mobile & Cross-Platform Testing · PWA Testing← prev⊞ allnext →☰ Read as one page
4.3Push Notification Testing
// tests/pwa/push-notifications.spec.ts
import { test, expect } from '@playwright/test';
test.describe('Push Notifications', () => {
test('requests notification permission on first interaction', async ({ page, context }) => {
// Grant notification permission
await context.grantPermissions(['notifications']);
await page.goto('/');
await page.click('[data-testid="enable-notifications-btn"]');
// Verify subscription was created
const subscription = await page.evaluate(async () => {
const reg = await navigator.serviceWorker.ready;
const sub = await reg.pushManager.getSubscription();
return sub !== null;
});
expect(subscription).toBe(true);
});
test('displays notification when push event received', async ({ page }) => {
await page.goto('/');
// Simulate push via service worker
const notificationShown = await page.evaluate(async () => {
const reg = await navigator.serviceWorker.ready;
await reg.showNotification('Test Order Update', {
body: 'Your order #123 has shipped',
icon: '/icons/notification-icon.png',
actions: [
{ action: 'view', title: 'View Order' },
{ action: 'dismiss', title: 'Dismiss' }
]
});
return true;
});
expect(notificationShown).toBe(true);
});
test('handles notification permission denial gracefully', async ({ page, context }) => {
// Deny notification permission
await context.grantPermissions([]);
await page.goto('/');
// The enable button should still be present
const enableBtn = page.locator('[data-testid="enable-notifications-btn"]');
await expect(enableBtn).toBeVisible();
// Clicking it should show a fallback message, not crash
await enableBtn.click();
await expect(page.locator('[data-testid="notification-denied-message"]')).toBeVisible();
});
});