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

@lwc/jest-preset

v16.0.0

Published

Jest preset configuration and stubs to help test LWC

Downloads

280,406

Readme

@lwc/jest-preset

Tools to assist with testing Lightning Web Components (LWC) with Jest. This project provides: two jest presets covering project's base Jest configuration for testing Lightning web components rendered on the DOM/Server, and stubs for common external libraries used in Lightning web components.

Usage

Installation

yarn add --dev @lwc/jest-preset @lwc/compiler @lwc/engine-dom @lwc/engine-server @lwc/synthetic-shadow

If your project is using Jest 28 and above, you will also need install jest-environment-jsdom separately:

yarn add --dev jest-environment-jsdom

Configuration

@lwc/jest-preset comes with two presets: @lwc/jest-preset (default) and @lwc/jest-preset/ssr used to test how a LWC component renders on the dom, and the server.

Testing LWC components rendered on the DOM

To test how LWC components render in the DOM, add the @lwc/jest-preset preset to your jest configuration:

{
    "preset": "@lwc/jest-preset"
}

Then, update the moduleNameMapper entry of the Jest config to point to where your LWC components live. For example, use the following to map all components in the example and other namespaces:

{
    "preset": "@lwc/jest-preset",
    "moduleNameMapper": {
        "^(example|other)/(.+)$": "<rootDir>/src/test/modules/$1/$2/$2"
    }
}
nativeShadow

By default, this preset is configured to run the tests with synthetic shadow DOM. Optionally, you can configure @lwc/jest-preset to use native shadow DOM rather than synthetic shadow DOM. To do so, add the following to jest.config.js:

{
    "globals": {
        "lwc-jest": {
            "nativeShadow": true
        }
    }
}

LWC components rendered on the Server

Add the @lwc/jest-preset/ssr preset to the Jest configuration like so:

{
    "preset": "@lwc/jest-preset/ssr"
}

LWC DOM and SSR component test setup

Jest config only allows one preset per configuration. In order to allow client and server jest tests to live alongside, you might consider creating a new configuration.

Example: Use jest.config.js for DOM tests (@lwc/jest-preset) and create jest-ssr.config.js for server tests (@lwc/jest-preset/ssr); then add a test:unit:ssr script to your package.json to run jest with the --config option

{
    "scripts": {
        "test:unit": "jest",
        "test:unit:ssr": "jest --config=jest-ssr.config.js"
    }
}

jest.config.js (DOM tests):

module.exports = {
    preset: '@lwc/jest-preset',
    moduleNameMapper: {
        '^(example|other)/(.+)$': '<rootDir>/src/test/modules/$1/$2/$2',
    },
};

jest-ssr.config.js (SSR tests):

module.exports = {
    preset: '@lwc/jest-preset/ssr',
    moduleNameMapper: {
        '^(example|other)/(.+)$': '<rootDir>/src/test/modules/$1/$2/$2',
    },
};

Testing

Create a __tests__ inside the bundle of the LWC component under test.

Then, create a new test file in __tests__ that follows the naming convention <js-file-under-test>.test.js for DOM tests and <js-file-under-test>.ssr-test.js for ssr tests. See an example in this projects src/test directory.

Now you can write and run the Jest tests!

Custom matchers

This package contains convenience functions to help test web components, including Lightning Web Components.

Note that, for these matchers to work properly in TypeScript, you must import this package from your *.spec.ts files:

import '@lwc/jest-preset';

expect().toThrowInConnectedCallback

Allows you to test for an error thrown by the connectedCallback of a web component. connectedCallback does not necessarily throw errors synchronously, so this utility makes it easier to test for connectedCallback errors.

Example
// Component
export default class Throws extends LightningElement {
    connectedCallback() {
        throw new Error('whee!');
    }
}
// Test
import { createElement } from 'lwc';

it('Should throw in connectedCallback', () => {
    const element = createElement('x-throws', { is: Throws });
    expect(() => {
        document.body.appendChild(element);
    }).toThrowErrorInConnectedCallback(/whee!/);
});
Error matching

The argument passed in to toThrowInConnectedCallback behaves the same as for Jest's built-in toThrow:

  • Regular expression: error message matches the pattern.
  • String: error message includes the substring.
  • Error object: error message is equal to the message property of the object.
  • Error class: error object is instance of class.
Best practices

Note that, to avoid false positives, you should try to include only the document.body.appendChild call inside of your callback; otherwise you could get a false positive:

expect(() => {
    document.body.appendChild(elm);
    throw new Error('false positive!');
}).toThrowInConnectedCallback();

The above Error will be successfully caught by toThrowInConnectedCallback, even though it doesn't really occur in the connectedCallback.

Web component support

This matcher works both with LWC components and with non-LWC custom elements that use standard connectedCallback semantics (e.g. Lit or vanilla).

It also works with LWC components regardless of whether they use the standard connectedCallback or the legacy synthetic lifecycle connectedCallback.

expect().toThrowErrorInConnectedCallback

Equivalent to toThrowInConnectedCallback.