vitest-dev / vitest

Next generation testing framework powered by Vite.
https://vitest.dev
MIT License
12.17k stars 1.07k forks source link

Support service worker testing #4033

Open ayroblu opened 10 months ago

ayroblu commented 10 months ago

Clear and concise description of the problem

Service workers are complicated, so having unit tests for them where you can inspect every caching decision can be important.

Currently I'm not familiar with any way to test in a service worker environment with vitest. It would be great if it supported that.

I had a quick go and I got a hard error:

Error: This module can only be imported inside a service worker

I will try look for a workaround, but generally it would be good to have decent support for the service worker use case

Suggested solution

Add service worker environment testing

Alternative

playwright? Though I'm not sure it has good support either + you can't inspect every decision to ensure caches are correctly added / removed in all scenarios

Additional context

No response

Validations

FDiskas commented 3 months ago

You could try https://github.com/zackargyle/service-workers/tree/master/packages/service-worker-mock

In my case - spec file

/// <reference lib="WebWorker"/>
import makeServiceWorkerEnv from 'service-worker-mock';

declare const self: ServiceWorkerGlobalScope;

Object.assign(globalThis, makeServiceWorkerEnv());

describe('Service worker', () => {
  it('should add listeners', async () => {
    require('../../../../dist/lib/persist/sw');

    expect(self.listeners.get('install')).toBeDefined();
    expect(self.listeners.get('activate')).toBeDefined();
  });
});

I'm requiring a bundled service worker file instead of source code.