'Testing a serviceworker using Workbox
I have made an implementation of a service working using Google's Workbox library and I want to test my custom route handlers and logic, but I am really unsure how I can best test this. The tests should be performed in the browser because I will need to verify if the cache or my database has been modified. I also load in my custom route and handlers via a config file, so I need to make sure the correct routes are registered.
Can somebody help me point in the right direction? I have tried unit testing with Jest, but I could make the functions work which use parts of the Workbox library.
Solution 1:[1]
I can point you to a few different resources, but there's no one clear best, modern way to test service worker functionality (that I'm aware of).
The sw-appcache-behavior test suite
The test suite for sw-appcache-behavior
is not directly related to Workbox, but it does test service worker caching behavior. The advantage of basing your tests off of this is that it's a newer and simpler codebase than Workbox, and it shows off how to run a test suite that uses Puppeteer to orchestrate in-browser tests, including examining cache contents after service worker event handlers have completed.
The Workbox test suite
You could also look at how Workbox tests its own first-party code and use that as an example. I'd divide those tests up into three parts:
node
unit tests
Some tests are run in a node
environment using a mock service worker environment, and heavily uses sinon
stubs to observe calls to the underlying fetch()
and Cache Storage APIs to ensure that the expected calls are being made.
Current integration tests
These tests rely on Selenium (wrapped via the selenium-assistant
library) to control instances of Safari, Chrome, and Firefox. You have the advantage over the mock environment in the unit tests of actually getting test behaviors in a real browser environment. Unfortunately, there's a decent amount of pre-test workarounds and general flakiness involved in this approach to testing.
Future integration tests
We've been working on a modernization of the Workbox integration test suite to use Playwright instead of selenium-assistant
to orchestrate tests across Safari, Firefox, and Chrome. The resulting code ends up being much less complex, with fewer browser-specific workarounds. This is probably what I would recommend modeling a new codebase off of.
Unfortunately, we haven't had enough time to prioritize migrating the entire existing test suite over to Playwright, but you can take a look at some of what has been migrated over in a branch, and use that as inspiration.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Jeff Posnick |