This directory contains Jest tests for the Progressive Web App (PWA) Service Worker modules.
spec/javascript/
├── setup.js # Test setup with Service Worker API mocks
├── pwa/
│ ├── strategies/
│ │ ├── cache_first_strategy.test.js # Cache-first strategy tests
│ │ ├── network_first_strategy.test.js # Network-first strategy tests
│ │ └── network_only_strategy.test.js # Network-only strategy tests
│ ├── strategy_router.test.js # Strategy router tests
│ ├── lifecycle_manager.test.js # Lifecycle manager tests
│ └── config_loader.test.js # Config loader tests
└── README.md # This file
First, install the required npm packages:
npm installnpm testnpm run test:watchnpm run test:coverageCoverage reports are generated in the /coverage directory.
- Branches: ≥ 80%
- Functions: ≥ 80%
- Lines: ≥ 80%
- Statements: ≥ 80%
-
CacheFirstStrategy (
cache_first_strategy.test.js)- Serves from cache when available
- Falls back to network on cache miss
- Caches network responses
- Updates cache in background
- Handles errors gracefully
-
NetworkFirstStrategy (
network_first_strategy.test.js)- Tries network first with timeout
- Falls back to cache on network failure
- Caches successful network responses
- Handles timeout errors
- Provides offline fallback
-
NetworkOnlyStrategy (
network_only_strategy.test.js)- Always fetches from network
- Never caches responses
- Provides appropriate error responses
- Differentiates navigation vs API requests
-
StrategyRouter (
strategy_router.test.js)- Matches URL patterns correctly
- Routes to appropriate strategies
- Handles unmatched requests
- Skips non-GET and cross-origin requests
-
LifecycleManager (
lifecycle_manager.test.js)- Pre-caches critical assets on install
- Cleans up old caches on activate
- Calls skipWaiting and clients.claim
- Handles errors during lifecycle events
-
ConfigLoader (
config_loader.test.js)- Fetches configuration from API
- Falls back to defaults on error
- Provides nested config value access
- Handles invalid API responses
The test setup (setup.js) provides mocks for:
- Cache API:
caches.open(),caches.match(),caches.keys(),caches.delete() - Fetch API:
fetch()with configurable responses - Service Worker Globals:
self.skipWaiting(),self.clients.claim() - Request/Response: Browser-like Request and Response classes
- AbortController: For testing timeout functionality
it('should serve from cache when available', async () => {
// Arrange
const cachedResponse = createMockResponse('cached content');
mockCache.match.mockResolvedValue(cachedResponse);
// Act
const result = await strategy.handle(mockRequest);
// Assert
expect(result).toBe(cachedResponse);
expect(mockCache.match).toHaveBeenCalledWith(mockRequest);
});it('should fall back to cache when network fails', async () => {
// Arrange
global.fetch.mockRejectedValue(new Error('Network error'));
const cachedResponse = createMockResponse('cached content');
mockCache.match.mockResolvedValue(cachedResponse);
// Act
const result = await strategy.handle(mockRequest);
// Assert
expect(result).toBe(cachedResponse);
expect(console.warn).toHaveBeenCalledWith('[SW] Network failed:', 'Network error');
});The setup file provides helper functions for creating test fixtures:
setupCacheMock(): Creates a mock cache objectcreateMockResponse(body, options): Creates a mock ResponsecreateMockRequest(url, options): Creates a mock Request
Make sure you've installed all dependencies:
npm installRun coverage report to see uncovered lines:
npm run test:coverageThen check the HTML report in /coverage/index.html.
If mocks aren't working correctly, check that:
setup.jsis being loaded (configured injest.config.js)- Mocks are cleared between tests (happens automatically in
beforeEach)
To run tests in CI/CD pipelines:
# Example GitHub Actions workflow
- name: Run JavaScript Tests
run: |
npm ci
npm run test:coverage