The optimal flow for Jest based testing in VS Code
MIT License
This extension supports full jest features in vscode environment to make testing more intuitive and fun. It should work out-of-the-box for most common jest projects. To get started:
If the extension can find the jest command, by default it will automatically run and monitor all tests in watch mode upon launch, and you should see tests, status, errors, coverage (if enabled) in TestExplorer and editors like this:
If you have a more sophisticated project configuration or prefer to run tests differently, fear not, the extension supports extensive customization settings. For example:
yarn test
instead of the default jest command.You can see the full features and learn more details in the How-To section. If you encounter an unexpected error, feel free to checkout the Troubleshooting or file an issue.
Happy testing!
All: Release Notes
Content
expect
function, as well as in the problem inspector.Simply open Visual Studio Code, go to the extension view and search for "Jest". Alternatively, open Jest - Visual Studio Marketplace and click "Install".
For detailed releases and migration help, please see releases.
This extension fully integrates with the VSCode testing framework, supporting both automatic and on-demand test runs. In addition to the standard VSCode Test Explorer interface, the extension provides additional UI elements to simplify the development workflow:
Dynamic Run Mode: Run mode dictates the overall user experience, determining when tests should run, with or without coverage, error display style, etc. Different run modes may have different performance implications, particularly for larger projects.
We realized that runMode preference could change even within a given project, for example developers prefer "watch" runMode when doing light code changes to ensure nothing breaks, may prefer the 'on-demand' mode during heavy test development for greater control over test execution. A static runMode config in "settings.json" is simply not sufficient. Therefore, we added the runMode quick switch so users can easily switch to different runMode without permanently modifying the "settings.json".
Interactive Test Run: Besides automatic test executions ("watch", "on-save"), users can initiate full test actions, such as run, debug, update/view snapshot, from both editor and Test Explorer through various UI components.
Test Output: The extension offers native jest run outputs in both the "TERMINAL" and "TEST RESULTS" panel. "TEST RESULTS" panel mainly displays test run output in execution order, while "TERMINAL" groups test output by workspace folder/virtual-folder, and also includes extension configuration details, quick-fix suggestions, etc. By default, the output appears when tests run, but this can be adjusted via the outputConfig setting.
Extension Status: Upon successful launch of the extension, the status bar shows the run status for the active folder, and the aggregated test status for the whole workspace. Clicking on each status reveals the associated output window.
Hopefully, you don't have to do anything. If you can run jest from the terminal, you should be able to use this extension.
The extension will try to auto-config a jest command and debug config when needed. If the auto-config fails, or any non-test error occurred, users should see an quick-fix-chooser link in the output terminal to help resolving the issues.
For more details see the setup tool and the complete customization options in settings.
To adjust the runMode during your current session:
Click on the runMode buttons referenced in the User Interface section. This action will prompt a runMode chooser.
Within the chooser, you can swiftly switch the runMode type, toggle coverage, opt for deferred mode, or directly edit the runMode within an editor.
Note: Changes to runMode using the UI will apply only to the ongoing session. Upon restarting the extension or reloading the window, the runMode will revert to the value in settings.json. However, you can write the current runMode value to settings.json
with command: "Jest: Save Current RunMode"
via command palette.
For an in-depth understanding of each type and the available options, refer to runMode.
By default, the extension uses jest watch mode that automatically runs tests upon related file changes. In addition, users can also trigger individual tests/suites on-demand:
Jest: Run All Tests
Jest: Run Related Tests
The extension will try to auto-config a jest runner, if it fails, you can try the quick-fix-chooser.
There are 2 ways to debug a specific test:
The extension will try to generate a debug config, but if you encounter a debug error or want to change the configuration, please see Customization - Debug Config.
v6.3.0 and up
Test coverage can also be run interactively via the TestExplorer tree view, by clicking the "Run with Coverage" button.
v6.2.5 and below
[!Note] Note: The following describes the original test coverage feature, which remains available as of 2024/08/13. With the introduction of the new, more intuitive integration in v6.3.0, we plan to deprecate this feature soon. If you have any concerns or would like to share your thoughts on this change, please let us know.
Code coverage can be triggered via
The coverage stats will be displayed at the source code editor: summary at the top and inline coverage indicator based on the formatter selected.
To verify the coverage mode is on, one can check the runMode chooser or the status bar (see how to read the status bar)
Note: this extension supports both babel
and v8
coverageProviders. However, please note the coverage might not be exactly the same, see facebook/jest#11188 for more details.
In addition to the coverage summary that is shown on the top of the file, each line will be marked by its coverage status according to the coverage formatter configured. There are 3 types of coverage you might see in your source code, distinguished by colors:
You can customize coverage start up behavior, style and colors, see customization for more details.
Users can update snapshots in any granularity from the context menu:
Snapshots are now fully supported for parameterized (test.each
) and template-literal named tests.
The extension supports monorepo projects with the following mechanisms:
"jest.disabledWorkspaceFolders"
to exclude the packages from jest run.For option 1 and 2, the easiest way to setup the monorepo projects is to use the Setup Tool and choose Setup monorepo project.
Please note, a working jest environment is a prerequisite for this extension. If you are having problem running the tests from a terminal, please follow jest instruction to set it up first.
StatusBar shows 2 types of information, illustrated below:
Jest (folder-name)
: shows the mode and state of the "active" workspace folder or virtual folder (based on the active editor). As the hovering text showed, the "active" folder "react-ts" is in "watch" mode with coverage on.Jest-WS
: shows the total test suite stats (pass, failed, unknown) for the whole workspace. Unknown test suites usually mean the test files are not yet run.Hovering over the status items will show tooltips with descriptions; clicking on the items open the corresponding output window.
Upon non-test errors, such as jest command not found, the extension can help user fix common errors with quick fix:
cmd + click
on the quick fix link in the output terminal will open a quick-fix chooser.jest.jestCommandLine
, jest.rootPath
, monorepo settings, etc. This action will open the setup tools to continue."jest.enable": false
in the .vscode/settings.json
file.It is sometimes helpful to see the actual command and shell environment spawned, as well as internal debug messages, to diagnose issues:
"jest.debugMode": true
in .vscode/settings.json
Help > Toggle Developer Tools
menu), for example, to examine the PATH environment variables: look for the "spawn" log, expand the "options" object, expand the "env" property, all env variables (inherited from vscode process) should be there (view animation).Users can use the following settings to tailor the extension for their environments.
jest
and saved in standard .vscode/settings.json
.setting | description | default | example/notes | available |
---|---|---|---|---|
Process | ||||
jestCommandLine | The command line to start jest tests | undefined |
"jest.jestCommandLine": "npm test --" or "jest.jestCommandLine": "yarn test" or "jest.jestCommandLine": "node_modules/.bin/jest --config custom-config.js"
|
|
rootPath | The path to your frontend src folder | "" |
"jest.rootPath":"packages/app" or "jest.rootPath":"/apps/my-app"
|
|
nodeEnv | Add additional env variables to spawned jest process | null | "jest.nodeEnv": {"PORT": "9800", "BAR":"true"} |
|
shell | shell (path or LoginShell) for executing jest | null |
"jest.shell": "/bin/bash" or "jest.shell": "powershell" or "jest.shell": {"path": "/bin/bash"; args: ["--login"]}
|
|
useDashedArgs | Determine if to use dashed arguments for jest processes | undefined | "jest.useDashedArgs":true |
>= v6.0.0 |
parserPluginOptions | Configure babel parser plugins | null | "jest.parserPluginOptions": {decorators: 'legacy'} |
|
virtualFolders | defines multiple jest runs in a given vscode workspace folder | undefined | "jest.virtualFolders": "[{"name": "front-end", "rootPath': "packages/front-end"}, {"name": "back-end", "rootPath': "packages/back-end"} ]" |
>= v6.0.0 |
useJest30 | instruct the extension to use jest 30 command line syntax | undefined | "jest.useJest30": true |
>= v6.3.0 |
UX | ||||
outputConfig 💼 | Controls test output experience across the whole workspace. | undefined |
"jest.outputConfig": "neutral" or "jest.outputConfig": {"revealOn": "run", "revealWithFocus": "terminal", "clearOnRun": 'terminal"
|
>= v6.1.0 |
runMode | Controls most test UX, including when tests should be run, output management, etc | undefined |
"jest.runMode": "watch" or "jest.runMode": "on-demand" or "jest.runMode": {"type": "on-demand", "deferred": true}
|
>= v6.1.0 |
❌ autoClearTerminal | Clear the terminal output at the start of any new test run. | false | "jest.autoClearTerminal": true |
v6.0.0 (replaced by outputConfig) |
❌ testExplorer | Configure jest test explorer | null | {"showInlineError": "true"} |
< 6.1.0 (replaced by runMode) |
❌ autoRun | Controls when and what tests should be run | undefined |
"jest.autoRun": "off" or "jest.autoRun": "watch" or "jest.autoRun": {"watch": false, "onSave":"test-only"}
|
< v6.1.0 (replaced by runMode) |
❌ autoRevealOutput | Determine when to show test output | "on-run" | "jest.autoRevealOutput": "on-exec-error" |
< v6.1.0 (replaced by outputConfig) |
Coverage | ||||
❌ showCoverageOnLoad | Show code coverage when extension starts | false | "jest.showCoverageOnLoad": true |
< v6.1.0 (replaced by runMode) |
coverageFormatter | Determine the coverage overlay style | "DefaultFormatter" | "jest.coverageFormatter": "GutterFormatter" |
|
coverageColors | Coverage indicator color override | undefined | "jest.coverageColors": { "uncovered": "rgba(255,99,71, 0.2)", "partially-covered": "rgba(255,215,0, 0.2)"} |
|
Misc | ||||
enable | Enable/disable jest extension for the given workspace folder/virtual-folder | true | "jest.enable": false |
>=6.0.0 |
disabledWorkspaceFolders 💼 | Disabled workspace folders names in multi-root environment | [] | "jest.disabledWorkspaceFolders": ["package-a", "package-b"] |
|
debugMode | Enable debug mode to diagnose plugin issues. (see developer console) | false | "jest.debugMode": true |
|
monitorLongRun | monitor long running tests based on given threshold in ms | 60000 | "jest.monitorLongRun": 120000 |
This should be the command users used to kick off the jest tests in the terminal. However, since the extension will append additional options at run time, please make sure the command line can pass along these options, which usually just means if you uses npm, add an additional "--" at the end (e.g. "npm run test --"
) if you haven't already in your script.
It is recommended not to add the following options as they are managed by the extension: --watch
, --watchAll
, --coverage
If your project doesn't live in the root of your repository, you may want to customize the jest.rootPath
setting to enlighten the extension as to where to look. For instance: "jest.rootPath": "src/client-app"
will direct the extension to use the src/client-app
folder as the root for Jest.
There are 2 formatters to choose from:
(Note, there is an known issue in vscode (microsoft/vscode#5923) that gutter decorators could interfere with debug breakpoints visibility. Therefore, you probably want to disable coverage before debugging or switch to DefaultFormatter)
Besides the formatter, user can also customize the color via jest.coverageColors
to change color for 3 coverage categories: "uncovered", "covered", or "partially-covered"
,
for example:
"jest.coverageColors": {
"uncovered": "rgba(255,99,71, 0.2)",
"partially-covered": "rgba(255,215,0, 0.2)",
}
the default color scheme below, note the opacity might differ per formatter:
"jest.coverageColors": {
"covered": "rgba(9, 156, 65, 0.4)",
"uncovered": "rgba(121, 31, 10, 0.4)",
"partially-covered": "rgba(235, 198, 52, 0.4)",
}
The outputConfig
controls the Jest output experience by specifying when and where to create, display, and clear the output content. It supports 2 output panels: TEST RESULTS
and TERMINAL
. The TEST RESULTS
panel displays test results in the order they were run, while the TERMINAL
panel organizes outputs by workspace folder. TERMINAL
panel also contains the non-test run outputs, such as quick-fix link, extension auto-config info, and tips.
Type Definitions
// typescript type definition
export interface JestRawOutputSetting {
revealOn?: 'run' | 'error' | 'demand';
revealWithFocus?: 'terminal' | 'test-results' | 'none';
clearOnRun?: 'both' | 'terminal' | 'test-results' | 'none';
}
export type JestPredefinedOutputSetting = 'neutral' | 'terminal-based' | 'test-results-based';
export type JestOutputSetting = JestPredefinedOutputSetting | JestRawOutputSetting;
JestOutputSetting This setting can be one of the predefined types or a custom object.
Predefined OutputConfig Settings (JestPredefinedOutputSetting):
Predefined outputConfig | Description | JestRawOutputSetting |
---|---|---|
"neutral" | A passive setting that does not favor either panel | {revealOn: "run", revealWithFocus: "none", clearOnRun: "none"} |
"terminal-based" | A terminal-centric output experience | {revealOn: "run", revealWithFocus: "terminal", clearOnRun: "none"} |
"test-results-based" | A test-results-centric output experience | {revealOn: "run", revealWithFocus: "test-results", clearOnRun: "none"} |
Custom Config Object (JestRawOutputSetting):
Handling Conflicts with "TEST RESULTS" panel setting
The Problem
The behavior of the "TEST RESULTS" panel is influenced by VSCode's native "testing.openTesting"
setting. This can cause inconsistencies with your "jest.outputConfig"
settings.
For instance, if you set "jest.outputConfig": {"revealWithFocus": "none"}
to prevent automatic focus changes, but leave "testing.openTesting"
at its default value of "openOnTestStart"
, the "TEST RESULTS" panel will still automatically switch focus when the tests are run via UI.
The Universal Solution
For a consistent Jest output experience, the simplest solution is to set "testing.openTesting": "neverOpen"
. This allows the extension to manage the "TEST RESULTS" and "TERMINAL" panels together using "jest.outputConfig"
alone.
Further Customization
However, if you prefer "TEST RESULTS" and "TERMINAL" panels to behave differently and don't mind managing 2 settings yourself, you could play with different combinations.
For instance, if "testing.openTesting"
is set to "openOnTestFailure"
, and you want your terminal panel to still reveal when any tests run, your setting would look like this: "jest.outputConfig": {revealWithFocus: "terminal"}
.
Validation and Diagnosis
The extension features output config diagnosis information in the jest terminal, as well as the built-in conflict detection and quick fixes to assist with the transition.
Default Output Focus Behavior by RunMode
When none of the output settings ("testing.openTesting"
and "jest.outputConfig"
) are present, The default output behavior is determined by runMode:
runMode | auto reveal "TEST RESULTS" | auto reveal "TERMINAL" |
---|---|---|
"watch" | ✖️ | ✖️ |
"on-save" | ✖️ | ✖️ |
"on-demand" | ✔️ | ✖️ |
Configuration Examples
"testing.openTesting": "neverOpen",
"jest.outputConfig": "neutral"
"testing.openTesting": "neverOpen",
"jest.outputConfig": "terminal-based"
"testing.openTesting": "neverOpen",
"jest.outputConfig": {
"revealOn": "error",
"revealWithFocus": "test-results",
}
"testing.openTesting": "neverOpen",
"jest.outputConfig": {
"clearOnRun": "terminal"
}
[!NOTE] Migration Guide
Migrating to the new
"jest.outputConfig"
might require some manual adjustments, especially if you're working in a multi-root workspace. Here are some guidelines to help with the transition:
Workspace Level vs Workspace-Folder Level: The new
"jest.outputConfig"
is a workspace-level setting, unlike legacy settings like"jest.autoClearTerminal"
and"jest.autoRevealOutput"
, which are workspace-folder level settings.Backward Compatibility: If no
"jest.outputConfig"
is defined in your settings.json, the extension will attempt to generate a backward-compatible outputConfig in memory. This uses the"testing.openTesting"
setting and any legacy settings ("jest.autoClearTerminal"
,"jest.autoRevealOutput"
) you might have. Note that this might only work for single-root workspaces.Customization Steps: In general it should work out of the box, but if you encounter any issues, here are some steps to help adjusting the output behavior:
- Use the
"Jest: Save Current Output Config"
command from the command palette to update your settings.json. Then adjust it to fit your needs.- Fix warning if any: The save does not include
"testing.openTesting"
, so you might see the conflict warning message. You can either use the "Quick Fix" action or adjust thesettings.json
manually (see handling conflict).- Finally, remove any deprecated settings.
By following these guidelines, you should be able to smoothly transition to using
"jest.outputConfig"
.
The runMode
controls test UX, determining when tests should run, and housing the common run-time toggles like coverage.
Type Definitions
// typescript types
interface JestRunModeOptions {
runAllTestsOnStartup?: boolean;
coverage?: boolean;
deferred?: boolean;
showInlineError?: boolean;
}
export type JestRunMode = JestRunModeOptions & (
| { type: 'watch' }
| { type: 'on-demand' }
| { type: 'on-save'; testFileOnly?: boolean }
);
JestRunMode: Here's what each type does:
JestRunModeOptions: Options applicable for all runMode
types:
runAllTestsOnStartup: Want to run all tests as soon as the extension starts? Use this.
coverage: To get those coverage metrics, turn this on.
deferred: Usually, the extension sets things up before any test run, verifying the Jest env and discovering tests. This process is generally quick, but if you've got a hefty project or your setup isn't Jest-ready, this option helps:
true
: Suspend the initial setup. Most UI components remain active. If you toggle runMode.deferred
or manually trigger a test run, the setup will resume, deferred option will be set to false, and the runMode will operate as usual.false
: Default behavior, the setup process gets going before any test run.📌 Note: There's a distinction between the deferred mode and disabling the extension via "jest.enable: false". Disabling the extension will remove all test features for the given workspace-folder. In contrast, deferred just delays the setup but most UI features are still visible.
Predefined RunMode
The following are the predefined runMode
configurations for convenience. They are mapped to the specified JestRunMode
type at run time.
Predefined runMode | Description | JestRunMode |
---|---|---|
"watch" | run tests by watchman | {type: "watch"} |
"on-save" | run tests when test or source files are saved | {type: "on-save"} |
"on-demand" | run tests on-demand through UI | {type: "on-demand"} |
"deferred" | defer test run and discovery until the first on-demand run | {type: "on-demand", deferred: true} |
Examples
"jest.runMode": "watch"
"jest.runMode": "on-demand"
"jest.runMode": "deferred"
"jest.runMode": {
"type": "on-save",
"testFileOnly": true,
"coverage": true
}
"jest.runMode": {
"type": "on-save",
"deferred": true
}
runMode performance tradeoff
Balancing performance, convenience and completeness is often challenging. The runMode offers a tool to fine-tune this equilibrium according to your preferences.
While the concepts of performance and automation are generally clear, "completeness" may require some elaboration:
[!NOTE] Migration Guide
Starting from v6.1.0, if no runMode is defined in settings.json, the extension will automatically generate one using legacy settings (
autoRun
,showCoverageOnLoad
). To migrate, simply use the"Jest: Save Current RunMode"
command from the command palette to update the setting, then remove the deprecated settings.
[!WARNING] As of v6.1.0, autoRun will be replaced by runMode. For transition details, please refer to the runMode migration.
AutoRun controls when tests should be executed automatically.
Performance and automation/completeness are often a trade-off. autoRun is the tool to fine-tune the balance, which is unique for every project and user.
Performance and automation are self-explanatory, "completeness" might not:
There are 2 ways to change autoRun:
settings.json
file.autoRun Configuration
AutoRun =
| "watch" | "off" | "legacy" | "on-save"
| { watch: true, onStartup?: ["all-tests"] }
| {
watch: false,
onStartup?: ["all-tests"],
onSave?: "test-file" | "test-src-file",
}
The string type are short-hand for the most common configurations:
Short Hand | description | actual config | note |
---|---|---|---|
"watch" | run jest in watch mode | {"watch": true} | the default mode |
"off" | turn off jest autoRun | {"watch": false} | this is the manual mode |
"legacy" | starting a full test-run followed by jest watch | {"watch": true, "onStartup": ["all-tests"]} | he default mode prior to v4.7 |
"on-save" | run jest upon source or test file changes | {"watch": false, "onSave": "test-src-file"} |
User can also pass the actual config in the .vscode/settings.json
, see more example below.
Turn off auto run, users need to trigger tests run manually via run commands or context menu:
"jest.autoRun": "off"
Run all the tests in the workspace upon extension startup, followed by jest watch run for subsequent test/src file changes.
"jest.autoRun": "legacy"
or
"jest.autoRun": {
"watch": true,
"onStartup": ["all-tests"]
}
Only run tests in the test file when the test file itself changes. It will neither run all tests for the workspace upon startup nor trigger any test run when the source file changes.
"jest.autoRun": {
"watch": false,
"onSave": "test-file"
}
Like the one above but does run all tests upon extension start up
"jest.autoRun": {
"watch": false,
"onSave": "test-file",
"onStartup": ["all-tests"]
}
Please note, even when the autoRun
is "off", the extension will still perform the usual setup upon start-up, such as checking jest env and parsing test blocks, so users can run test blocks manually. To turn off the extension completely for the given workspace, you can use jest.enable
setting instead.
[!WARNING] As of v6.1.0, this setting has been folded into runMode. For transition details, please refer to the runMode migration.
testExplorer = {showInlineError?: boolean}
showInlineError
: (optional) show vscode style inline error and error message viewer. Default is false.shell = string | LoginShell;
interface LoginShell
{
path: string;
args: string[];
}
By default, jest command is executed in default shell ('cmd' for windows, '/bin/sh' for non-windows). Users can use the "jest.shell"
setting to either pass the path of another shell (e.g. "/bin/zsh") or a LoginShell config, e.g. {"path": "/bin/bash", "args": ["--login"]}
)
Note the LoginShell is only applicable for non-windows platform and could cause a bit more overhead.
Auto recovery with login shell
Since v5, if detected shell env issue, such as node: command not found
or npm: no such file or directory
, the extension will fallback to a login shell to ensure tests can run correctly. If will try to auto generate a login shell configuration based on the jest.shell
setting, otherwise, it will use the default bash
login-shell. Currently supported auto-fallback shells are bash
, zsh
, fish
.
monitorLongRun = number | 'off'
Default is "jest.monitorLongRun":60000
(1 minute)
[!WARNING] As of v6.1.0, this setting has been folded into outputConfig. For transition details, please refer to the outputConfig migration.
autoRevealOutput = "on-run" | "on-exec-error" | "off"
on-run
: reveal test run output when test run started.on-exec-error
: reveal test run output only when execution error (note, not test error) occurred.off
: no auto reveal test output. Note this could mask critical error, check status bar status for detail.parserPluginOptions = { decorators?:
| 'legacy'
| {
decoratorsBeforeExport?: boolean;
allowCallParenthesized?: boolean;
}
}
This extension uses babel to parse the test files. For decorators plugin options, it uses 'decorators', {decoratorsBeforeExport: true}
by default, which can be customized with this setting. Examples:
"jest.parserPluginOptions": {"decorators": "legacy"}
"jest.parserPluginOptions": {"decorators": {"decoratorsBeforeExport": false}}
Much like a vscode workspace folder, which manages a runtime environment for a specific folder, a virtualFolder manages a custom Jest runtime environment. Each virtualFolder can have its own resource-level settings, such as jestCommandLine
and rootPath
.
You can configure multiple virtual folders within any given vscode workspace folder using the jest.virtualFolders
setting. Here are a few common use cases and examples:
Your project contains multiple jest configurations, such as unit test and integration test. While they run on the same set of source files, you want to run them separately and with different frequency: for instance, unit tests should always run automatically ("runMode": "watch") while the integration tests should only run on-demand ("runMode": "on-demand"):
// settings.json for unit and integration test environments under the root folder:
{
"jest.virtualFolders": [
{"name": "unit-tests", "jestCommandLine": "yarn test --config jest.unit.config.js", "runMode": "watch"},
{"name": "integration-tests", "jestCommandLine": "yarn test --config jest.integration.config.js", "runMode": "on-demand"}
]
}
Your project is a monorepo and you want to run tests for each package separately. You can configure a virtual folder for each package:
// settings.json for a monorepo project under the root folder:
{
"jest.virtualFolders": [
{"name": "package1", "rootPath": "packages/package1"},
{"name": "package2", "rootPath": "packages/package2"}
]
}
Virtual Folders Inherit and Override Workspace Folder Settings Virtual folders inherit settings from the parent workspace but can override these settings as needed. For instance, you can set the runMode to "watch" in the workspace, but set it to "on-demand" for the virtual folders with many or expensive tests. This flexibility allows for granular control over the testing environments within a single workspace folder.
// settings.json in the "project" folder
{
...
"jest.runMode": "watch",
"jest.jestCommandLine": "yarn test",
"jest.virtualFolders": [
{"name": "unit-tests"},
{"name": "integration-tests", , "runMode": "on-demand", "jestCommandLine": "yarn test --config=jest.integration.config.js"}
]
}
In this scenario, the "project" workspace will not run its own Jest environment but will instead spawn two separate Jest environments for "unit-tests" and "integration-tests".
VirtualFolders vs. Multi-root Workspace While virtual folders are primarily designed to address the gap of supporting multiple test configurations for the same set of source files, they are also capable of supporting monorepo projects. Some developers might prefer this approach over traditional multi-root workspaces due to the simplified and centralized settings over individual package settings.
However, there are some key differences between virtual folders and multi-root workspaces to consider:
.vscode/settings.json
(like in a multi-root workspace), then you are probably better off continue with multi-root workspace.This extension looks for jest specific debug config ("vscode-jest-tests.[folder-name]"
or "vscode-jest-tests.v2.[folder-name]"
) in the following order:
.vscode/launch.json
.xxx.code-workspace
, if existsThe generated config should work for most standard jest or projects bootstrapped by create-react-app
, however it might fall short for more sophisticated projects. Please use the setup tool to help you configure or edit the launch.json
file manually.
There are many information online about how to setup vscode debug config for specific environments/frameworks, you might find the following helpful:
v4.3 introduces a "variable substitution" based config with name "vscode-jest-tests.v2.[folder-name]"
. The extension will merely substitute the jest variables in the config, without adding/removing anything else.
Currently supported variables:
--testPathPattern
.{
"type": "node",
"name": "vscode-jest-tests.v2",
"request": "launch",
"program": "${workspaceFolder}/node_modules/.bin/jest",
"args": [
"--runInBand",
"--watchAll=false",
"--testNamePattern",
"${jest.testNamePattern}",
"--runTestsByPath",
"${jest.testFile}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true,
"windows": {
"program": "${workspaceFolder}/node_modules/jest/bin/jest"
}
}
{
"type": "node",
"name": "vscode-jest-tests.v2",
"request": "launch",
"runtimeExecutable": "yarn",
"args": [
"test",
"--run-in-band",
"--watch-all=false",
"--test-name-pattern",
"${jest.testNamePattern}",
"--test-path-pattern",
"${jest.testFilePattern}"
],
"cwd": "${workspaceFolder}",
"console": "integratedTerminal",
"internalConsoleOptions": "neverOpen",
"disableOptimisticBPs": true
}
This extension contributes the following commands and can be accessed via Command Palette:
command | description | availability |
---|---|---|
Jest: Start All Runners | start or restart all jest runners | always |
Jest: Stop All Runners | stop all jest runners | always |
Jest: Toggle Coverage | toggle coverage mode for all runners | always |
Jest: Start Runner (Select Workspace) | start or restart the jest runner for the selected workspace | multi-root workspace |
Jest: Stop Runner (Select Workspace) | stop jest runner for the selected workspace | multi-root workspace |
Jest: Toggle Coverage (Select Workspace) | toggle coverage mode for the selected workspace | multi-root workspace |
Jest: Run All Tests | run all tests for all the workspaces | always |
Jest: Run All Tests (Select Workspace) | run all tests for the selected workspace | multi-root workspace |
Jest: Run All Tests in Current Workspace | run all tests for the current workspace based on the active editor | always |
Jest: Toggle Coverage for Current Workspace | toggle coverage mode for the current workspace based on the active editor | always |
Jest: Save Current RunMode | update "jest.runMode" in settings.json based on the current value |
always (>= 6.1.0) |
Jest: Save Current Output Config | update "jest.outputConfig" in settings.json based on the current value |
always (>= 6.1.0) |
Jest: Setup Extension | start the setup tool | always |
In addition, TestExplorer also exposed many handy commands, see the full list by searching for testing
in vscode keyboard shortcuts editor. One can assign/change keyboard shortcut to any of these commands, see vscode Key Bindings for more details.
User can trigger the following action from the text editor context-menu
menu | description | keyboard shortcut |
---|---|---|
Jest: Run Related Tests | if in test file, run all tests in the file; if in source file, run all tests with dependency to the file | Ctrl-Option-t (Mac) or Ctrl-Alt-t |
Please see vscode Key Bindings if you want to change the keyboard shortcut.
Sorry you are having trouble with the extension. If your issue did not get resolved after checking out the how-to section and the tips below, feel free to ask the community, chances are some one else had a similar experience and could help resolving it.
If you can't run jest in the terminal, please reference jest configuration to setup accordingly.
If you can run jest manually in the terminal but the extension showed error like "xxx ended unexpectedly", following are the most common causes (see self-diagnosis if you need more debug info):
yarn test
but the extension uses the default jest
instead.
yarn test
or npm run test --
. The extension can auto-config common configurations like create react apps but not custom scripts like CRACO.Feel free to try the quick-fix chooser, or check out the customization section to manually adjust the extension.
A few known failure scenarios:
The extension should be a thin wrapper on top of the jest process, i.e., it shouldn't use much more resources than the jest process itself.
Having said that, we have definitely seen sluggish performance for some projects/users. The short answer is try changing runMode in the explorer, which should usually show noticeable improvement.
The long answer is a bit more complicated:
This should only happen in Linux or MacOS, and is due to vscode not able to fully initialize the shell env when it starts up (more details here).
you can instruct vscode debugger to use a login shell via task/debug profile, for example, adding the following in your user's settings then restart:
"terminal.integrated.automationProfile.osx": {
"args": ["-l"],
"path": "/bin/bash"
},
Alternatively, you can try the following methods if you prefer a non-login-shell solution:
code
from your external terminalThis means the extension is not activated.
vscode will automatically activate the extension upon detecting any of the following patterns:
jest.json
, jest.config.js
, jest.config.ts
, jest.config.mjs
, jest.config.cjs
, jest.config.json
) any where under the project root.node_modules/.bin/jest
, node_modules/react-scripts/node_modules/.bin/jest
) or react-native script (node_modules/react-native-scripts
) under the project root.If none of the auto activation criteria is met, you can do the following to manually activate the extension:
.vscode-jest
file at your actual project root."Jest: Start All Runners"
will also activate the extension for the current vscode process.The extension monitor excessive test run with "jest.monitorLongRun" setting. By default if any runs exceed 60 seconds, a warning message will be shown.
If running the tests with the extension seems to be longer than running it from a terminal, chances are you can use "jest.runMode" to optimize it, for example:
runMode
.If the tests are slow even from the terminal, i.e. without the extension, you will need to optimize your tests, feel free to check out jest troubleshooting or other online articles.
If the run appeared to hang, i.e. the TestExplorer or statusBar showed test running when it is not. It might be related to this jest issue, which should be fixed after release 29.0.2
. If you believe your issue is different, please file a new issue so we can take a look.
You can also turn off the monitor or change the threshold with "jest.monitorLongRun" to meet your needs.
If your test file happen to have parameterized tests, i.e. test.each
variations, please make sure you have jest version >= 26.5.
If the above did not resolve your issue, please see the self-diagnosis to show more insight of why the test and result could not be matched.
Thanks for considering! Check here for useful tips and guidelines.
vscode-jest is MIT licensed.