Skip to content

Commit

Permalink
Merge pull request #4357 from woss/add-node-env-config-to-heft-jest-p…
Browse files Browse the repository at this point in the history
…lugin

[heft-jest-plugin] set NODE_ENV if not already set
  • Loading branch information
iclanton authored Oct 25, 2023
2 parents 2440730 + 5c3b57e commit 33000e1
Show file tree
Hide file tree
Showing 3 changed files with 53 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"changes": [
{
"packageName": "@rushstack/heft-jest-plugin",
"comment": "Add an option (`enableNodeEnvManagement`) to ensure that the NODE_ENV environment variable is set to `\"test\"` during test execution.",
"type": "patch"
}
],
"packageName": "@rushstack/heft-jest-plugin"
}
42 changes: 38 additions & 4 deletions heft-plugins/heft-jest-plugin/src/JestPlugin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -101,6 +101,7 @@ export interface IJestPluginOptions {
detectOpenHandles?: boolean;
disableCodeCoverage?: boolean;
disableConfigurationModuleResolution?: boolean;
enableNodeEnvManagement?: boolean;
findRelatedTests?: string[];
maxWorkers?: string;
passWithNoTests?: boolean;
Expand Down Expand Up @@ -153,6 +154,7 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
private _jestOutputStream: TerminalWritableStream | undefined;
private _changedFiles: Set<string> = new Set();
private _requestRun!: () => void;
private _nodeEnvSet: boolean | undefined;

private _resolveFirstRunQueued!: () => void;
private _firstRunQueuedPromise: Promise<void>;
Expand Down Expand Up @@ -210,7 +212,7 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
const testTimeoutParameter: CommandLineIntegerParameter =
parameters.getIntegerParameter('--test-timeout-ms');

const combinedOptions: IJestPluginOptions = {
const options: IJestPluginOptions = {
...pluginOptions,
configurationPath: configParameter.value || pluginOptions?.configurationPath,
debugHeftReporter: debugHeftReporterParameter.value || pluginOptions?.debugHeftReporter,
Expand All @@ -228,11 +230,12 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
testPathIgnorePatterns: testPathIgnorePatternsParameter.value || pluginOptions?.testPathIgnorePatterns,
testPathPattern: testPathPatternParameter.value || pluginOptions?.testPathPattern,
testTimeout: testTimeoutParameter.value ?? pluginOptions?.testTimeout,
updateSnapshots: updateSnapshotsParameter.value || pluginOptions?.updateSnapshots
updateSnapshots: updateSnapshotsParameter.value || pluginOptions?.updateSnapshots,
enableNodeEnvManagement: pluginOptions?.enableNodeEnvManagement ?? true
};

taskSession.hooks.run.tapPromise(PLUGIN_NAME, async (runOptions: IHeftTaskRunHookOptions) => {
await this._runJestAsync(taskSession, heftConfiguration, combinedOptions);
await this._runJestAsync(taskSession, heftConfiguration, options);
});

taskSession.hooks.runIncremental.tapPromise(
Expand All @@ -241,7 +244,7 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
await this._runJestWatchAsync(
taskSession,
heftConfiguration,
combinedOptions,
options,
runIncrementalOptions.requestRun
);
}
Expand All @@ -259,6 +262,8 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
const logger: IScopedLogger = taskSession.logger;
const terminal: ITerminal = logger.terminal;

this._setNodeEnvIfRequested(options, logger);

const { getVersion, runCLI } = await import(`@jest/core`);
terminal.writeLine(`Using Jest version ${getVersion()}`);

Expand All @@ -281,6 +286,8 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
results: jestResults
} = await runCLI(jestArgv, [buildFolderPath]);

this._resetNodeEnv();

if (jestResults.numFailedTests > 0) {
logger.emitError(
new Error(
Expand Down Expand Up @@ -491,6 +498,8 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
await Promise.resolve();

if (pendingTestRuns.size > 0) {
this._setNodeEnvIfRequested(options, logger);

this._executing = true;
for (const pendingTestRun of pendingTestRuns) {
pendingTestRuns.delete(pendingTestRun);
Expand All @@ -516,6 +525,8 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
}
}

this._resetNodeEnv();

if (!logger.hasErrors) {
// If we ran tests and they succeeded, consider the files to no longer be changed.
// This might be overly-permissive, but there isn't a great way to identify if the changes
Expand Down Expand Up @@ -790,6 +801,29 @@ export default class JestPlugin implements IHeftTaskPlugin<IJestPluginOptions> {
return JestPlugin._jestConfigurationFileLoader;
}

private _setNodeEnvIfRequested(options: IJestPluginOptions, logger: IScopedLogger): void {
if (options.enableNodeEnvManagement) {
if (process.env.NODE_ENV) {
if (process.env.NODE_ENV !== 'test') {
// In the future, we may consider just setting this and not warning
logger.emitWarning(
new Error(`NODE_ENV variable is set and it's not "test". NODE_ENV=${process.env.NODE_ENV}`)
);
}
} else {
process.env.NODE_ENV = 'test';
this._nodeEnvSet = true;
}
}
}

private _resetNodeEnv(): void {
// unset the NODE_ENV only if we have set it
if (this._nodeEnvSet) {
delete process.env.NODE_ENV;
}
}

private static _extractHeftJestReporters(
taskSession: IHeftTaskSession,
heftConfiguration: HeftConfiguration,
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,6 +11,11 @@
"title": "Disable Configuration Module Resolution",
"description": "If set to true, modules specified in the Jest configuration will be resolved using Jest default (rootDir-relative) resolution. Otherwise, modules will be resolved using Node module resolution.",
"type": "boolean"
},
"enableNodeEnvManagement": {
"title": "Enable management of the NODE_ENV variable",
"description": "If set to false, heft-jest-plugin will not set or unset the NODE_ENV variable. Otherwise, NODE_ENV will be set to `test` before execution and cleared after. If the NODE_ENV value is already set to a value that is not `test`, warning message appears.",
"type": "boolean"
}
}
}

0 comments on commit 33000e1

Please sign in to comment.