Use workbox in Jest test

267 views Asked by At

My Vue app has a component that listens to a service worker to determine if the app needs to update. I would like to add a simple test that the component displays like it should. However, I need service workers and workbox working properly in a jest. I got service workers working with service-worker-mock, however I can't find any resources on how to incorporate workbox. Here is my test so far:

import UpdateNotification from '@/components/UpdateNotification.vue';
import { workbox } from 'workbox-sw';
const makeServiceWorkerEnv = require('service-worker-mock');


describe('UpdateNotification', () => {
    beforeEach(() => {
        Object.assign(global, makeServiceWorkerEnv(), workbox);
        jest.resetModules();

    });

    it('displays', async() => {
        require('../../../src/service-worker');
        render(UpdateNotification);
    });
});

And here is my service worker:

/* eslint-disable no-undef*/
workbox.precaching.precacheAndRoute(self.__precacheManifest);
workbox.routing.registerNavigationRoute(workbox.precaching.getCacheKeyForURL('index.html'));

My solution so far is breaking at require('../../../src/service-worker'); in the test due to:

TypeError: Cannot read property 'precacheAndRoute' of undefined

      1 | /* eslint-disable no-undef*/
    > 2 | workbox.precaching.precacheAndRoute(self.__precacheManifest);

That import of { workbox } is just kind of guesswork, and I think that's where I'm going wrong.

0

There are 0 answers