Do you know the best part of Web Workers? They can speed up heavy tasks on your UI. But, have you tried testing them? Is not that easy… until now.

As you could read in Alex’s article, Use Web Workers in your Vue.js Components for Max Performance, you can use Web Workers to maximize performance in your Vue.js app instead of running heavy tasks in the main thread which is UI-blocking.

But how can we test Web Workers? Webpack-bundled Web Workers are not supported by Jest so we have to mock the worker in order to test it! Let’s see how to do in 3 simple steps, starting from a simple Vue app to calculate the Fibonacci number, where fibonacci function is the heavy task performed by the Web worker (you can follow the code here)

First of all we need to isolate the main functionality of our worker, in this case is really straightforward because it’s just our fibonacci function (src/fibonacci.js)

let fibonacci = (num) => {
  if (num <= 1) return 1;
  return fibonacci(num - 1) + fibonacci(num - 2);
}

export default fibonacci

and keep the worker minimal (src/fibonacci.worker.js):

import fibonacci from "./fibonacci";

self.onmessage = async function (e) {
  self.postMessage(fibonacci(e.data));
};

This way we can mock just the Web Worker part of our implementation (src/__mocks__/fibonacci.worker.js)

#testing #jest #programming #developer

How to test Web Workers with Jest
32.15 GEEK