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

supplejs-testing-library

v1.1.0

Published

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

Downloads

2

Readme

Inspired completely by solid-testing-library and preact-testing-library

NPM Version GitHub License Build Status codecov


Table of Contents


The Problem

You want to write tests for your Solid components so that they avoid including implementation details, and are maintainable in the long run.

The Solution

The Solid Testing Library is a very lightweight solution for testing Solid components. 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 supplejs-testing-library

💡 If you are using Jest or vitest, you may also be interested in installing @testing-library/jest-dom so you can use the custom jest matchers.

Integration with Vite

A working Vite template setup with supplejs-testing-library and TypeScript support can be found here.

Docs

See the docs for preact-testing-library over at the Testing Library website. supplejs-testing-library is pretty similar.

There are several key differences, though:

render

⚠️ The render function takes in a function that returns a SuppleJS Component, rather than simply the component itself.

// With @testing-library/preact
const results = render(<YourComponent />, options);
// With supplejs-testing-library
const results = render(() => <YourComponent />, options);

⚠️ SuppleJS does not re-render, it merely executes side effects triggered by reactive states that change the DOM, therefore there is no rerender method. You can use global signals to manipulate your test component in a way that causes it to update.

SuppleJS reactive changes are pretty instantaneous, so there is rarely need to use waitFor(…), await findByRole(…) and other asynchronous queries to test the rendered result, except for suspense, resources, lazy loaded components, some effects (createEffect, createDeferred, onMount) and error boundaries.

renderHook

⚠️ SuppleJS external reactive state does not require any DOM elements to run in, so our renderHook call to test hooks in the context of a component (if your hook does not require the context of a component, createRoot should suffice to test the reactive behavior; for convenience, we also have testEffect, which is described later) has no container, baseElement or queries in its options or return value. Instead, it has an owner to be used with runWithOwner if required. It also exposes a cleanup function, though this is already automatically called after the test is finished.

function renderHook<Args extends any[], Result>(
  hook: (...args: Args) => Result,
  options: {
    initialProps?: Args,
    wrapper?: Component<{ children: JSX.Element }>
  }
) => {
  result: Result;
  owner: Owner | null;
  cleanup: () => void;
}

This can be used to easily test a hook / primitive:

const { result } = renderHook(createResult);
expect(result).toBe(true);

If you are using a wrapper with renderHook, make sure it will always return props.children - especially if you are using a context with asynchronous code together with <Show>, because this is required to get the value from the hook and it is only obtained synchronously once and you will otherwise only get undefined and wonder why this is the case.

testEffect

SuppleJS manages side effects with different variants of createEffect. While you can use waitFor to test asynchronous effects, it uses polling instead of allowing Solid's reactivity to trigger the next step. In order to simplify testing those asynchronous effects, we have a testEffect helper that complements the hooks for directives and hooks:

testEffect(fn: (done: (result: T) => void) => void, owner?: Owner): Promise<T>

// use it like this:
test("testEffect allows testing an effect asynchronously", () => {
  const [v, setValue] = createSignal(0);
  const value = createDeferred(v);
  return testEffect((done) =>
    createEffect((run: number = 0) => {
      if (run === 0) {
        expect(value()).toBe(0);
        setValue(1);
      } else if (run === 1) {
        expect(value()).toBe(1);
        done();
      }
      return run + 1;
    })
  );
});

It allows running the effect inside a defined owner that is received as an optional second argument. This can be useful in combination with renderHook, which gives you an owner field in its result. The return value is a Promise with the value given to the done() callback. You can either await the result for further assertions or return it to your test runner.

cleanup

The cleanup function cleans-up any rendered context. It is installed automatically when afterEach is globally available (as is the case when using option globals: true in vitest config).

If you don't want to set globals: true, it is possible to manually install the cleanup function in a setup file.

// vitest-setup.ts
import { afterEach } from "vitest";
import { cleanup } from "supplejs-testing-library";

afterEach(() => cleanup());

// vite.config.ts
export default defineConfig({
    test: {
        setupFiles: ["vitest-setup.ts"],
    },
});

Acknowledgement

Thanks goes to Kent C. Dodds and his colleagues for creating testing-library and to the creators of solid-testing-library.