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

Invalid variable access: _jsxFileName #9896

Closed
FezVrasta opened this issue Oct 24, 2020 · 11 comments
Closed

Invalid variable access: _jsxFileName #9896

FezVrasta opened this issue Oct 24, 2020 · 11 comments
Milestone

Comments

@FezVrasta
Copy link
Contributor

FezVrasta commented Oct 24, 2020

Describe the bug

My tests are failing because I have some Jest mocks that use JSX. The error is Invalid variable access: _jsxFileName.

It seems to be related to jestjs/jest#10690

Did you try recovering your dependencies?

Yes.

Which terms did you search for in User Guide?

_jsxFileName

Environment

Environment Info:

  System:
    OS: macOS 10.15.7
    CPU: (4) x64 Intel(R) Core(TM) i5-4690 CPU @ 3.50GHz
  Binaries:
    Node: 14.5.0 - /usr/local/bin/node
    Yarn: 1.22.5 - /usr/local/bin/yarn
    npm: 6.14.5 - /usr/local/bin/npm
  Browsers:
    Chrome: 86.0.4240.111
    Firefox: 81.0
    Safari: 14.0
  npmPackages:
    react: ^16.6.3 => 16.14.0 
    react-dom: ^16.6.0 => 16.14.0 
    react-scripts: ^4.0.0 => 4.0.0 
  npmGlobalPackages:
    create-react-app: Not Found

Steps to reproduce

  1. create a test file
  2. add jest.mock('./someModule', () => () => <div />)
  3. run the tests to observe the error

Expected behavior

Tests should work.

Actual behavior

  ● Test suite failed to run

    ReferenceError: /Users/federicozivolo/Projects/[...]/frontend/src/__mocks__/material-ui.js: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: _jsxFileName
    Allowed objects: Array, ArrayBuffer, Atomics, BigInt, BigInt64Array, BigUint64Array, Boolean, Buffer, 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, SharedArrayBuffer, String, Symbol, SyntaxError, TextDecoder, TextEncoder, TypeError, URIError, URL, URLSearchParams, Uint16Array, Uint32Array, Uint8Array, Uint8ClampedArray, WeakMap, WeakSet, WebAssembly, arguments, clearImmediate, clearInterval, clearTimeout, console, decodeURI, decodeURIComponent, encodeURI, encodeURIComponent, escape, eval, expect, global, globalThis, isFinite, isNaN, jest, parseFloat, parseInt, process, queueMicrotask, require, setImmediate, setInterval, setTimeout, undefined, unescape.
    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.
     (This is an error on an internal node. Probably an internal error.)

      at File.buildCodeFrameError (node_modules/@babel/core/lib/transformation/file/file.js:250:12)
      at NodePath.buildCodeFrameError (node_modules/@babel/traverse/lib/path/index.js:163:21)

Reproducible demo

(Paste the link to an example project and exact instructions to reproduce the issue.)

@yann-combarnous
Copy link

Same here, I had to disable the new JSX transform for my tests to run.
DISABLE_NEW_JSX_TRANSFORM=true

@ghost
Copy link

ghost commented Oct 27, 2020

In my case, it was solved by creating a __mock__ folder with the mocked module, so instead of creating the mock inside the function as it was before

jest.mock('../folder/myModule', () => {
  return {
    __esModule: true,
    default: function myModule() {
      return <div>My Module</div>
    },
  }
})

I just pointed to the manual mock:

// Mock import
jest.mock('../folder/myModule')

// Folder structure
../folder/__mock__/myModule

//File in "../folder/__mock__/myModule"
import React from 'react'

function MyModule() {
  return <div>My Module</div>
}

export default Cover

Reference: https://jestjs.io/docs/en/manual-mocks

@stl-alehskrypko
Copy link

@yann-combarnous, how did you disabled new JSX transform? I tried adding process.env.DISABLE_NEW_JSX_TRANSFORM = 'true' to setupTests.js and directly in .env - doesn't seem to have any effect. Tried to console.log(process.env), and this flag is true, but I still experiencing this behavior.

@SimenB
Copy link
Contributor

SimenB commented Nov 2, 2020

Fixed in [email protected] or more specifically [email protected]. Updating your lockfile should resolve this 🤞

@ianschmitz
Copy link
Contributor

ianschmitz commented Nov 2, 2020

Jest is still pinned currently:

Will require us to bump the version.

Edit: I read your comment more closely @SimenB. I assume [email protected] will fuzzy match that fix?

@SimenB
Copy link
Contributor

SimenB commented Nov 2, 2020

Yep, just removing babel-plugin-jest-hoist from the lockfile and re-running yarn/npm will pull in the fix.

Bumping up the Jest version in CRA would be nice though. I plan to release one final v26 patch tomorrow before starting work on v27 - shipping the lastest 26 by default in CRA would be nice.

@iansu iansu modified the milestones: 4.0.1, 4.0.2 Nov 23, 2020
barrymcgee added a commit to canonical/juju-dashboard that referenced this issue Dec 7, 2020
barrymcgee added a commit to canonical/juju-dashboard that referenced this issue Dec 7, 2020
@mrmckeb mrmckeb modified the milestones: 4.0.2, 4.0.3 Feb 3, 2021
@MarkLyck
Copy link

MarkLyck commented Feb 9, 2021

Having this issue as well but none of the solutions here worked.

I am using CRA "react-scripts": "4.0.2",

@yann-combarnous I tried setting the env variable:

process.env.DISABLE_NEW_JSX_TRANSFORM = 'true'

Didn't work for me.

@lc-brunomonteiro I tried creating a manual mock. But also didn't work

@SimenB I already have [email protected] installed & the corresponding version of [email protected]

I tried clearing my yarn.lock and re-installing anyway, but did not help.

I tried updating to [email protected] (also didn't solve it).

any ideas why this would still be happening with [email protected]?

@SimenB
Copy link
Contributor

SimenB commented Feb 9, 2021

If none of the suggested fixes works for you you probably have a completely different issue

@MarkLyck
Copy link

MarkLyck commented Feb 9, 2021

@SimenB figured it out. It was due to my location of jest.mock() I needed to move it outside of my actual test so it could hoist properly.

before:

describe('stuff', () => {
  test('my test', () => {
     jest.mock('./myModule')
  })
})

after

jest.mock('./myModule')
 
describe('stuff', () => {
  test('my test', () => {
    
  })
})

I'll leave this here, since this is the only issue I found with the error I got. Hope it helps some one else.

@SimenB
Copy link
Contributor

SimenB commented Feb 9, 2021

weird, I'd have thought that worked fine as the variable should be in the outer scope already. Can you create an issue (with a reproduction) in the Jest repo?

@FlorTello
Copy link

FlorTello commented Jul 22, 2021

Using jest.doMock instead of jest.mock has helped me
When using babel-jest, calls to mock will automatically be hoisted to the top of the code block.
According to the documentation use this method jest.doMock if you want to explicitly avoid this behavior.
One example when this is useful is when you want to mock a module
https://jestjs.io/docs/jest-object#jestdomockmodulename-factory-options

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

No branches or pull requests

9 participants