alewin/useWorker

Testing useWorker

zant opened this issue Β· 4 comments

zant commented

Since they are plans to add new features (#36) I started to work in adding some tests for the hook. I initially setup Jest with react-hooks-testing-library. But found that Jest (which uses jsdom) does not have an implementation for URL.createObjectURL nor Web Workers.

So I had to dig a bit on the internet 🌈to find potential workarounds, and it seems that they're two approaches to test workers (afaik) that we can use.

Options

  • Test with karma on headless chrome, this approach is used by comlink which is a wrapper for Web Workers. I did try this and it worked nicely, the one downside I see is the tooling (needs a preprocessor like webpack with babel to bundle everything for the test, as it's going to be tested in a browser) but at the end they're just devDependencies so it will not affect bundle size.
  • Mock the Web Worker with something like jsdom-worker (although looks like is not actively maintained). This package also comes with a URL.createObjectURL mock :).

Imo, I prefer karma since it will provide reliable behavior for the tests. What do you guys think? πŸ˜„

For reference, this is the test I tried with Karma:

import React from "react";
import { useWorker } from "../dist/index";
import { renderHook } from "@testing-library/react-hooks";

it("Basic Test", async () => {
  const sum = (a, b) => a + b;
  const { result } = renderHook(() => useWorker(sum));
  const [sumWorker] = result.current;
  const res = await sumWorker(1, 2);
  assert.equal(res, 3);
});

Perfect analysis @gonzachr thanks! πŸ‘ I like the first option (karma approach), since it's based on a headless browser, moreover react-hooks-testing-library is really simple to use.

zant commented

Awesome @alewin! I'll open a PR later today πŸ‘

zant commented

Admittedly at first I just tried the first preprocessing option I found. Today I will make a few experiments with rollup as I found another karma preprocessor compatible with it. I heard good things about rollup specially for libraries so I think is a nice option, becase it really feels a bit bloated to add Webpack just for testing. Specially having such a compact bundler for the project itself πŸ˜…

zant commented

Closing after #88