From 4ffd3fd6b809d7a5b0678f7497d76ed96227e2f2 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 20 Apr 2020 21:43:36 +0200 Subject: [PATCH 1/5] Revert "Revert "feat: add `@jest/globals` package for importing globals explicitly (#9801)"" This reverts commit 75ab1abe67d30f7aa25a5b01218af6af1059f8f9. --- CHANGELOG.md | 1 + docs/GlobalAPI.md | 2 +- docs/JestObjectAPI.md | 2 +- e2e/__tests__/importedGlobals.test.ts | 13 +++++ e2e/imported-globals/__tests__/env.test.js | 22 ++++++++ e2e/imported-globals/babel.config.js | 8 +++ e2e/imported-globals/package.json | 5 ++ packages/jest-globals/.npmignore | 5 ++ packages/jest-globals/package.json | 30 ++++++++++ packages/jest-globals/src/__tests__/index.ts | 12 ++++ packages/jest-globals/src/index.ts | 31 +++++++++++ packages/jest-globals/tsconfig.json | 14 +++++ packages/jest-runtime/package.json | 1 + packages/jest-runtime/src/index.ts | 58 +++++++++++++++++--- packages/jest-runtime/tsconfig.json | 1 + 15 files changed, 195 insertions(+), 10 deletions(-) create mode 100644 e2e/__tests__/importedGlobals.test.ts create mode 100644 e2e/imported-globals/__tests__/env.test.js create mode 100644 e2e/imported-globals/babel.config.js create mode 100644 e2e/imported-globals/package.json create mode 100644 packages/jest-globals/.npmignore create mode 100644 packages/jest-globals/package.json create mode 100644 packages/jest-globals/src/__tests__/index.ts create mode 100644 packages/jest-globals/src/index.ts create mode 100644 packages/jest-globals/tsconfig.json diff --git a/CHANGELOG.md b/CHANGELOG.md index de22b98fd823..c12db83fede3 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,7 @@ ### Features +- `[@jest/globals]` New package so Jest's globals can be explicitly imported ([#9801](https://github.com/facebook/jest/pull/9801)) - `[jest-runtime]` Populate `require.cache` ([#9841](https://github.com/facebook/jest/pull/9841)) ### Fixes diff --git a/docs/GlobalAPI.md b/docs/GlobalAPI.md index d01f975884b8..bbbc7d526b05 100644 --- a/docs/GlobalAPI.md +++ b/docs/GlobalAPI.md @@ -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 diff --git a/docs/JestObjectAPI.md b/docs/JestObjectAPI.md index 638e16f38550..784c5c3370f1 100644 --- a/docs/JestObjectAPI.md +++ b/docs/JestObjectAPI.md @@ -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 diff --git a/e2e/__tests__/importedGlobals.test.ts b/e2e/__tests__/importedGlobals.test.ts new file mode 100644 index 000000000000..146ed6544715 --- /dev/null +++ b/e2e/__tests__/importedGlobals.test.ts @@ -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); +}); diff --git a/e2e/imported-globals/__tests__/env.test.js b/e2e/imported-globals/__tests__/env.test.js new file mode 100644 index 000000000000..e81a1db5a6d5 --- /dev/null +++ b/e2e/imported-globals/__tests__/env.test.js @@ -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); +}); diff --git a/e2e/imported-globals/babel.config.js b/e2e/imported-globals/babel.config.js new file mode 100644 index 000000000000..9be036106918 --- /dev/null +++ b/e2e/imported-globals/babel.config.js @@ -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'); diff --git a/e2e/imported-globals/package.json b/e2e/imported-globals/package.json new file mode 100644 index 000000000000..148788b25446 --- /dev/null +++ b/e2e/imported-globals/package.json @@ -0,0 +1,5 @@ +{ + "jest": { + "testEnvironment": "node" + } +} diff --git a/packages/jest-globals/.npmignore b/packages/jest-globals/.npmignore new file mode 100644 index 000000000000..3ee5d55b0b89 --- /dev/null +++ b/packages/jest-globals/.npmignore @@ -0,0 +1,5 @@ +**/__mocks__/** +**/__tests__/** +src +tsconfig.json +tsconfig.tsbuildinfo diff --git a/packages/jest-globals/package.json b/packages/jest-globals/package.json new file mode 100644 index 000000000000..c216d3beda23 --- /dev/null +++ b/packages/jest-globals/package.json @@ -0,0 +1,30 @@ +{ + "name": "@jest/globals", + "version": "25.4.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.4.0", + "@jest/types": "^25.4.0", + "expect": "^25.4.0" + }, + "publishConfig": { + "access": "public" + } +} diff --git a/packages/jest-globals/src/__tests__/index.ts b/packages/jest-globals/src/__tests__/index.ts new file mode 100644 index 000000000000..cb0af7398581 --- /dev/null +++ b/packages/jest-globals/src/__tests__/index.ts @@ -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', + ); +}); diff --git a/packages/jest-globals/src/index.ts b/packages/jest-globals/src/index.ts new file mode 100644 index 000000000000..82bc15a3b522 --- /dev/null +++ b/packages/jest-globals/src/index.ts @@ -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( + 'Do not import `@jest/globals` outside of the Jest test environment', +); diff --git a/packages/jest-globals/tsconfig.json b/packages/jest-globals/tsconfig.json new file mode 100644 index 000000000000..b6678e5f0aed --- /dev/null +++ b/packages/jest-globals/tsconfig.json @@ -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"} + ] +} diff --git a/packages/jest-runtime/package.json b/packages/jest-runtime/package.json index bcbe8cc534c7..856194f2d8fc 100644 --- a/packages/jest-runtime/package.json +++ b/packages/jest-runtime/package.json @@ -19,6 +19,7 @@ "dependencies": { "@jest/console": "^25.4.0", "@jest/environment": "^25.4.0", + "@jest/globals": "^25.4.0", "@jest/source-map": "^25.2.6", "@jest/test-result": "^25.4.0", "@jest/transform": "^25.4.0", diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index af6cc31ef0ec..c125a5a8d5a5 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -19,7 +19,7 @@ import { 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, @@ -27,6 +27,7 @@ import type { 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'; @@ -52,6 +53,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; @@ -148,6 +154,7 @@ class Runtime { private _unmockList: RegExp | undefined; private _virtualMocks: BooleanObject; private _moduleImplementation?: typeof nativeModule.Module; + private jestObjectCaches: Map; constructor( config: Config.ProjectConfig, @@ -185,6 +192,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); @@ -654,12 +662,18 @@ class Runtime { }; } - requireModuleOrMock(from: Config.Path, moduleName: string): unknown { + requireModuleOrMock(from: Config.Path, moduleName: string): T { + // this module is unmockable + if (moduleName === '@jest/globals') { + // @ts-ignore: we don't care that it's not assignable to T + return this.getGlobalsForFile(from); + } + try { if (this._shouldMock(from, moduleName)) { - return this.requireMock(from, moduleName); + return this.requireMock(from, moduleName); } else { - return this.requireModule(from, moduleName); + return this.requireModule(from, moduleName); } } catch (e) { const moduleNotFound = Resolver.tryCastModuleNotFoundError(e); @@ -986,6 +1000,13 @@ class Runtime { return; } + const jestObject = this._createJestObjectFor( + filename, + localModule.require as LocalModuleRequire, + ); + + this.jestObjectCaches.set(filename, jestObject); + try { compiledFunction.call( localModule.exports, @@ -995,10 +1016,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]; @@ -1531,6 +1549,30 @@ class Runtime { throw e; } + + private getGlobalsForFile(from: Config.Path): JestGlobalsValues { + const jest = this.jestObjectCaches.get(from); + + // This won't exist in ESM + 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 { diff --git a/packages/jest-runtime/tsconfig.json b/packages/jest-runtime/tsconfig.json index 08abc7a9ddfc..2955d779d6b1 100644 --- a/packages/jest-runtime/tsconfig.json +++ b/packages/jest-runtime/tsconfig.json @@ -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"}, From ca1c51978a4b17ec84e1a9de455c2b3fc64cd909 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Mon, 20 Apr 2020 23:54:44 +0200 Subject: [PATCH 2/5] support import from esm as well --- .../__snapshots__/nativeEsm.test.ts.snap | 2 +- e2e/native-esm/__tests__/native-esm.test.js | 5 ++ packages/jest-runtime/src/index.ts | 64 +++++++++++++++++-- 3 files changed, 65 insertions(+), 6 deletions(-) diff --git a/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap b/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap index be56a4394e76..ca20b5785769 100644 --- a/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap +++ b/e2e/__tests__/__snapshots__/nativeEsm.test.ts.snap @@ -2,7 +2,7 @@ exports[`on node >=12.16.0 runs test with native ESM 1`] = ` Test Suites: 1 passed, 1 total -Tests: 9 passed, 9 total +Tests: 10 passed, 10 total Snapshots: 0 total Time: <> Ran all test suites. diff --git a/e2e/native-esm/__tests__/native-esm.test.js b/e2e/native-esm/__tests__/native-esm.test.js index 8f1800e57c12..6cf48b3811ec 100644 --- a/e2e/native-esm/__tests__/native-esm.test.js +++ b/e2e/native-esm/__tests__/native-esm.test.js @@ -9,6 +9,7 @@ import {readFileSync} from 'fs'; import {createRequire} from 'module'; import {dirname, resolve} from 'path'; import {fileURLToPath} from 'url'; +import {jest as jestObject} from '@jest/globals'; import staticImportedStateful from '../stateful.mjs'; import staticImportedStatefulFromCjs from '../fromCjs.mjs'; import {double} from '../index'; @@ -90,3 +91,7 @@ test('handle unlinked dynamic imports', async () => { expect(deepDouble(4)).toBe(8); }); + +test('can import `jest` object', () => { + expect(jestObject).toBeDefined(); +}); diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 39d01e891594..aa98dbfe5c28 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -326,7 +326,6 @@ class Runtime { query = '', ): Promise { if (modulePath === '@jest/globals') { - // TODO: create a Synthetic Module for this. Will need to create a `jest` object without a `LocalModuleRequire` throw new Error( 'Importing `@jest/globals` is not supported from ESM yet', ); @@ -380,10 +379,23 @@ class Runtime { } private async linkModules(specifier: string, referencingModule: VMModule) { + if (specifier === '@jest/globals') { + if (!this._esmoduleRegistry.has(specifier)) { + const module = await this.getGlobalsForEsm( + referencingModule.identifier, + referencingModule.context, + ); + this._esmoduleRegistry.set(specifier, module); + } + + return this._esmoduleRegistry.get(specifier); + } + const resolved = this._resolveModule( referencingModule.identifier, specifier, ); + if ( this._resolver.isCoreModule(resolved) || this.unstable_shouldLoadAsEsm(resolved) @@ -661,7 +673,7 @@ class Runtime { // this module is unmockable if (moduleName === '@jest/globals') { // @ts-ignore: we don't care that it's not assignable to T - return this.getGlobalsForFile(from); + return this.getGlobalsForCjs(from); } try { @@ -1545,12 +1557,55 @@ class Runtime { throw e; } - private getGlobalsForFile(from: Config.Path): JestGlobalsValues { + private getGlobalsForCjs(from: Config.Path): JestGlobalsValues { const jest = this.jestObjectCaches.get(from); - // This won't exist in ESM invariant(jest, 'There should always be a Jest object already'); + return {...this.getGlobalsFromEnvironment(), jest}; + } + + private async getGlobalsForEsm( + from: Config.Path, + context: VMContext, + ): Promise { + let jest = this.jestObjectCaches.get(from); + + if (!jest) { + jest = this._createJestObjectFor( + from, + this._getMockedNativeModule().createRequire(from), + ); + + this.jestObjectCaches.set(from, jest); + } + + const globals: JestGlobalsValues = { + ...this.getGlobalsFromEnvironment(), + jest, + }; + + const module = new SyntheticModule( + Object.keys(globals), + function () { + Object.entries(globals).forEach(([key, value]) => { + // @ts-ignore: TS doesn't know what `this` is + this.setExport(key, value); + }); + }, + {context, identifier: from}, + ); + + await module.link(() => { + throw new Error('This should never happen'); + }); + + await module.evaluate(); + + return module; + } + + private getGlobalsFromEnvironment(): Omit { return { afterAll: this._environment.global.afterAll, afterEach: this._environment.global.afterEach, @@ -1561,7 +1616,6 @@ class Runtime { 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, From 5092f2f8de98e47e00a232f17b9bd554d68ecc74 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Tue, 21 Apr 2020 00:06:51 +0200 Subject: [PATCH 3/5] remove faulty caching --- packages/jest-runtime/src/index.ts | 18 +++++++----------- 1 file changed, 7 insertions(+), 11 deletions(-) diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index aa98dbfe5c28..f7c2139a5c52 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -378,17 +378,13 @@ class Runtime { return module; } - private async linkModules(specifier: string, referencingModule: VMModule) { + private linkModules(specifier: string, referencingModule: VMModule) { if (specifier === '@jest/globals') { - if (!this._esmoduleRegistry.has(specifier)) { - const module = await this.getGlobalsForEsm( - referencingModule.identifier, - referencingModule.context, - ); - this._esmoduleRegistry.set(specifier, module); - } - - return this._esmoduleRegistry.get(specifier); + // should we cache this? + return this.getGlobalsForEsm( + referencingModule.identifier, + referencingModule.context, + ); } const resolved = this._resolveModule( @@ -1593,7 +1589,7 @@ class Runtime { this.setExport(key, value); }); }, - {context, identifier: from}, + {context, identifier: '@jest/globals'}, ); await module.link(() => { From 835c95c035bbd0bc937ded28f1390ef04135eaa5 Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Tue, 21 Apr 2020 09:10:47 +0200 Subject: [PATCH 4/5] remove dead code --- packages/jest-runtime/src/index.ts | 6 ------ 1 file changed, 6 deletions(-) diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index f7c2139a5c52..4ba882be9984 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -325,12 +325,6 @@ class Runtime { modulePath: Config.Path, query = '', ): Promise { - if (modulePath === '@jest/globals') { - throw new Error( - 'Importing `@jest/globals` is not supported from ESM yet', - ); - } - const cacheKey = modulePath + query; if (!this._esmoduleRegistry.has(cacheKey)) { From 5d8abcd113783c0249d983f6d57abfe9a984eefd Mon Sep 17 00:00:00 2001 From: Simen Bekkhus Date: Wed, 22 Apr 2020 10:14:00 +0200 Subject: [PATCH 5/5] chore: cache @jest/globals for esm --- packages/jest-runtime/src/index.ts | 11 +++++++++-- 1 file changed, 9 insertions(+), 2 deletions(-) diff --git a/packages/jest-runtime/src/index.ts b/packages/jest-runtime/src/index.ts index 436e3d789672..39f0cbcb3cc8 100644 --- a/packages/jest-runtime/src/index.ts +++ b/packages/jest-runtime/src/index.ts @@ -374,11 +374,18 @@ class Runtime { private linkModules(specifier: string, referencingModule: VMModule) { if (specifier === '@jest/globals') { - // should we cache this? - return this.getGlobalsForEsm( + const fromCache = this._esmoduleRegistry.get('@jest/globals'); + + if (fromCache) { + return fromCache; + } + const globals = this.getGlobalsForEsm( referencingModule.identifier, referencingModule.context, ); + this._esmoduleRegistry.set('@jest/globals', globals); + + return globals; } const resolved = this._resolveModule(