Mock factories do not support explicit TypeScript typing using imported types in mock factories because hoisting happens before types are stripped.
Steps to reproduce the behaviour:
In a test file, do:
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.
Simple repro with a semi-realistic case: https://github.com/theneva/jest-babel-hoist-typescript-repro
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
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
Most helpful comment
Wow, that does the trick. Thanks once again @jeysal! I'll put together a PR