Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Run Jest against LWC components in SFDX workspace environment

License

NotificationsYou must be signed in to change notification settings

salesforce/sfdx-lwc-jest

Repository files navigation

Run Jest against Lightning web components in a Salesforce DX workspace environment.

Versions

To test against the latest Salesforce production instances, use the npm tag appropriate for the current release, e.g.:

yarn add -D @salesforce/sfdx-lwc-jest@winter22yarn add -D @salesforce/sfdx-lwc-jest@spring22

The npmlatest tag corresponds to the latest version of this repo, not necessarily Salesforce production versions.

To see a full list of available versions, and the tag that maps to the corresponding Salesforce release, seethe list ofnpm package versions.

Installation

Add this project as a devDependency:

yarn add -D @salesforce/sfdx-lwc-jest

Update your project's unit testing script inpackage.json to executesfdx-lwc-jest:

{"scripts": {"test:unit":"sfdx-lwc-jest","test:unit:watch":"sfdx-lwc-jest --watch","test:unit:debug":"sfdx-lwc-jest --debug","test:unit:coverage":"sfdx-lwc-jest --coverage"    }}

test:unit runs all your tests.test:unit:watch andtest:unit:debug run Jest in watch and debug mode (see below).

Alternatively, you can globally install the package and run directly from the command line.

Usage

`sfdx-lwc-jest [options]` runs Jest unit tests in SFDX workspaceOptions:      --version              Show version number                       [boolean]      --coverage             Collect coverage and display in output                                                      [boolean] [default: false]  -u, --updateSnapshot       Re-record every snapshot that fails during a test                             run                      [boolean] [default: false]      --verbose              Display individual test results with the test suite                             hierarchy                [boolean] [default: false]      --watch                Watch files for changes and rerun tests related to                             changed files            [boolean] [default: false]      --debug                Run tests in debug mode                             (https://jestjs.io/docs/en/troubleshooting)                                                      [boolean] [default: false]      --help                 Show help                                 [boolean]Examples:  sfdx-lwc-jest --coverage  Collect coverage and display in output  sfdx-lwc-jest -- --json   All params after `--` are directly passed to Jest

Passing Additional Jest CLI Options

To pass any additional Jest CLI options to your run, pass them after the-- flag. All CLI parameters after the flag are passed directly to Jest.

sfdx-lwc-jest -- --json

See theJest documentation for all CLI options.

Debug Mode

Debug mode lets you easily debug your Jest tests.

  • Put adebugger; into your code
  • Openchrome://inspect
  • Runsfdx-lwc-jest with the--debug flag.

Pass other parameters to Jest after the-- flag. For example,

sfdx-lwc-jest --debug -- --no-cache

Debugging in Visual Studio Code

If you prefer to debug inside Visual Studio Code, follow these steps:

  • From the Visual Studio Code dropdowns, select Debug > Add Configuration....
  • If you're prompted for an Environment choose any value.
  • Mac users, replace the contents of the generatedlaunch.json with the following. (for Windows users see theJest website for launch.json contents).
{"version":"0.2.0","configurations": [        {"name":"Debug Jest Tests","type":"node","request":"launch","runtimeArgs": ["--inspect-brk","${workspaceRoot}/node_modules/.bin/jest","--runInBand"            ],"console":"integratedTerminal","internalConsoleOptions":"neverOpen","port":9229        }    ]}
  • Add ajest.config.js file to the root of the Salesforce DX project as describedhere. You must add this file to run Jest from Visual Studio Code.
  • To run tests, press F5 or select Debug > Start Debugging.

Watch Mode

Watch mode causes Jest to monitor files for changes and rerun tests related to the changed files. This is a great way to rapidly make component and test changes while monitoring tests results.

Overriding Jest Config

sfdx-lwc-jest sets up all the necessary Jestconfigs for you to run tests out of the box without any additional changes. To override any options or set additional ones, create a file calledjest.config.js at the root of your Salesforce DX project, import the default config fromsfdx-lwc-jest, modify as you please, and then export the new config.

const{ jestConfig}=require('@salesforce/sfdx-lwc-jest/config');module.exports={    ...jestConfig,// add any custom configurations here};

Resolving External Lightning Web Components

If a Lightning web component isn't located in the locallwc directory of your Salesforce DX project, you must mock it in your Jest tests. This package includes a set of stubs for all components in thelightning namespace.

Lightning Namespaced Component Stubs

This package installs stubs for thelightning base components to thesrc/lightning-stubs directory. These stubs are used automatically when running tests throughsfdx-lwc-jest. To override the default stub provided for your project, override themoduleNameMapper config as described inOther Component Mocks.

Other Component Mocks

For components from other namespaces, not in your locallwc directory, create your own mock and update the Jest config to map the name of these components to the mock file.

Let's go through an example. We want to test the following template,helloWorld.html.

<template>    Hello From a Lightning Web Component!<lightning-buttononclick="{doSomething}"></lightning-button><foo-fancy-buttononclick="{doSomethingElse}"></foo-fancy-button></template>

Because it's in thelightning namespace, thelightning-button just works. However, you must write some code to help the Jest resolver find thefoo-fancy-button component. First, create ajest.config.js file at the root of the Salesforce DX project workspace and add the following:

const{ jestConfig}=require('@salesforce/sfdx-lwc-jest/config');module.exports={    ...jestConfig,moduleNameMapper:{'^foo/fancyButton$':'<rootDir>/force-app/test/jest-mocks/foo/fancyButton',},};

This config tells Jest to map the import forfoo-fancy-button to the provided file. Notice that the first dash is converted to a forward slash and the rest of the component name goes from kebab to camel case. The reason for the forward slash is because the module resolver treats everything before the first dash as the namespace. Here,<rootDir> maps to the root of the Salesforce DX workspace. Note that this file location is not required, just an example.

You also have the freedom to make these mock implementations as sophisticated or simple as you'd like. In this example, we'll keepfoo-fancy-button simple with an empty template and no functionality in the.js file, but you can always add whatever markup you'd like or implement functionality like any other Lightning web component.

Finally, we need to create the mockfoo-fancy-button files. In theforce-app/test/jest-mocks/foo directory create the following files:

<!-- fancyButton.html --><template></template>
// fancyButton.jsimport{LightningElement,api}from'lwc';exportdefaultclassFancyButtonextendsLightningElement{    @apilabel;// any other implementation you may want to expose here}

Testing @wire Adapters

To provision data through@wire adapters in unit tests, use the APIs provided by@salesforce/wire-service-jest-util. These APIs are exposed through this package so you do not need to include another dependency in your package.json.

See the@salesforce/wire-service-jest-utilREADME for further documentation on these APIs.

About

Run Jest against LWC components in SFDX workspace environment

Topics

Resources

License

Code of conduct

Security policy

Stars

Watchers

Forks

Packages

No packages published

Contributors39


[8]ページ先頭

©2009-2025 Movatter.jp