Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- SERVICE WORKER TESTING
- - SW’s have states:
- - Installing ( synonymous with registering)
- - Installed ( synonymous with registered)
- - Activating
- - Activated
- - Redundant
- - We add eventListeners (as you would on browser elements) to detect and act upon changes in worker state
- - SW’s must be registered before they can be installed and go active. They stay registered until their SW file changes or it’s explicitly de-registered (usually by calling the unregister() method on the SW) .
- - A SW’s cache (usually IndexedDB these days, although I see references to WebSQL occasionally) persists, even through de-registration.
- To maintain a consistent testing environment, you must purge the cache and de-register the SW.
- Generally, SW behavioral tests do one of two things:
- - listen for changes in SW state and report on them
- - read messages posted from the SW and report on them or the cache
- This is all well and good if we want to test the BEHAVIOR of a SW - but what if we’re interesting in testing the stuff that’s going on inside of it?
- - Here’s the workflow for unit testing using Service Workers:
- - Register your service worker.
- - Import a testing suite using importScripts()
- - Within the service worker, write tests.
- - Instead of your testing suite writing stuff to the Dom/console, configure it such that testing results are posted to the parent (using .postMessage() ).
- - Write a function that tells the service worker to run tests on command.
- - Outside of the SW write a test that listens for messages from that service worker.
- - Outside of the SW, write a function that commands the SW to run tests.
- You can also configure create fake events and pass them to a service worker for testing purposes. See here for a list of events:
- https://developer.mozilla.org/en-US/docs/Web/API/Event
- I don’t like this process too much for two reasons -
- - You’re writing a test that’s basically waiting for the results of a test, which feels unintuitive.
- - Managing the active/idle/terminated behaviors is a bit of a pain
- There are some particulars to keep in mind - Chrome generally tries to terminate up service worker threads after 30 seconds for efficiency. You may not want this in a testing environment - so to prevent this behavior, you have to turn on dev tools (possibly not desirable in a testing situation).
- So the idea is: write a library that would allow you to write tests outside of the service worker environment and allow you to importScript() them into the SW, taking snapshots of the cache and de/registering along the way as needed.
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement