Skip to content

Commit

Permalink
added nodeEnv and shell settings to customize jest process runner
Browse files Browse the repository at this point in the history
  • Loading branch information
connectdotz committed Sep 29, 2021
1 parent cebc7e8 commit aa6351d
Show file tree
Hide file tree
Showing 6 changed files with 72 additions and 16 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ Please add your own contribution below inside the Master section
## Master
* brief change description - @author
* expose test file parse result to TestExplorer so the status indicators and test item menu are accessible for all run modes. - @connectdotz
* added `jest.nodeEnv` and `jest.shell` settings to override default jest process env/shell - @connectdotz
-->

### 4.1.2
Expand Down
33 changes: 20 additions & 13 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -151,7 +151,7 @@ Note: other than the "off" mode, users can specify the "onStartup" option for an

A test can be debugged via the debug codeLens appeared above the [debuggable](#debugcodelensshowwhenteststatein) tests. Simply clicking on the codeLens will launch vscode debugger for the specific test. The extension also supports parameterized tests and allows users to pick the specific parameter set to debug.

The simplest use cases should be supported out-of-the-box. If VS Code displays errors about the attribute `program` or `runtimeExecutable` not being available, you can either use [setup wizard]() to help or create your own debug configuration within `launch.json`. See more details in [Customization - Debug Config](#debug-config).
The simplest use cases should be supported out-of-the-box. If VS Code displays errors about the attribute `program` or `runtimeExecutable` not being available, you can either use [setup wizard](setup-wizard.md) to help or create your own debug configuration within `launch.json`. See more details in [Customization - Debug Config](#debug-config).

<details>
<summary>Illustration</summary>
Expand Down Expand Up @@ -244,6 +244,8 @@ Users can use the following settings to tailor the extension for their environme
|**Process**|
|autoEnable :x:|Automatically start Jest for this project|true|Please use `autoRun` instead|
|[jestCommandLine](#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"`|
|nodeEnv|Add additional env variables to spawned jest process|null|`"jest.nodeEnv": {"PORT": "9800", "BAR":"true"}` |
|shell|Custom shell (path) for jest process|null|`"jest.shell": "/bin/bash"` or `"jest.shell": "powershell"` |
|[autoRun](#autorun)|Controls when and what tests should be run|undefined|`"jest.autoRun": "off"` or `"jest.autoRun": {"watch": true, "onStartup": ["all-tests"]}` or `"jest.autoRun": false, onSave:"test-only"}`|
|pathToJest :x:|The path to the Jest binary, or an npm/yarn command to run tests|undefined|Please use `jestCommandLine` instead|
|pathToConfig :x:|The path to your Jest configuration file"|""|Please use `jestCommandLine` instead|
Expand Down Expand Up @@ -285,12 +287,12 @@ Possible status are: `[ "fail", "pass", "skip", "unknown"]`. Please note that th

There are 2 formatters to choose from:
1. <details><summary> DefaultFormatter: high light uncovered and partially-covered code inlilne as well as on the right overview ruler. (this is the default)</summary>

![coverage-DefaultFormatter.png](./images/coverage-DefaultFormatter.png)
</details>

1. <details><summary>GutterFormatter: render coverage status in the gutter as well as the overview ruler.</summary>

![coverage-GutterFormatter.png](./images/coverage-GutterFormatter.png)
</details>

Expand Down Expand Up @@ -427,7 +429,7 @@ Please see [vscode Key Bindings](https://code.visualstudio.com/docs/getstarted/k


## Troubleshooting
Sorry you are having trouble with the extension. If your issue did not get resolved after checking out the [how-to](#how-to-use-the-extension) section and the tips below, feel free to [ask](https://github.com/jest-community/vscode-jest/issues) the community, chances are some one else had a similar experience and could help resolving it.
Sorry you are having trouble with the extension. If your issue did not get resolved after checking out the [how-to](#how-to-use-the-extension) section and the tips below (click arrows to expand), feel free to [ask](https://github.com/jest-community/vscode-jest/issues) the community, chances are some one else had a similar experience and could help resolving it.

<details>
<summary>I don't see "Jest" in the bottom status bar</summary>
Expand All @@ -439,15 +441,18 @@ Sorry you are having trouble with the extension. If your issue did not get resol
<details>
<summary>I got "Jest Process xxx failed unexpectedly..." or "Jest failed too many times..." error message</summary>

This usually mean the extension is not able to start jest process for you. First check the Jest OUTPUT channel or developer console to see what is the actual error (see [self-diagnosis](#self-diagnosis)).
This usually means the extension is not able to start jest process for you. First check the TestExplorer Output, Jest OUTPUT channel or developer console to see what is the actual error (see [self-diagnosis](#self-diagnosis)).

If it is related to the run time environment, such as
```
env: node: No such file or directory
```
The issue is probably not related to this extension. If this only happened occasionally after launch or you saw vscode warning about shell start up slow, try to simplified the env files, restart vscode or reload windows. See [Resolving Shell Environment is Slow](https://code.visualstudio.com/docs/supporting/faq#_resolving-shell-environment-is-slow-error-warning).

If you see error about not able to find `jest` or some other jest related runtime error: if you can run jest from terminal then you can use the **"Run Setup Wizard"** button in the error panel to help resolving the configuration issue, see [Setup Wizard](setup-wizard.md) for more details. There could be other causes, such as jest test root path is different from the project's, which can be fixed by setting [jest.rootPath](#rootPath). Feel free to check out the [customization](#customization) section to manually adjust the extension if needed.
Most likely the child_process environment is not correctly initialized. There are many possible causes, sometimes restarting vscode will fix it, otherwise feel free to check out a more in-depth explanation/suggestion [here](https://github.com/jest-community/vscode-jest/issues/741#issuecomment-921222851).

If you see error about not able to find `jest` or some other jest related runtime error: if you can run jest from terminal then you can use the **"Run Setup Wizard"** button in the error panel to help resolving the configuration issue, see [Setup Wizard](setup-wizard.md). If jest doesn't even run from the terminal, then please reference [jest](https://jestjs.io/docs/configuration) to set up your jest test environment.

There could be other causes, such as jest test root path is different from the project's, which can be fixed by setting [jest.rootPath](#rootPath). Feel free to check out the [customization](#customization) section to manually adjust the extension if needed.
</details>

<details>
Expand All @@ -469,13 +474,15 @@ If the above did not resolve your issue, please see the [self-diagnosis](#self-d
<summary><a id='self-diagnosis'></a>The extension is not behaving as expected, what is going on? (try self diagnosis)</summary>

If your can execute jest tests on command line but vscode-jest was not running as expected, here is what you can do to find out more information:
- See jest process output in the "OUTPUT" channel, which is usually named after the workspace folder, such as `Jest (your-workspace-name)`. Or you can click on `Jest` label on status bar to show Jest Output window. This will show you the jest run output and the errors.
<img src="https://github.com/jest-community/vscode-jest/raw/master/images/output-channel.png" alt="Screenshot of the tool" width="100%">

- Turn on the debug mode to see more internal debugging message:
- You can see jest process output with either one of the methods:
- If you uses TestExplorer, you can see color coded jest output from the TestExplorer's Output terminal (the square arrow icon on the top of the Explorer View)
- Otherwise you can see the output in "OUTPUT" channel, which is usually named after the workspace folder, such as `Jest (your-workspace-name)`. Or you can click on `Jest` label on status bar to show Jest Output window. This will show you the jest run output and the errors.
<img src="https://github.com/jest-community/vscode-jest/raw/master/images/output-channel.png" alt="Screenshot of the tool" width="100%">

- See additional logging from the developer console (via `Help > Toggle Developer Tools` menu), for example to examine the environment variables passed to jest runner: [examine-env.git](https://github.com/jest-community/vscode-jest/blob/master/images/vscode-jest-env-log.gif)

- Turn on the debug mode to see more internal debugging message in the developer console:
- set `"jest.debugMode": true` in `.vscode/settings.json`
- restart vscode-jest or reload the window (via `Reload Window` command)
- open the developer tool (via `Help > Toggle Developer Tools` menu), you should see more information including how we extract jest config and spawn jest processes.

Hopefully most issues would be pretty obvious after seeing these extra output, and you can probably fix most yourself by [customizing](#customization) the `jest.jestCommandLine` and others.
</details>
Expand Down
18 changes: 18 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,24 @@
"default": "",
"scope": "resource"
},
"jest.nodeEnv": {
"markdownDescription": "The env passed to runner process in addtion to `process.env`",
"type": [
"object",
"null"
],
"default": null,
"scope": "resource"
},
"jest.shell": {
"markdownDescription": "The shell path to override jest runner process default shell (see Node [child_process.spawn()](https://nodejs.org/api/child_process.html#child_process_child_process_spawn_command_args_options)) for more detail)",
"type": [
"string",
"null"
],
"default": null,
"scope": "resource"
},
"jest.enableSnapshotUpdateMessages": {
"description": "Whether snapshot update messages should show",
"type": "boolean",
Expand Down
13 changes: 11 additions & 2 deletions src/JestExt/helper.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,12 @@ import * as vscode from 'vscode';
import * as path from 'path';
import { ProjectWorkspace } from 'jest-editor-support';
import { JestProcessRequest } from '../JestProcessManagement';
import { PluginResourceSettings, JestExtAutoRunConfig, TestExplorerConfig } from '../Settings';
import {
PluginResourceSettings,
JestExtAutoRunConfig,
TestExplorerConfig,
NodeEnv,
} from '../Settings';
import { AutoRunMode } from '../StatusBar';
import { pathToJest, pathToConfig, toFilePath } from '../helpers';
import { workspaceLogging } from '../logging';
Expand Down Expand Up @@ -87,7 +92,9 @@ export const createJestExtContext = (
currentJestVersion,
workspaceFolder.name,
settings.showCoverageOnLoad,
settings.debugMode
settings.debugMode,
settings.nodeEnv,
settings.shell
);
return {
workspace: workspaceFolder,
Expand Down Expand Up @@ -118,6 +125,8 @@ export const getExtensionResourceSettings = (uri: vscode.Uri): PluginResourceSet
coverageColors: config.get<CoverageColors>('coverageColors'),
autoRun: config.get<JestExtAutoRunConfig>('autoRun'),
testExplorer: config.get<TestExplorerConfig>('testExplorer') ?? { enabled: true },
nodeEnv: config.get<NodeEnv | null>('nodeEnv') ?? undefined,
shell: config.get<string | null>('shell') ?? undefined,
};
};

Expand Down
4 changes: 4 additions & 0 deletions src/Settings/index.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import { TestState } from '../DebugCodeLens';
import { CoverageColors } from '../Coverage/CoverageOverlay';
import { ProjectWorkspace } from 'jest-editor-support';

export type JestTestProcessType =
| 'all-tests'
Expand All @@ -25,6 +26,7 @@ export type JestExtAutoRunConfig =
export type TestExplorerConfig =
| { enabled: false }
| { enabled: true; showClassicStatus?: boolean; showInlineError?: boolean };
export type NodeEnv = ProjectWorkspace['nodeEnv'];
export interface PluginResourceSettings {
autoEnable?: boolean;
enableSnapshotUpdateMessages?: boolean;
Expand All @@ -40,6 +42,8 @@ export interface PluginResourceSettings {
coverageColors?: CoverageColors;
autoRun?: JestExtAutoRunConfig;
testExplorer: TestExplorerConfig;
nodeEnv?: NodeEnv;
shell?: string;
}

export interface PluginWindowSettings {
Expand Down
19 changes: 18 additions & 1 deletion tests/JestExt/helper.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -118,7 +118,9 @@ describe('isWatchRequest', () => {
});

describe('getExtensionResourceSettings()', () => {
let userSettings: any;
beforeEach(() => {
userSettings = {};
vscode.workspace.getConfiguration = jest.fn().mockImplementation((section) => {
const data = readFileSync('./package.json');
const config = JSON.parse(data.toString()).contributes.configuration.properties;
Expand All @@ -131,7 +133,9 @@ describe('getExtensionResourceSettings()', () => {
}

return {
get: jest.fn().mockImplementation((key) => defaults[`${section}.${key}`]),
get: jest
.fn()
.mockImplementation((key) => userSettings[key] ?? defaults[`${section}.${key}`]),
};
});
});
Expand All @@ -154,4 +158,17 @@ describe('getExtensionResourceSettings()', () => {
testExplorer: { enabled: true },
});
});
it('can read user settings', () => {
userSettings = {
testExplorer: { enable: false },
nodeEnv: { whatever: '1' },
shell: '/bin/bash',
};
const uri: any = { fsPath: 'workspaceFolder1' };
expect(getExtensionResourceSettings(uri)).toEqual(
expect.objectContaining({
...userSettings,
})
);
});
});

0 comments on commit aa6351d

Please sign in to comment.