DEV Community

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

Posted on

1

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.

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (1)

Collapse
 
layzee profile image
Lars Gyrup Brink Nielsen โ€ข

Thanks for the advice. I didn't know it was this simple with ESBuild ๐Ÿ˜ƒ

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

๐Ÿ‘‹ Kindness is contagious

Please leave a โค๏ธ or a friendly comment on this post if you found it helpful!

Okay