Skip to content

oscarmarina/lit-vitest-testing-comparison

Repository files navigation

Testing Lit with Vitest Browser and Playwright

Introduction

This guide outlines the process of migrating from using Web Test Runner to Vitest Browser for testing web components created with Lit. For more details on browser mode, visit the Vitest guide.

This change stems from a desire to explore more popular and widely adopted options in the open-source world, such as Vite and Vitest.

It's interesting to see how Vitest Browser draws inspiration from many other tools, including Web Test Runner itself.

Demo

Open in StackBlitz


Using Chai A11y aXe and rollup-plugin-externalize-source-dependencies

The Chai A11y aXe testing library can be used with Vitest.

test('a11y', async () => {
  await assert.isAccessible(el);
});

However, you'll need to add the following plugin to your Vite configuration:

import { defineConfig } from 'vite';
import externalizeSourceDependencies from '@blockquote/rollup-plugin-externalize-source-dependencies';

export default {
  plugins: [
    externalizeSourceDependencies([
      /* @web/test-runner-commands needs to establish a web-socket
       * connection. It expects a file to be served from the
       * @web/dev-server. So it should be ignored by Vite */
      '/__web-dev-server__web-socket.js',
    ]),
  ],
};

Using Vitest Snapshots with Semantic-DOM-Diff

Vitest's snapshot feature combines very well with getDiffableHTML from @open-wc/semantic-dom-diff, providing a powerful way to test DOM structures meaningfully.

import {getDiffableHTML} from '@open-wc/semantic-dom-diff';

test('LIGHT DOM - Structure test', () => {
  expect(getDiffableHTML(el, {ignoreAttributes: ['id']})).toMatchSnapshot('LIGHT DOM');
});

For more details, refer to the snapshots - semantic-dom-diff documentation.


Scaffold generated using:

npm init @blockquote/wc