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

fix: hoist imports of @jest/globals correctly #9806

Merged
merged 23 commits into from
Apr 28, 2020
Merged
Show file tree
Hide file tree
Changes from 2 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: 1 addition & 1 deletion e2e/__tests__/babelPluginJestHoist.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@ beforeEach(() => {
run('yarn', DIR);
});

it('sucessfully runs the tests inside `babel-plugin-jest-hoist/`', () => {
it('successfully runs the tests inside `babel-plugin-jest-hoist/`', () => {
const {json} = runWithJson(DIR, ['--no-cache', '--coverage']);
expect(json.success).toBe(true);
expect(json.numTotalTestSuites).toBe(3);
Expand Down
18 changes: 18 additions & 0 deletions e2e/babel-plugin-jest-hoist/__tests__/importJest.test.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
/**
* 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 {jest} from '@jest/globals';
jeysal marked this conversation as resolved.
Show resolved Hide resolved

// The virtual mock call below will be hoisted above this `require` call.
const virtualModule = require('virtual-module');

jest.mock('virtual-module', () => 'kiwi', {virtual: true});

test('works with virtual modules', () => {
expect(virtualModule).toBe('kiwi');
});
36 changes: 36 additions & 0 deletions packages/babel-plugin-jest-hoist/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -183,6 +183,42 @@ export default (): {visitor: Visitor} => {
path.node._blockHoist = Infinity;
}
},
ImportDeclaration(path) {
Copy link
Member Author

Choose a reason for hiding this comment

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

Should probably look for a require instead (or as well?)

Copy link
Member Author

Choose a reason for hiding this comment

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

I tried this:

const visitor: Visitor = {
  CallExpression(path) {
    const callee = path.get('callee') as NodePath;
    const callArguments = path.get('arguments');

    if (
      callee.isIdentifier() &&
      callee.node.name === 'require' &&
      callArguments.length === 1
    ) {
      const [argument] = callArguments;

      if (
        argument.isStringLiteral() &&
        argument.node.value === '@jest/globals'
      ) {
        // @ts-ignore: private, magical property
        path.node._blockHoist = Infinity;
      }
    }
  },
};

and it gets into the _blockHoist thing, but doesn't seem to actually hoist it. Halp? 😀

Copy link
Member Author

@SimenB SimenB Apr 13, 2020

Choose a reason for hiding this comment

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

New try:

const visitor: Visitor = {
  VariableDeclaration(path) {
    const declarations = path.get('declarations');
  
    if (declarations.length === 1) {
      const declarationInit = declarations[0].get('init');
  
      if (declarationInit.isCallExpression()) {
        const callee = declarationInit.get('callee') as NodePath;
        const callArguments = declarationInit.get('arguments') as Array<
          NodePath
        >;
  
        if (
          callee.isIdentifier() &&
          callee.node.name === 'require' &&
          callArguments.length === 1
        ) {
          const [argument] = callArguments;
  
          if (
            argument.isStringLiteral() &&
            argument.node.value === '@jest/globals'
          ) {
            // @ts-ignore: private, magical property
            path.node._blockHoist = Infinity;
          }
        }
      }
    }
  }
}

This seems to hoist the require, but not above the jest.mock call.

"use strict";

_globals.jest.mock('virtual-module', function () {
  return 'kiwi';
}, {
  virtual: true
});

var _globals = require("@jest/globals");

/**
 * 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.
 *
 */
// The virtual mock call below will be hoisted above this `require` call.
var virtualModule = require('virtual-module');

test('works with virtual modules', function () {
  expect(virtualModule).toBe('kiwi');
});

Getting pretty close though 🙂

EDIT: wait no, that's the same as not having it at all 😅 I give up

Copy link
Member Author

Choose a reason for hiding this comment

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

I pushed up that last one, since it feels like it's somewhere close

if (path.node.source.value === '@jest/globals') {
// @ts-ignore: private, magical property
path.node._blockHoist = Infinity;
}
},
VariableDeclaration(path) {
const declarations = path.get('declarations');

if (declarations.length === 1) {
const declarationInit = declarations[0].get('init');

if (declarationInit.isCallExpression()) {
const callee = declarationInit.get('callee') as NodePath;
const callArguments = declarationInit.get('arguments') as Array<
NodePath
>;

if (
callee.isIdentifier() &&
callee.node.name === 'require' &&
callArguments.length === 1
) {
const [argument] = callArguments;

if (
argument.isStringLiteral() &&
argument.node.value === '@jest/globals'
) {
// @ts-ignore: private, magical property
path.node._blockHoist = Infinity;
}
}
}
}
},
};

return {visitor};
Expand Down
17 changes: 9 additions & 8 deletions packages/jest-runtime/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -331,11 +331,6 @@ 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 @@ -526,12 +521,18 @@ class Runtime {
};
}

requireModuleOrMock(from: Config.Path, moduleName: string): unknown {
requireModuleOrMock<T = unknown>(from: Config.Path, moduleName: string): T {
// this module is unmockable
if (moduleName === '@jest/globals') {
jeysal marked this conversation as resolved.
Show resolved Hide resolved
// @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<T>(from, moduleName);
} else {
return this.requireModule(from, moduleName);
return this.requireModule<T>(from, moduleName);
}
} catch (e) {
const moduleNotFound = Resolver.tryCastModuleNotFoundError(e);
Expand Down