How to mock web worker for testing in react testing library?

Viewed 1316

I'm creating a web worker like this:

const getWebWorker = () => {
  let worker;
  if (typeof worker === 'undefined') {
    worker = new Worker('worker.js');
  }
  return worker;
};

Then I am calling the function like this:

useEffect(() => {
  getWebWorker().onmessage = (event) => {
    setWorkerData(event.data);
  };
}, []);

The actually worker.js file is under the public folder and postMessage's an object.

I'm using the react testing library/jest to test. When I run yarn run test I get the error ReferenceError: Worker is not defined at worker = new Worker('worker.js');.

I understand that I need to mock the worker, I'm just confused on how to.

What do I name the mock file in the __mock__ folder?

What would mocking the worker even look like?

Is there anything I have to do in the ____.test.js file?

Thanks

1 Answers

Afaik that is not supported by jest btw. Web Workers are a browser thing. Use e2e tests instead.

if (typeof(Worker) !== "undefined") {
  alert("Your have web worker support! (Webbrowser)")
} else {
  console.warn("You have no web worker support (node)")
}

Jest uses a JSDOM environment by default, which means it doesn't support Workers. This means it is impossible to test code that requires both NodeJS functionality and Web Workers. jsdom-worker

jsdom-worker tried to bring web workers to jest, but that had no update since 2020 and seems to be unmaintained... btw there is a spin off that is marked as experimental.

I had the same question and used e2e tests playwright to test things where web workers are involved because I found no production ready way to mock workers.

Related