import.meta.url and jest

Works for any framework!

Charlie Greenman
Razroo
1 min readNov 28, 2022

--

Life is beautiful! Ain’t it!

Create a service worker utils

// service-worker.util.ts
// swap out url with your own url
export function iAmWorker() {
if (typeof Worker !== 'undefined') {
const worker = new Worker(new URL('apps/razroo-frontend/src/app/razroo-frontend.worker.ts', import.meta.url));
return worker;
}
else {
// workers not supported in environment
}
}

Create a service worker mock utils

// servicer-worker.util.mock.ts
// remove import.meta.url
export function iAmWorker() {
if (typeof Worker !== 'undefined') {
const worker = new Worker(new URL('apps/razroo-frontend/src/app/razroo-frontend.worker.ts', ''));
return worker;
}
else {
return {}
// workers not supported in environment
}
}

Use service worker utils to get worker

// home.component.ts
import { createGenerateCodeDialogWorker } from './service-worker.util';

// yada code goes here
const worker = iAmWorker() as Worker;
// more yada yada code here

Here’s the magic! Jest config moduleNameMapper

// home/jest.config.ts
// swaps out service worker import path with mocked file

export default {
displayName: 'home',
moduleNameMapper: {
'.*service-worker.util': './service-worker.util.mock.ts',
},
}

That’s it!

--

--