npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@noma.to/qwik-testing-library

v1.0.4

Published

Simple and complete Qwik testing utilities that encourage good testing practices.

Downloads

316

Readme

Read The Docs | Edit the docs

Build Status version downloads MIT License

All Contributors

PRs Welcome Code of Conduct Discord

Watch on GitHub Star on GitHub Tweet

Table of Contents

The Problem

You want to write maintainable tests for your Qwik components.

This Solution

@noma.to/qwik-testing-library is a lightweight library for testing Qwik components. It provides functions on top of qwik and @testing-library/dom so you can mount Qwik components and query their rendered output in the DOM. Its primary guiding principle is:

The more your tests resemble the way your software is used, the more confidence they can give you.

Installation

This module is distributed via npm which is bundled with node and should be installed as one of your project's devDependencies:

npm install --save-dev @noma.to/qwik-testing-library

This library supports qwik versions 1.7.2 and above.

You may also be interested in installing @testing-library/jest-dom and @testing-library/user-event so you can use the custom jest matchers and the user event library to test interactions with the DOM.

npm install --save-dev @testing-library/jest-dom @testing-library/user-event

Finally, we need a DOM environment to run the tests in. This library was tested (for now) only with jsdom so we recommend using it:

npm install --save-dev jsdom

Setup

We recommend using @noma.to/qwik-testing-library with Vitest as your test runner.

If you haven't done so already, add vitest to your project using Qwik CLI:

npm qwik add vitest

After that, we need to configure Vitest so it can run your tests. For this, create a separate vitest.config.ts so you don't have to modify your project's vite.config.ts:

// vitest.config.ts

import {defineConfig, mergeConfig} from "vitest/config";
import viteConfig from "./vite.config";

export default defineConfig((configEnv) =>
  mergeConfig(
    viteConfig(configEnv),
    defineConfig({
      // qwik-testing-library needs to consider your project as a Qwik lib
      // if it's already a Qwik lib, you can remove this section
      build: {
        target: "es2020",
        lib: {
          entry: "./src/index.ts",
          formats: ["es", "cjs"],
          fileName: (format, entryName) =>
            `${entryName}.qwik.${format === "es" ? "mjs" : "cjs"}`,
        },
      },
      // configure your test environment
      test: {
        environment: "jsdom",
        setupFiles: ["./vitest.setup.ts"],
        globals: true,
      },
    }),
  ),
);

For now, qwik-testing-library needs to consider your project as a lib (PR welcomed to simplify this). Hence, the build.lib section in the config above.

As the build will try to use ./src/index.ts as the entry point, we need to create it:

// ./src/index.ts

/**
 * DO NOT DELETE THIS FILE
 *
 * This entrypoint is needed by @noma.to/qwik-testing-library to run your tests
 */

Then, create the vitest.setup.ts file:

// vitest.setup.ts

import {afterEach} from "vitest";
import "@testing-library/jest-dom/vitest";

// This has to run before qdev.ts loads. `beforeAll` is too late
globalThis.qTest = false; // Forces Qwik to run as if it was in a Browser
globalThis.qRuntimeQrl = true;
globalThis.qDev = true;
globalThis.qInspector = false;

afterEach(async () => {
  const {cleanup} = await import("@noma.to/qwik-testing-library");
  cleanup();
});

This setup will make sure that Qwik is properly configured and that everything gets cleaned after each test.

Additionally, it loads @testing-library/jest-dom/vitest in your test runner so you can use matchers like expect(...).toBeInTheDocument().

Finally, edit your tsconfig.json to declare the following global types:

// tsconfig.json

{
  "compilerOptions": {
    "types": [
+     "vite/client",
+     "vitest/globals",
+     "@testing-library/jest-dom/vitest"
    ]
  },
  "include": ["src"]
}

Examples

Below are some examples of how to use @noma.to/qwik-testing-library to tests your Qwik components.

You can also learn more about the queries and user events over at the Testing Library website.

Qwikstart

This is a minimal setup to get you started, with line-by-line explanations.

// counter.spec.tsx

// import qwik-testing methods
import {screen, render, waitFor} from "@noma.to/qwik-testing-library";
// import the component to be tested
import {Counter} from "./counter";

// describe the test suite
describe("<Counter />", () => {
  // describe the test case
  it("should increment the counter", async () => {
    // render the component into the DOM
    await render(<Counter/>);

    // retrieve the 'increment count' button
    const incrementBtn = screen.getByRole("button", {name: /increment count/});
    // click the button twice
    await userEvent.click(incrementBtn);
    await userEvent.click(incrementBtn);

    // assert that the counter is now 2
    await waitFor(() => expect(screen.getByText(/count:2/)).toBeInTheDocument());
  });
})

Qwik City - server$ calls

If one of your Qwik components uses server$ calls, your tests might fail with a rather cryptic message (e.g. QWIK ERROR __vite_ssr_import_0__.myServerFunctionQrl is not a function or QWIK ERROR Failed to parse URL from ?qfunc=DNpotUma33o).

We're happy to discuss it on Discord, but we consider this failure to be a good thing: your components should be tested in isolation, so you will be forced to mock your server functions.

Here is an example of how to test a component that uses server$ calls:

// ~/server/blog-posts.ts

import {server$} from "@builder.io/qwik-city";
import {BlogPost} from "~/lib/blog-post";

export const getLatestPosts$ = server$(function (): Promise<BlogPost> {
  // get the latest posts
  return Promise.resolve([]);
});
// ~/components/latest-post-list.spec.tsx

import {render, screen, waitFor} from "@noma.to/qwik-testing-library";
import {LatestPostList} from "./latest-post-list";

vi.mock('~/server/blog-posts', () => ({
  // the mocked function should end with `Qrl` instead of `$`
  getLatestPostsQrl: () => {
    return Promise.resolve([{id: 'post-1', title: 'Post 1'}, {id: 'post-2', title: 'Post 2'}]);
  },
}));

describe('<LatestPostList />', () => {
  it('should render the latest posts', async () => {
    await render(<LatestPostList/>);

    await waitFor(() => expect(screen.queryAllByRole('listitem')).toHaveLength(2));
  });
});

Notice how the mocked function is ending with Qrl instead of $, despite being named as getLatestPosts$. This is caused by the Qwik optimizer renaming it to Qrl. So, we need to mock the Qrl function instead of the original $ one.

If your server$ function doesn't end with $, the Qwik optimizer might not rename it to Qrl.

Gotchas

  • Watch mode (at least in Webstorm) doesn't seem to work well: components are not being updated with your latest changes

Issues

Looking to contribute? Look for the Good First Issue label.

🐛 Bugs

Please file an issue for bugs, missing documentation, or unexpected behavior.

See Bugs

💡 Feature Requests

Please file an issue to suggest new features. Vote on feature requests by adding a 👍. This helps maintainers prioritize what to work on.

See Feature Requests

❓ Questions

For questions related to using the library, please visit a support community instead of filing an issue on GitHub.

Contributors

Thanks goes to these people (emoji key):

This project follows the all-contributors specification. Contributions of any kind welcome!

Acknowledgements

Massive thanks to the Qwik Team and the whole community for their efforts to build Qwik and for the inspiration on how to create a testing library for Qwik.

Thanks to the Testing Library Team for a great set of tools to build better products, confidently, and qwikly.