Jest: Mock factories do not support explicit TypeScript typing using imported types

Created on 15 Jan 2019  路  4Comments  路  Source: facebook/jest

馃悰 Bug Report

Mock factories do not support explicit TypeScript typing using imported types in mock factories because hoisting happens before types are stripped.

To Reproduce

Steps to reproduce the behaviour:

In a test file, do:

  1. Import a type from somewhere
  2. Mock a module, and provide a factory which uses that type
  3. Run the test

Expected behavior

Since Jest does not perform any checks related to typings, it makes sense to me that type information should be stripped (and other Babel plugins should be applied) before mocks are hoisted.

As Jest claims I reference an out-of-scope "variable" (actually a type), this does not seem to be the case. To me (and @SimenB, who looked at this after I gave up), this seems like a bug.

Link to repl or repo (highly encouraged)

Simple repro with a semi-realistic case: https://github.com/theneva/jest-babel-hoist-typescript-repro

Run npx envinfo --preset jest

$ npx envinfo --preset jest
npx: installed 1 in 1.727s

  System:
    OS: macOS 10.14.1
    CPU: (12) x64 Intel(R) Core(TM) i7-8750H CPU @ 2.20GHz
  Binaries:
    Node: 10.13.0 - ~/.nvm/versions/node/v10.13.0/bin/node
    Yarn: 1.12.3 - /usr/local/bin/yarn
    npm: 6.4.1 - ~/.nvm/versions/node/v10.13.0/bin/npm
  npmPackages:
    jest: ^24.0.0-alpha.12 => 24.0.0-alpha.12
Bug Confirmed Help Wanted

Most helpful comment

Wow, that does the trick. Thanks once again @jeysal! I'll put together a PR

All 4 comments

I tried messing with the order of babel plugins without making it work - no matter if babel-plugin-jest-hoist was before or after @babel/plugin-transform-typescript it still gives the warning.

@loganfsmyth is there any way we can make sure that our plugin is ran after @babel/plugin-transform-typescript has been able to strip out type annotations?

Plugin source: https://github.com/facebook/jest/blob/master/packages/babel-plugin-jest-hoist/src/index.js
Added via preset: https://github.com/facebook/jest/blob/403044962063c4003ed7362a4899920b90eaeffc/packages/babel-jest/src/index.js#L36

I tried doing babel.loadPartialConfig then messing with where I added the preset, then doing babel.loadOptions on that object, and looking at plugins there. I had hoped an ordering change made a difference, but no such luck

Perhaps making the ExpressionStatement visitor an exit visitor could help?
Edit: Seems likely after a quick glance on jest-hoist and transform-typescript, but I've got no time to try it out right now.

Wow, that does the trick. Thanks once again @jeysal! I'll put together a PR

7634

Was this page helpful?
0 / 5 - 0 ratings

Related issues

rosiakr picture rosiakr  路  3Comments

jardakotesovec picture jardakotesovec  路  3Comments

withinboredom picture withinboredom  路  3Comments

stephenlautier picture stephenlautier  路  3Comments

hramos picture hramos  路  3Comments