DEV Community

Cover image for How to use @testing-library with @web/test-runner
Danny Blue
Danny Blue

Posted on

How to use @testing-library with @web/test-runner

Web Test Runner is great and Testing Library is great. One problem is that the current versions of Testing Library are not fully compatible with esmodules. Using esbuild we can prepare our testing modules to make sure they run well in the browser.

Install Web Test Runner and Testing library.

npm i -D \
  @web/test-runner \
  @web/dev-server-import-maps \
  @testing-library/dom \
  @testing-library/user-event \
Enter fullscreen mode Exit fullscreen mode

Next run the following command. This will output bundled esmodule compatible files into a directory called ./testing-library.

esbuild \
 ./node_modules/@testing-library/* \
 --bundle \
 --outdir=testing-library \
 --format=esm
Enter fullscreen mode Exit fullscreen mode

Finally we can configure web-test-runner using import maps. Import maps allow the browser to map a give import token to a particular file.

import { importMapsPlugin } from "@web/dev-server-import-maps";

export default {
  nodeResolve: true,
  files: ["src/**/*.test.js"],
  plugins: [
    importMapsPlugin({
      inject: {
        importMap: {
          imports: {
            "@testing-library/dom": "./testing-library/dom.js",
            "@testing-library/user-event": "./testing-library/user-event.js",
          },
        },
      },
    }),
  ],
};

Enter fullscreen mode Exit fullscreen mode

Ideally in the future we won't need to do things like this but for now this is a solid workaround using tools that are already installed by web-test-runner.

Top comments (0)