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

chore: use globalThis over global everywhere #12447

Merged
merged 5 commits into from Feb 21, 2022
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.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
24 changes: 18 additions & 6 deletions .eslintrc.js
Expand Up @@ -13,8 +13,8 @@ const internalPackages = getPackages()

module.exports = {
env: {
es2020: true,
'jest/globals': true,
node: true,
},
extends: [
'plugin:markdown/recommended',
Expand All @@ -23,7 +23,7 @@ module.exports = {
'plugin:prettier/recommended',
],
globals: {
BigInt: 'readonly',
console: 'readonly',
},
overrides: [
{
Expand All @@ -41,7 +41,7 @@ module.exports = {
{argsIgnorePattern: '^_'},
],
'@typescript-eslint/prefer-ts-expect-error': 'error',
// TS verifies this
// TS verifies these
'consistent-return': 'off',
'no-dupe-class-members': 'off',
'no-unused-vars': 'off',
Expand Down Expand Up @@ -166,6 +166,7 @@ module.exports = {
rules: {
'import/order': 'off',
'import/sort-keys': 'off',
'no-restricted-globals': ['off'],
'sort-keys': 'off',
},
},
Expand Down Expand Up @@ -228,9 +229,9 @@ module.exports = {
'e2e/jasmine-async/__tests__/*',
],
globals: {
fail: true,
jasmine: true,
pending: true,
fail: 'readonly',
jasmine: 'readonly',
pending: 'readonly',
},
},
{
Expand All @@ -252,6 +253,10 @@ module.exports = {
'jest/valid-expect': 'off',
},
},
{
env: {node: true},
files: ['*.js', '*.jsx'],
},
{
files: [
'scripts/*',
Expand Down Expand Up @@ -431,6 +436,13 @@ module.exports = {
'no-prototype-builtins': 'error',
'no-redeclare': 'warn',
'no-regex-spaces': 'warn',
'no-restricted-globals': [
'error',
{
message: 'Use `globalThis` instead.',
name: 'global',
},
],
'no-restricted-imports': [
'error',
{message: 'Please use graceful-fs instead.', name: 'fs'},
Expand Down
1 change: 1 addition & 0 deletions CHANGELOG.md
Expand Up @@ -35,6 +35,7 @@
- `[*]` [**BREAKING**] Drop support for Node v10 and v15 and target first LTS `16.13.0` ([#12220](https://github.com/facebook/jest/pull/12220))
- `[*]` [**BREAKING**] Drop support for `typescript@3.8`, minimum version is now `4.2` ([#11142](https://github.com/facebook/jest/pull/11142))
- `[*]` Bundle all `.d.ts` files into a single `index.d.ts` per module ([#12345](https://github.com/facebook/jest/pull/12345))
- `[*]` Use `globalThis` instead of `global` ([#12447](https://github.com/facebook/jest/pull/12447))
- `[docs]` Add note about not mixing `done()` with Promises ([#11077](https://github.com/facebook/jest/pull/11077))
- `[docs, examples]` Update React examples to match with the new React guidelines for code examples ([#12217](https://github.com/facebook/jest/pull/12217))
- `[expect]` [**BREAKING**] Remove support for importing `build/utils` ([#12323](https://github.com/facebook/jest/pull/12323))
Expand Down
6 changes: 3 additions & 3 deletions docs/Configuration.md
Expand Up @@ -463,13 +463,13 @@ Example:
module.exports = async () => {
// ...
// Set reference to mongod in order to close the server during teardown.
global.__MONGOD__ = mongod;
globalThis.__MONGOD__ = mongod;
};
```

```js title="teardown.js"
module.exports = async function () {
await global.__MONGOD__.stop();
await globalThis.__MONGOD__.stop();
};
```

Expand Down Expand Up @@ -1151,7 +1151,7 @@ module.exports = CustomEnvironment;
let someGlobalObject;

beforeAll(() => {
someGlobalObject = global.someGlobalObject;
someGlobalObject = globalThis.someGlobalObject;
});
```

Expand Down
4 changes: 2 additions & 2 deletions docs/MongoDB.md
Expand Up @@ -33,10 +33,10 @@ describe('insert', () => {
let db;

beforeAll(async () => {
connection = await MongoClient.connect(global.__MONGO_URI__, {
connection = await MongoClient.connect(globalThis.__MONGO_URI__, {
useNewUrlParser: true,
});
db = await connection.db(global.__MONGO_DB_NAME__);
db = await connection.db(globalThis.__MONGO_DB_NAME__);
});

afterAll(async () => {
Expand Down
6 changes: 3 additions & 3 deletions docs/Puppeteer.md
Expand Up @@ -65,7 +65,7 @@ module.exports = async function () {
const browser = await puppeteer.launch();
// store the browser instance so we can teardown it later
// this global is only available in the teardown but not in TestEnvironments
global.__BROWSER_GLOBAL__ = browser;
globalThis.__BROWSER_GLOBAL__ = browser;

// use the file system to expose the wsEndpoint for TestEnvironments
await mkdir(DIR, {recursive: true});
Expand Down Expand Up @@ -125,7 +125,7 @@ const path = require('path');
const DIR = path.join(os.tmpdir(), 'jest_puppeteer_global_setup');
module.exports = async function () {
// close the browser instance
await global.__BROWSER_GLOBAL__.close();
await globalThis.__BROWSER_GLOBAL__.close();

// clean-up the wsEndpoint file
await fs.rm(DIR, {recursive: true, force: true});
Expand All @@ -142,7 +142,7 @@ describe(
() => {
let page;
beforeAll(async () => {
page = await global.__BROWSER_GLOBAL__.newPage();
page = await globalThis.__BROWSER_GLOBAL__.newPage();
await page.goto('https://google.com');
}, timeout);

Expand Down
2 changes: 1 addition & 1 deletion docs/Troubleshooting.md
Expand Up @@ -140,7 +140,7 @@ If a promise doesn't resolve at all, this error might be thrown:
- Error: Timeout - Async callback was not invoked within timeout specified by jasmine.DEFAULT_TIMEOUT_INTERVAL.`
```

Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `global.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.
Most commonly this is being caused by conflicting Promise implementations. Consider replacing the global promise implementation with your own, for example `globalThis.Promise = jest.requireActual('promise');` and/or consolidate the used Promise libraries to a single one.

If your test is long running, you may want to consider to increase the timeout by calling `jest.setTimeout`

Expand Down
Expand Up @@ -16,7 +16,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
14 | });
15 | });

at eventHandler (../../packages/jest-circus/build/eventHandler.js:190:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:146:11)
at test (__tests__/asyncDefinition.test.js:12:5)

● Test suite failed to run
Expand All @@ -31,7 +31,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
15 | });
16 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:158:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:114:11)
at afterAll (__tests__/asyncDefinition.test.js:13:5)

● Test suite failed to run
Expand All @@ -46,7 +46,7 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
20 | });
21 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:190:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:146:11)
at test (__tests__/asyncDefinition.test.js:18:3)

● Test suite failed to run
Expand All @@ -60,6 +60,6 @@ exports[`defining tests and hooks asynchronously throws 1`] = `
20 | });
21 |

at eventHandler (../../packages/jest-circus/build/eventHandler.js:158:11)
at eventHandler (../../packages/jest-circus/build/eventHandler.js:114:11)
at afterAll (__tests__/asyncDefinition.test.js:19:3)"
`;
2 changes: 1 addition & 1 deletion e2e/__tests__/global.test.ts
Expand Up @@ -6,5 +6,5 @@
*/

test('globals are properly defined', () => {
expect(global.Object).toBe(Object);
expect(globalThis.Object).toBe(Object);
});
2 changes: 1 addition & 1 deletion e2e/__tests__/json.test.ts
Expand Up @@ -6,7 +6,7 @@
*/

test('JSON is available in the global scope', () => {
expect(JSON).toBe(global.JSON);
expect(JSON).toBe(globalThis.JSON);
});

test('JSON.parse creates objects from within this context', () => {
Expand Down
4 changes: 2 additions & 2 deletions e2e/__tests__/multiProjectRunner.test.ts
Expand Up @@ -353,10 +353,10 @@ test('resolves projects and their <rootDir> properly', () => {
testEnvironment: 'node',
}),
'project1/__tests__/test.test.js':
"test('project1', () => expect(global.project1).toBe(true))",
"test('project1', () => expect(globalThis.project1).toBe(true))",
'project1/project1_setup.js': 'global.project1 = true;',
'project2/__tests__/test.test.js':
"test('project2', () => expect(global.project2).toBe(true))",
"test('project2', () => expect(globalThis.project2).toBe(true))",
'project2/project2.conf.json': JSON.stringify({
name: 'project2',
rootDir: '../', // root dir is set to the top level
Expand Down
3 changes: 2 additions & 1 deletion e2e/__tests__/symbol.test.ts
Expand Up @@ -6,7 +6,8 @@
*/

test('Symbol deletion', () => {
global.Symbol = undefined;
// @ts-expect-error
globalThis.Symbol = undefined;

expect({}).toEqual({});
});
2 changes: 1 addition & 1 deletion e2e/__tests__/testEnvironment.test.ts
Expand Up @@ -50,7 +50,7 @@ it('handles missing `mocked` property', () => {
jest.mocked();

test('halla', () => {
expect(global.thing).toBe('nope');
expect(globalThis.thing).toBe('nope');
});
`,
});
Expand Down
4 changes: 3 additions & 1 deletion e2e/__tests__/transform.test.ts
Expand Up @@ -114,7 +114,9 @@ describe('custom transformer', () => {
it('preprocesses files', () => {
const {json, stderr} = runWithJson(dir, ['--no-cache']);
expect(stderr).toMatch(/FAIL/);
expect(stderr).toMatch(/instruments by setting.*global\.__INSTRUMENTED__/);
expect(stderr).toMatch(
/instruments by setting.*globalThis\.__INSTRUMENTED__/,
);
expect(json.numTotalTests).toBe(2);
expect(json.numPassedTests).toBe(1);
expect(json.numFailedTests).toBe(1);
Expand Down
14 changes: 7 additions & 7 deletions e2e/babel-plugin-jest-hoist/__tests__/integration.test.js
Expand Up @@ -34,10 +34,10 @@ let e;
})();

jest.mock('../__test_modules__/f', () => {
if (!global.CALLS) {
global.CALLS = 0;
if (!globalThis.CALLS) {
globalThis.CALLS = 0;
}
global.CALLS++;
globalThis.CALLS++;

return {
_isMock: true,
Expand Down Expand Up @@ -116,15 +116,15 @@ describe('babel-plugin-jest-hoist', () => {
it('only executes the module factories once', () => {
jest.resetModules();

global.CALLS = 0;
globalThis.CALLS = 0;

require('../__test_modules__/f');
expect(global.CALLS).toEqual(1);
expect(globalThis.CALLS).toEqual(1);

require('../__test_modules__/f');
expect(global.CALLS).toEqual(1);
expect(globalThis.CALLS).toEqual(1);

delete global.CALLS;
delete globalThis.CALLS;
});

it('does not hoist dontMock calls before imports', () => {
Expand Down
12 changes: 6 additions & 6 deletions e2e/console-debugging/stdout-spy.js
Expand Up @@ -8,19 +8,19 @@

const originalStdoutWrite = process.stdout.write.bind(process.stdout);

global.process.__stdoutWriteMock = global.process.__stdoutWriteMock || null;
process.__stdoutWriteMock = process.__stdoutWriteMock || null;

/*
This is a terrible hack to ensure that we monkeyPath stdoutWrite before
the jest reporter does...
*/
if (!global.process.__stdoutWriteMock) {
global.process.__stdoutWriteMock = (...args) => {
global.process.__stdoutWriteMock.text = args[0];
if (!process.__stdoutWriteMock) {
process.__stdoutWriteMock = (...args) => {
process.__stdoutWriteMock.text = args[0];
originalStdoutWrite(...args);
};

process.stdout.write = global.process.__stdoutWriteMock;
process.stdout.write = process.__stdoutWriteMock;
}

module.exports = global.process.__stdoutWriteMock;
module.exports = process.__stdoutWriteMock;
2 changes: 1 addition & 1 deletion e2e/coverage-report/__tests__/sum.test.js
Expand Up @@ -10,7 +10,7 @@ jest.mock('../sumDependency.js'); // call mock explicitly

const {sum} = require('../sum');

if (!global.setup) {
if (!globalThis.setup) {
throw new Error('setup.js was not called.');
}

Expand Down
2 changes: 1 addition & 1 deletion e2e/coverage-report/setup.js
Expand Up @@ -5,4 +5,4 @@
* LICENSE file in the root directory of this source tree.
*/

global.setup = true;
globalThis.setup = true;
2 changes: 1 addition & 1 deletion e2e/env-test/__tests__/env.test.js
Expand Up @@ -6,6 +6,6 @@
*/
'use strict';

console.log(global.window ? 'WINDOW' : 'NO WINDOW');
console.log(globalThis.window ? 'WINDOW' : 'NO WINDOW');

test('stub', () => expect(1).toBe(1));
2 changes: 1 addition & 1 deletion e2e/expect-in-vm/__tests__/expect-in-vm.test.js
Expand Up @@ -14,7 +14,7 @@ it('correctly expects RegExp inside a new VM context', () => {
`(function(require, module, exports, __dirname, __filename, expect) {
expect('ab12cd').toMatch(/ab12cd/);
})`,
global,
globalThis,
);

const module = {
Expand Down
2 changes: 1 addition & 1 deletion e2e/fake-promises/asap/fake-promises.js
Expand Up @@ -7,4 +7,4 @@

'use strict';

global.Promise = require('promise');
globalThis.Promise = require('promise');
2 changes: 1 addition & 1 deletion e2e/fake-promises/immediate/fake-promises.js
Expand Up @@ -7,4 +7,4 @@

'use strict';

global.Promise = require('promise/setimmediate');
globalThis.Promise = require('promise/setimmediate');
2 changes: 1 addition & 1 deletion e2e/override-globals/index.js
Expand Up @@ -5,6 +5,6 @@
* LICENSE file in the root directory of this source tree.
*/

global.Promise = function () {
globalThis.Promise = function () {
throw new Error('Booo');
};
3 changes: 1 addition & 2 deletions e2e/reset-modules/__tests__/resetModules.test.js
Expand Up @@ -6,8 +6,7 @@
*/
'use strict';

// eslint-disable-next-line no-undef
global.testObject = new Proxy(
globalThis.testObject = new Proxy(
{},
{
get: function getter(target, key) {
Expand Down
Expand Up @@ -8,6 +8,6 @@

describe('setupFile', () => {
it('patches jasmine in setup file', () => {
expect(global.describeDefined).toBe(true);
expect(globalThis.describeDefined).toBe(true);
});
});
2 changes: 1 addition & 1 deletion e2e/setup-files-after-env-config/__tests__/test1.test.js
Expand Up @@ -8,6 +8,6 @@

describe('test', () => {
it('has predefined global variable', () => {
expect(global.definedInSetupFile).toEqual(true);
expect(globalThis.definedInSetupFile).toEqual(true);
});
});
2 changes: 1 addition & 1 deletion e2e/setup-files-after-env-config/__tests__/test2.test.js
Expand Up @@ -8,6 +8,6 @@

describe('test', () => {
it('has predefined global variable', () => {
expect(global.definedInSetupFile).toEqual(true);
expect(globalThis.definedInSetupFile).toEqual(true);
});
});