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

[Bug]: mock factory hoisting fails with 'mock' prepended variables #11862

Closed
john-u opened this issue Sep 9, 2021 · 2 comments · Fixed by #12453
Closed

[Bug]: mock factory hoisting fails with 'mock' prepended variables #11862

john-u opened this issue Sep 9, 2021 · 2 comments · Fixed by #12453

Comments

@john-u
Copy link
Contributor

john-u commented Sep 9, 2021

Version

27.1.1

Steps to reproduce

  1. Clone my repo at https://github.com/john-u/jest-mock-hoist-issue
  2. npm install
  3. npm test
  4. Both provided tests should fail with something similar to ReferenceError: Cannot access 'mockExampleClient' before initialization

Expected behavior

As stated in jests docs, I expect variables prepended with mock to be defined outside of the mock factory without issue.

A limitation with the factory parameter is that, since calls to jest.mock() are hoisted to the top of the file, it's not possible to first define a variable and then use it in the factory. An exception is made for variables that start with the word 'mock'.

Actual behavior

An error is thrown: ReferenceError: Cannot access 'mock' before initialization where mock is a variable defined outside of the moduleFactory parameter passed to jest.mock().

Additional context

continues #10996

Environment

System:
    OS: macOS 11.4
    CPU: (12) x64 Intel(R) Core(TM) i7-8850H CPU @ 2.60GHz
  Binaries:
    Node: 14.17.6 - ~/.nvm/versions/node/v14.17.6/bin/node
    npm: 6.14.15 - ~/.nvm/versions/node/v14.17.6/bin/npm
  npmPackages:
    jest: ^27.1.1 => 27.1.1
@SimenB
Copy link
Member

SimenB commented Sep 10, 2021

I think we need to improve the docs - the exception is that Jest doesn't throw when parsing the file, it's not an exception to the limitation. That limitation comes from how JS works and nothing we can do about it. The error message from the code is clearer than the docs: #11455 (comment)

@github-actions
Copy link

This issue has been automatically locked since there has not been any recent activity after it was closed. Please open a new issue for related bugs.
Please note this issue tracker is not a help forum. We recommend using StackOverflow or our discord channel for questions.

@github-actions github-actions bot locked as resolved and limited conversation to collaborators Mar 25, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

Successfully merging a pull request may close this issue.

2 participants