Skip to content

babel-plugin-jest-hoist: NodeJS v12 global.process and global.Buffer not enumerable #8427

Closed
@IanSavchenko

Description

@IanSavchenko

🐛 Bug Report

In the v12 of NodeJS, they changed the list of enumerable globals. Most notably process and Buffer are no longer enumerable. So this makes tests fail if global mock implementations use any of them.

To Reproduce

Steps to reproduce the behavior:

  1. Upgrade to the latest node:
    > npm install -g node

  2. Create a test file test.js like:

jest.mock('./a', function() {
  return process;
});
  1. Run test
    npx jest ./test.js

This will fail with

babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: process
    Whitelisted objects: Array, ArrayBuffer, Boolean, DataView, Date, Error, EvalError, Float32Array, Float64Array, Function, Generator, GeneratorFunction, Infinity, Int16Array, Int32Array, Int8Array, InternalError, Intl, JSON, Map, Math, NaN, Number, Object, Promise, Proxy, RangeError, ReferenceError, Reflect, RegExp, Set, String, Symbol, SyntaxError, TypeError, URIError, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray, WeakMap, WeakSet, arguments, console, expect, isNaN, jest, parseFloat, parseInt, require, undefined, global, clearInterval, clearTimeout, setInterval, setTimeout, queueMicrotask, clearImmediate, setImmediate.
    Note: This is a precaution to guard against uninitialized mock variables. If it is ensured that the mock is required lazily, variable names prefixed with `mock` (case insensitive) are permitted.

Expected behavior

It is expected for jest to know about globals.

Run npx envinfo --preset jest

Paste the results here:

System:
    OS: macOS Mojave 10.14.4
    CPU: (4) x64 Intel(R) Core(TM) i7-6660U CPU @ 2.40GHz
  Binaries:
    Node: 12.1.0 - /usr/local/bin/node
    Yarn: 1.15.2 - /usr/local/bin/yarn
    npm: 6.9.0 - /usr/local/bin/npm
  npmPackages:
    jest: file:../../../node_modules/jest => 24.8.0

Suggested fix

I can suggest a quick and fair IMO fix. In https://github.com/facebook/jest/blob/master/packages/babel-plugin-jest-hoist/src/index.ts instead of

Object.keys(global).forEach(name => {
  WHITELISTED_IDENTIFIERS.add(name);
});

do

Object.getOwnPropertyNames(global).forEach(name => {
  WHITELISTED_IDENTIFIERS.add(name);
});

A PR #8429 submitted.

Quick workaround

For referencing process or Buffer in mock, you can use global like

jest.mock('./a', function() {
  return global.process;
});

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions