Skip to content

Commit

Permalink
Merge branch 'master' into import-transformers
Browse files Browse the repository at this point in the history
  • Loading branch information
SimenB committed Mar 7, 2021
2 parents f1844a0 + 3c679f1 commit fc0f616
Show file tree
Hide file tree
Showing 21 changed files with 150 additions and 117 deletions.
6 changes: 5 additions & 1 deletion CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@

### Features

- `[jest-changed-files]` Use '--' to separate paths from revisions ([#11160](https://github.com/facebook/jest/pull/11160))
- `[jest-circus]` [**BREAKING**] Fail tests when multiple `done()` calls are made ([#10624](https://github.com/facebook/jest/pull/10624))
- `[jest-circus, jest-jasmine2]` [**BREAKING**] Fail the test instead of just warning when describe returns a value ([#10947](https://github.com/facebook/jest/pull/10947))
- `[jest-config]` [**BREAKING**] Default to Node testing environment instead of browser (JSDOM) ([#9874](https://github.com/facebook/jest/pull/9874))
Expand Down Expand Up @@ -39,6 +40,7 @@
- `[jest-console]` `console.dir` now respects the second argument correctly ([#10638](https://github.com/facebook/jest/pull/10638))
- `[jest-core]` Don't report PerformanceObserver as open handle ([#11123](https://github.com/facebook/jest/pull/11123))
- `[jest-each]` [**BREAKING**] Ignore excess words in headings ([#8766](https://github.com/facebook/jest/pull/8766))
- `[jest-environment]` [**BREAKING**] Drop support for `runScript` for test environments ([#11155](https://github.com/facebook/jest/pull/11155))
- `[jest-environment-jsdom]` Use inner realm’s `ArrayBuffer` constructor ([#10885](https://github.com/facebook/jest/pull/10885))
- `[jest-globals]` [**BREAKING**] Disallow return values other than a `Promise` from hooks and tests ([#10512](https://github.com/facebook/jest/pull/10512))
- `[jest-globals]` [**BREAKING**] Disallow mixing a done callback and returning a `Promise` from hooks and tests ([#10512](https://github.com/facebook/jest/pull/10512))
Expand All @@ -59,6 +61,7 @@
- `[jest-transform]` [**BREAKING**] Refactor API of transformers to pass an options bag rather than separate `config` and other options ([#10834](https://github.com/facebook/jest/pull/10834))
- `[jest-worker]` [**BREAKING**] Use named exports ([#10623](https://github.com/facebook/jest/pull/10623))
- `[jest-worker]` Do not swallow errors during serialization ([#10984](https://github.com/facebook/jest/pull/10984))
- `[jest-worker]` Handle `ERR_IPC_CHANNEL_CLOSED` errors properly ([#11143](https://github.com/facebook/jest/pull/11143))
- `[pretty-format]` [**BREAKING**] Convert to ES Modules ([#10515](https://github.com/facebook/jest/pull/10515))
- `[pretty-format]` Only call `hasAttribute` if it's a function ([#11000](https://github.com/facebook/jest/pull/11000))

Expand All @@ -83,8 +86,9 @@
- `[jest-reporters]` [**BREAKING**] Make `node-notifier` a peer dependency ([#10977](https://github.com/facebook/jest/pull/10977))
- `[jest-resolve, jest-runtime]` [**BREAKING**] Use `Map`s instead of objects for all cached resources ([#10968](https://github.com/facebook/jest/pull/10968))
- `[jest-runner]` [**BREAKING**] Migrate to ESM ([#10900](https://github.com/facebook/jest/pull/10900))
- `[jest-runtime]` [**BREAKING**] Remove deprecated and unnused `getSourceMapInfo` from Runtime ([#9969](https://github.com/facebook/jest/pull/9969))
- `[jest-runtime]` [**BREAKING**] Remove deprecated and unused `getSourceMapInfo` from Runtime ([#9969](https://github.com/facebook/jest/pull/9969))
- `[jest-runtime]` Detect reexports from CJS as named exports in ESM ([#10988](https://github.com/facebook/jest/pull/10988))
- `[jest-transformer]` [**BREAKING**] Remove unused `isCoreModule` option ([#11166](https://github.com/facebook/jest/pull/11166))
- `[jest-util]` No longer checking `enumerable` when adding `process.domain` ([#10862](https://github.com/facebook/jest/pull/10862))
- `[jest-validate]` [**BREAKING**] Remove `recursiveBlacklist ` option in favor of previously introduced `recursiveDenylist` ([#10650](https://github.com/facebook/jest/pull/10650))

Expand Down
6 changes: 3 additions & 3 deletions docs/Configuration.md
Original file line number Diff line number Diff line change
Expand Up @@ -1030,7 +1030,7 @@ test('use jsdom in this test file', () => {
});
```

You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `runScript` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables.
You can create your own module that will be used for setting up the test environment. The module must export a class with `setup`, `teardown` and `getVmContext` methods. You can also pass variables from this module to your test suites by assigning them to `this.global` object – this will make them available in your test suites as global variables.

The class may optionally expose an asynchronous `handleTestEvent` method to bind to events fired by [`jest-circus`](https://github.com/facebook/jest/tree/master/packages/jest-circus). Normally, `jest-circus` test runner would pause until a promise returned from `handleTestEvent` gets fulfilled, **except for the next events**: `start_describe_definition`, `finish_describe_definition`, `add_hook`, `add_test` or `error` (for the up-to-date list you can look at [SyncEvent type in the types definitions](https://github.com/facebook/jest/tree/master/packages/jest-types/src/Circus.ts)). That is caused by backward compatibility reasons and `process.on('unhandledRejection', callback)` signature, but that usually should not be a problem for most of the use cases.

Expand Down Expand Up @@ -1076,8 +1076,8 @@ class CustomEnvironment extends NodeEnvironment {
await super.teardown();
}

runScript(script) {
return super.runScript(script);
getVmContext() {
return super.getVmContext();
}

async handleTestEvent(event, state) {
Expand Down
4 changes: 2 additions & 2 deletions docs/Puppeteer.md
Original file line number Diff line number Diff line change
Expand Up @@ -110,8 +110,8 @@ class PuppeteerEnvironment extends NodeEnvironment {
await super.teardown();
}

runScript(script) {
return super.runScript(script);
getVmContext() {
return super.getVmContext();
}
}

Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
// Jest Snapshot v1, https://goo.gl/fbAQLP

exports[`throw error if test env does not have getVmContext 1`] = `"Test environment found at \\"<rootDir>/EnvUsingRunScript.js\\" does not export a \\"getVmContext\\" method, which is mandatory from Jest 27. This method is a replacement for \\"runScript\\"."`;
10 changes: 9 additions & 1 deletion e2e/__tests__/jestChangedFiles.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,6 +44,10 @@ function gitInit(dir: string) {
run(initCommand, dir);
}

function gitCreateBranch(branchName: string, dir: string) {
run(`git branch ${branchName}`, dir);
}

beforeEach(() => cleanup(DIR));
afterEach(() => cleanup(DIR));

Expand Down Expand Up @@ -171,9 +175,11 @@ test('gets changed files for git', async () => {
gitInit(DIR);

const roots = [
'',
// same first root name with existing branch name makes pitfall that
// causes "ambiguous argument" git error.
'nested-dir',
'nested-dir/second-nested-dir',
'',
].map(filename => path.resolve(DIR, filename));

let {changedFiles: files} = await getChangedFilesForRoots(roots, {});
Expand All @@ -190,6 +196,8 @@ test('gets changed files for git', async () => {
// returns files and not parts of commit messages.
run(`${GIT} commit --no-gpg-sign -m "test" -m "extra-line"`, DIR);

gitCreateBranch('nested-dir', DIR);

({changedFiles: files} = await getChangedFilesForRoots(roots, {}));
expect(Array.from(files)).toEqual([]);

Expand Down
17 changes: 17 additions & 0 deletions e2e/__tests__/testEnvironmentRunScript.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/

import {resolve, sep} from 'path';
import runJest from '../runJest';

it('throw error if test env does not have getVmContext', () => {
const DIR = resolve(__dirname, '../test-environment-run-script');
const {exitCode, stderr} = runJest(DIR);

expect(stderr.replace(`${DIR}${sep}`, '<rootDir>/')).toMatchSnapshot();
expect(exitCode).toBe(1);
});
4 changes: 2 additions & 2 deletions e2e/test-environment-async/TestEnvironment.js
Original file line number Diff line number Diff line change
Expand Up @@ -34,8 +34,8 @@ class TestEnvironment extends JSDOMEnvironment {
});
}

runScript(script) {
return super.runScript(script);
getVmContext() {
return super.getVmContext();
}
}

Expand Down
14 changes: 14 additions & 0 deletions e2e/test-environment-run-script/EnvUsingRunScript.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

module.exports = class Env {
constructor() {
this.global = global;
this.moduleMocker = {};
}
};
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
/**
* Copyright (c) Facebook, Inc. and its affiliates. All Rights Reserved.
*
* This source code is licensed under the MIT license found in the
* LICENSE file in the root directory of this source tree.
*/
'use strict';

test('dummy', () => {
throw new Error('nothing to see here');
});
5 changes: 5 additions & 0 deletions e2e/test-environment-run-script/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "<rootDir>/EnvUsingRunScript.js"
}
}
4 changes: 2 additions & 2 deletions examples/mongodb/mongo-environment.js
Original file line number Diff line number Diff line change
Expand Up @@ -29,8 +29,8 @@ class MongoEnvironment extends NodeEnvironment {
await super.teardown();
}

runScript(script) {
return super.runScript(script);
getVmContext() {
return super.getVmContext();
}
}

Expand Down
28 changes: 18 additions & 10 deletions packages/jest-changed-files/src/git.ts
Original file line number Diff line number Diff line change
Expand Up @@ -44,7 +44,7 @@ const adapter: SCMAdapter = {

if (options && options.lastCommit) {
return findChangedFilesUsingCommand(
['show', '--name-only', '--pretty=format:', 'HEAD'].concat(
['show', '--name-only', '--pretty=format:', 'HEAD', '--'].concat(
includePaths,
),
cwd,
Expand All @@ -53,33 +53,41 @@ const adapter: SCMAdapter = {
if (changedSince) {
const [committed, staged, unstaged] = await Promise.all([
findChangedFilesUsingCommand(
['diff', '--name-only', `${changedSince}...HEAD`].concat(
['diff', '--name-only', `${changedSince}...HEAD`, '--'].concat(
includePaths,
),
cwd,
),
findChangedFilesUsingCommand(
['diff', '--cached', '--name-only'].concat(includePaths),
['diff', '--cached', '--name-only', '--'].concat(includePaths),
cwd,
),
findChangedFilesUsingCommand(
['ls-files', '--other', '--modified', '--exclude-standard'].concat(
includePaths,
),
[
'ls-files',
'--other',
'--modified',
'--exclude-standard',
'--',
].concat(includePaths),
cwd,
),
]);
return [...committed, ...staged, ...unstaged];
}
const [staged, unstaged] = await Promise.all([
findChangedFilesUsingCommand(
['diff', '--cached', '--name-only'].concat(includePaths),
['diff', '--cached', '--name-only', '--'].concat(includePaths),
cwd,
),
findChangedFilesUsingCommand(
['ls-files', '--other', '--modified', '--exclude-standard'].concat(
includePaths,
),
[
'ls-files',
'--other',
'--modified',
'--exclude-standard',
'--',
].concat(includePaths),
cwd,
),
]);
Expand Down
13 changes: 3 additions & 10 deletions packages/jest-environment-jsdom/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import type {Context, Script} from 'vm';
import type {Context} from 'vm';
import {JSDOM, VirtualConsole} from 'jsdom';
import type {EnvironmentContext, JestEnvironment} from '@jest/environment';
import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
Expand All @@ -30,12 +30,12 @@ class JSDOMEnvironment implements JestEnvironment {
errorEventListener: ((event: Event & {error: Error}) => void) | null;
moduleMocker: ModuleMocker | null;

constructor(config: Config.ProjectConfig, options: EnvironmentContext = {}) {
constructor(config: Config.ProjectConfig, options?: EnvironmentContext) {
this.dom = new JSDOM('<!DOCTYPE html>', {
pretendToBeVisual: true,
runScripts: 'dangerously',
url: config.testURL,
virtualConsole: new VirtualConsole().sendTo(options.console || console),
virtualConsole: new VirtualConsole().sendTo(options?.console || console),
...config.testEnvironmentOptions,
});
const global = (this.global = (this.dom.window.document
Expand Down Expand Up @@ -125,13 +125,6 @@ class JSDOMEnvironment implements JestEnvironment {
this.fakeTimersModern = null;
}

runScript<T = unknown>(script: Script): T | null {
if (this.dom) {
return script.runInContext(this.dom.getInternalVMContext());
}
return null;
}

getVmContext(): Context | null {
if (this.dom) {
return this.dom.getInternalVMContext();
Expand Down
11 changes: 1 addition & 10 deletions packages/jest-environment-node/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import {Context, Script, createContext, runInContext} from 'vm';
import {Context, createContext, runInContext} from 'vm';
import type {JestEnvironment} from '@jest/environment';
import {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import type {Config, Global} from '@jest/types';
Expand Down Expand Up @@ -104,15 +104,6 @@ class NodeEnvironment implements JestEnvironment {
this.fakeTimersModern = null;
}

// TS infers the return type to be `any`, since that's what `runInContext`
// returns.
runScript<T = unknown>(script: Script): T | null {
if (this.context) {
return script.runInContext(this.context);
}
return null;
}

getVmContext(): Context | null {
return this.context;
}
Expand Down
19 changes: 5 additions & 14 deletions packages/jest-environment/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
* LICENSE file in the root directory of this source tree.
*/

import type {Context, Script} from 'vm';
import type {Context} from 'vm';
import type {LegacyFakeTimers, ModernFakeTimers} from '@jest/fake-timers';
import type {Circus, Config, Global} from '@jest/types';
import type {
Expand All @@ -14,13 +14,11 @@ import type {
ModuleMocker,
} from 'jest-mock';

// In Jest 25, remove `Partial` since it's incorrect. The properties are always
// passed, or not. The context itself is optional, not properties within it.
export type EnvironmentContext = Partial<{
export type EnvironmentContext = {
console: Console;
docblockPragmas: Record<string, string | Array<string>>;
testPath: Config.Path;
}>;
};

// Different Order than https://nodejs.org/api/modules.html#modules_the_module_wrapper , however needs to be in the form [jest-transform]ScriptTransformer accepts
export type ModuleWrapper = (
Expand All @@ -40,17 +38,10 @@ export declare class JestEnvironment {
fakeTimers: LegacyFakeTimers<unknown> | null;
fakeTimersModern: ModernFakeTimers | null;
moduleMocker: ModuleMocker | null;
/**
* @deprecated implement getVmContext instead
*/
runScript<T = unknown>(script: Script): T | null;
getVmContext?(): Context | null;
getVmContext(): Context | null;
setup(): Promise<void>;
teardown(): Promise<void>;
handleTestEvent?(
event: Circus.Event,
state: Circus.State,
): void | Promise<void>;
handleTestEvent?: Circus.EventHandler;
}

export type Module = NodeModule;
Expand Down
8 changes: 8 additions & 0 deletions packages/jest-runner/src/runTest.ts
Original file line number Diff line number Diff line change
Expand Up @@ -144,6 +144,14 @@ async function runTestInternal(
docblockPragmas,
testPath: path,
});

if (typeof environment.getVmContext !== 'function') {
console.error(
`Test environment found at "${testEnvironment}" does not export a "getVmContext" method, which is mandatory from Jest 27. This method is a replacement for "runScript".`,
);
process.exit(1);
}

const leakDetector = config.detectLeaks
? new LeakDetector(environment)
: null;
Expand Down
Loading

0 comments on commit fc0f616

Please sign in to comment.