How to mock a worker for a Jest test?

Viewed 40

I have a test:

import { convertHeicToPng } from './heicUtils';

class Worker {
  url: string;
  onmessage: (m?: any) => void;
  constructor(stringUrl: string) {
    this.url = stringUrl;
    this.onmessage = () => {};
  }

  postMessage(msg: any) {
    this.onmessage(msg);
  }
}

(window.Worker as any) = Worker;

describe('test heicUtils', () => {
  test('should convert HEIC to PNG', async () => {
    const file = new File([''], 'test.heic', { type: 'image/heic' });
    const base64 = await convertHeicToPng(file);
    expect(base64).toContain('data:image/png;base64');
  });
});

and in heicUtils, I'm using heic2any, which uses WebWorkers. How can I properly mock a Worker for a Jest test?

0 Answers
Related