Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: add @jest/globals package for importing globals explicitly #9801

Merged
merged 6 commits into from
Apr 12, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@

### Features

- `[@jest/globals]` New package so Jest's globals can be explicitly imported ([#9801](https://github.com/facebook/jest/pull/9801))

### Fixes

- `[expect]` Restore support for passing functions to `toHaveLength` matcher ([#9796](https://github.com/facebook/jest/pull/9796))
Expand Down
2 changes: 1 addition & 1 deletion docs/GlobalAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ id: api
title: Globals
---

In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them.
In your test files, Jest puts each of these methods and objects into the global environment. You don't have to require or import anything to use them. However, if you prefer explicit imports, you can do `import {describe, expect, it} from '@jest/globals'`.

## Methods

Expand Down
2 changes: 1 addition & 1 deletion docs/JestObjectAPI.md
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ id: jest-object
title: The Jest Object
---

The `jest` object is automatically in scope within every test file. The methods in the `jest` object help create mocks and let you control Jest's overall behavior.
The `jest` object is automatically in scope within every test file. The methods in the `jest` object help create mocks and let you control Jest's overall behavior. It can also be imported explicitly by via `import {jest} from '@jest/globals'`.

## Mock Modules

Expand Down
13 changes: 13 additions & 0 deletions e2e/__tests__/importedGlobals.test.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,13 @@
/**
* 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 runJest from '../runJest';

test('imported globals', () => {
const result = runJest('imported-globals');
expect(result.exitCode).toBe(0);
});
22 changes: 22 additions & 0 deletions e2e/imported-globals/__tests__/env.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
/**
* 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 {
expect as importedExpect,
jest as importedJest,
test as importedTest,
} from '@jest/globals';

importedTest('they match the globals', () => {
importedExpect(importedExpect).toBe(expect);
importedExpect(importedJest).toBe(jest);
importedExpect(importedTest).toBe(test);

expect(importedExpect).toBe(expect);
expect(importedJest).toBe(jest);
expect(importedTest).toBe(test);
});
8 changes: 8 additions & 0 deletions e2e/imported-globals/babel.config.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,8 @@
/**
* 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.
*/

module.exports = require('../../babel.config');
5 changes: 5 additions & 0 deletions e2e/imported-globals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
{
"jest": {
"testEnvironment": "node"
}
}
15 changes: 7 additions & 8 deletions packages/jest-circus/src/legacy-code-todo-rewrite/jestAdapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,8 @@ import type {TestResult} from '@jest/test-result';
import type {RuntimeType as Runtime} from 'jest-runtime';
import type {SnapshotStateType} from 'jest-snapshot';

const FRAMEWORK_INITIALIZER = require.resolve('./jestAdapterInit');
const FRAMEWORK_INITIALIZER = path.resolve(__dirname, './jestAdapterInit.js');
const EXPECT_INITIALIZER = path.resolve(__dirname, './jestExpect.js');
Copy link
Member Author

@SimenB SimenB Apr 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

changes not related, just some local cleanup from looking into not adding the globals to the global env. Went with a simpler solution, but I liked these refactorings 🤷


const jestAdapter = async (
globalConfig: Config.GlobalConfig,
Expand All @@ -24,15 +25,13 @@ const jestAdapter = async (
const {
initialize,
runAndTransformResultsToJestFormat,
} = runtime.requireInternalModule(FRAMEWORK_INITIALIZER);
} = runtime.requireInternalModule<typeof import('./jestAdapterInit')>(
FRAMEWORK_INITIALIZER,
);

runtime
.requireInternalModule<typeof import('./jestExpect')>(
path.resolve(__dirname, './jestExpect.js'),
)
.default({
expand: globalConfig.expand,
});
.requireInternalModule<typeof import('./jestExpect')>(EXPECT_INITIALIZER)
.default({expand: globalConfig.expand});

const getPrettier = () =>
config.prettierPath ? require(config.prettierPath) : null;
Expand Down
5 changes: 5 additions & 0 deletions packages/jest-globals/.npmignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
**/__mocks__/**
**/__tests__/**
src
tsconfig.json
tsconfig.tsbuildinfo
30 changes: 30 additions & 0 deletions packages/jest-globals/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,30 @@
{
"name": "@jest/globals",
"version": "25.3.0",
"repository": {
"type": "git",
"url": "https://github.com/facebook/jest.git",
"directory": "packages/jest-globals"
},
"engines": {
"node": ">= 8.3"
},
"license": "MIT",
"main": "build/index.js",
"types": "build/index.d.ts",
"typesVersions": {
"<3.8": {
"build/*": [
"build/ts3.4/*"
]
}
},
"dependencies": {
"@jest/environment": "^25.3.0",
"@jest/types": "^25.3.0",
"expect": "^25.3.0"
},
"publishConfig": {
"access": "public"
}
}
12 changes: 12 additions & 0 deletions packages/jest-globals/src/__tests__/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
/**
* 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.
*/

test('throw when directly imported', () => {
expect(() => require('../')).toThrowError(
'Do not import `@jest/globals` outside of the Jest test environment',
);
});
31 changes: 31 additions & 0 deletions packages/jest-globals/src/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
/**
* 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 importedExpect = require('expect');
import type {Jest} from '@jest/environment';
import type {Global} from '@jest/types';

export declare type jest = Jest;

export declare type expect = typeof importedExpect;

export declare type it = Global.GlobalAdditions['it'];
export declare type test = Global.GlobalAdditions['test'];
export declare type fit = Global.GlobalAdditions['fit'];
export declare type xit = Global.GlobalAdditions['xit'];
export declare type xtest = Global.GlobalAdditions['xtest'];
export declare type describe = Global.GlobalAdditions['describe'];
export declare type xdescribe = Global.GlobalAdditions['xdescribe'];
export declare type fdescribe = Global.GlobalAdditions['fdescribe'];
export declare type beforeAll = Global.GlobalAdditions['beforeAll'];
export declare type beforeEach = Global.GlobalAdditions['beforeEach'];
export declare type afterEach = Global.GlobalAdditions['afterEach'];
export declare type afterAll = Global.GlobalAdditions['afterAll'];

throw new Error(
Copy link
Member Author

@SimenB SimenB Apr 12, 2020

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

this file ensure types are correct, but also that it's not imported outside of jest. Compiled code is just the throw

'Do not import `@jest/globals` outside of the Jest test environment',
);
14 changes: 14 additions & 0 deletions packages/jest-globals/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
// we don't want `@types/jest` to be referenced
"types": ["node"],
"rootDir": "src",
"outDir": "build"
},
"references": [
{"path": "../expect"},
{"path": "../jest-environment"},
{"path": "../jest-types"}
]
}
1 change: 1 addition & 0 deletions packages/jest-runtime/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -19,6 +19,7 @@
"dependencies": {
"@jest/console": "^25.3.0",
"@jest/environment": "^25.3.0",
"@jest/globals": "^25.3.0",
"@jest/source-map": "^25.2.6",
"@jest/test-result": "^25.3.0",
"@jest/transform": "^25.3.0",
Expand Down
56 changes: 51 additions & 5 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,14 +9,15 @@ import {URL, fileURLToPath} from 'url';
import * as path from 'path';
import {Script, compileFunction} from 'vm';
import * as nativeModule from 'module';
import type {Config} from '@jest/types';
import type {Config, Global} from '@jest/types';
import type {
Jest,
JestEnvironment,
LocalModuleRequire,
Module,
ModuleWrapper,
} from '@jest/environment';
import type * as JestGlobals from '@jest/globals';
import type {SourceMapRegistry} from '@jest/source-map';
import {formatStackTrace, separateMessageFromStack} from 'jest-message-util';
import {createDirectory, deepCyclicCopy} from 'jest-util';
Expand All @@ -42,6 +43,11 @@ import Resolver = require('jest-resolve');
import Snapshot = require('jest-snapshot');
import stripBOM = require('strip-bom');

interface JestGlobalsValues extends Global.TestFrameworkGlobals {
jest: JestGlobals.jest;
expect: JestGlobals.expect;
}

type HasteMapOptions = {
console?: Console;
maxWorkers: number;
Expand Down Expand Up @@ -133,6 +139,7 @@ class Runtime {
private _unmockList: RegExp | undefined;
private _virtualMocks: BooleanObject;
private _moduleImplementation?: typeof nativeModule.Module;
private jestObjectCaches: Map<string, Jest>;

constructor(
config: Config.ProjectConfig,
Expand Down Expand Up @@ -169,6 +176,7 @@ class Runtime {
this._sourceMapRegistry = Object.create(null);
this._fileTransforms = new Map();
this._virtualMocks = Object.create(null);
this.jestObjectCaches = new Map();

this._mockMetaDataCache = Object.create(null);
this._shouldMockModuleCache = Object.create(null);
Expand Down Expand Up @@ -323,6 +331,11 @@ class Runtime {
modulePath = manualMock;
}

if (moduleName === '@jest/globals') {
// @ts-ignore: we don't care that it's not assignable to T
return this.getGlobalsForFile(from);
}

if (moduleName && this._resolver.isCoreModule(moduleName)) {
return this._requireCoreModule(moduleName);
}
Expand Down Expand Up @@ -859,6 +872,13 @@ class Runtime {
return;
}

const jestObject = this._createJestObjectFor(
filename,
localModule.require as LocalModuleRequire,
);

this.jestObjectCaches.set(filename, jestObject);

try {
compiledFunction.call(
localModule.exports,
Expand All @@ -868,10 +888,7 @@ class Runtime {
dirname, // __dirname
filename, // __filename
this._environment.global, // global object
this._createJestObjectFor(
filename,
localModule.require as LocalModuleRequire,
), // jest object
jestObject, // jest object
...this._config.extraGlobals.map(globalVariable => {
if (this._environment.global[globalVariable]) {
return this._environment.global[globalVariable];
Expand Down Expand Up @@ -1337,6 +1354,35 @@ class Runtime {

throw e;
}

private getGlobalsForFile(from: Config.Path): JestGlobalsValues {
const jest = this.jestObjectCaches.get(from);

invariant(jest, 'There should always be a Jest object already');

return {
afterAll: this._environment.global.afterAll,
afterEach: this._environment.global.afterEach,
beforeAll: this._environment.global.beforeAll,
beforeEach: this._environment.global.beforeEach,
describe: this._environment.global.describe,
expect: this._environment.global.expect,
fdescribe: this._environment.global.fdescribe,
fit: this._environment.global.fit,
it: this._environment.global.it,
jest,
test: this._environment.global.test,
xdescribe: this._environment.global.xdescribe,
xit: this._environment.global.xit,
xtest: this._environment.global.xtest,
};
}
}

function invariant(condition: unknown, message?: string): asserts condition {
if (!condition) {
throw new Error(message);
}
}

export = Runtime;
1 change: 1 addition & 0 deletions packages/jest-runtime/tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@
{"path": "../jest-console"},
{"path": "../jest-environment"},
{"path": "../jest-environment-node"},
{"path": "../jest-globals"},
{"path": "../jest-haste-map"},
{"path": "../jest-message-util"},
{"path": "../jest-mock"},
Expand Down
2 changes: 1 addition & 1 deletion packages/jest-types/src/Circus.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@ export type BlockMode = void | 'skip' | 'only' | 'todo';
export type TestMode = BlockMode;
export type TestName = Global.TestName;
export type TestFn = Global.TestFn;
export type HookFn = (done?: DoneFn) => Promise<any> | null | undefined;
Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

we don't actually accept null, we check for void 0 which is an non-strict mode way of saying undefined

export type HookFn = Global.HookFn;
export type AsyncFn = TestFn | HookFn;
export type SharedHookType = 'afterAll' | 'beforeAll';
export type HookType = SharedHookType | 'afterEach' | 'beforeEach';
Expand Down
16 changes: 13 additions & 3 deletions packages/jest-types/src/Global.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,9 +9,12 @@ import type {CoverageMapData} from 'istanbul-lib-coverage';

export type DoneFn = (reason?: string | Error) => void;
export type TestName = string;
export type TestFn = (done?: DoneFn) => Promise<any> | void | undefined;
export type TestFn = (
done?: DoneFn,
) => Promise<void | undefined | unknown> | void | undefined;
export type BlockFn = () => void;
export type BlockName = string;
export type HookFn = TestFn;

export type Col = unknown;
export type Row = Array<Col>;
Expand Down Expand Up @@ -66,8 +69,7 @@ export interface Describe extends DescribeBase {
skip: DescribeBase;
}

// TODO: Maybe add `| Window` in the future?
export interface GlobalAdditions {
export interface TestFrameworkGlobals {
it: ItConcurrent;
test: ItConcurrent;
fit: ItBase & {concurrent?: ItConcurrentBase};
Expand All @@ -76,6 +78,13 @@ export interface GlobalAdditions {
describe: Describe;
xdescribe: DescribeBase;
fdescribe: DescribeBase;
beforeAll: HookFn;
beforeEach: HookFn;
afterEach: HookFn;
afterAll: HookFn;
}

export interface GlobalAdditions extends TestFrameworkGlobals {
__coverage__: CoverageMapData;
jasmine: Jasmine;
fail: () => void;
Expand All @@ -84,6 +93,7 @@ export interface GlobalAdditions {
spyOnProperty: () => void;
}

// TODO: Maybe add `| Window` in the future?
// extends directly after https://github.com/sandersn/downlevel-dts/issues/33 is fixed
type NodeGlobalWithoutAdditions = Omit<NodeJS.Global, keyof GlobalAdditions>;

Expand Down
Loading