question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. ItĀ collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

`ReferenceError: Cannot access 'myMock' before initialization` even though the rule is respected

See original GitHub issue

šŸ› Bug Report

I’m getting the error:

ReferenceError: Cannot access 'myMock' before initialization

Even though i respected jest documentation about the hoisting: 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’.

what i’m doing:

import MyClass from './my_class';
import * as anotherClass from './another_class';

const mockMethod1 = jest.fn();
const mockMethod2 = jest.fn();
jest.mock('./my_class', () => {
  return {
    default: {
      staticMethod: jest.fn().mockReturnValue(
        {
          method1: mockMethod1,
          method2: mockMethod2,
        })
    }
  }
});

As you can see, i’m mocking a singleton class. The static method (here: staticMethod) is the entry point of my class.

To Reproduce

Steps to reproduce the behavior: Having a singleton class like so:

class MyClass {
  private instance

  private constructor(){ /* constructor thing */}

  static staticMethod(){
     if MyClass.instance { return MyClass.instance}

     /* do constructor etc....*/
     }
}
```

And i'm using this in the file I actually want to test:

```typescript
import MyClass from '/path/to/myClass'

const myClass = MyClass.staticMethod()

/* business logic goes here */

About the test file, you can see what i’m doing above.

Expected behavior

Not throwing ReferenceError: Cannot access 'myMock' before initialization when the rule about mock variable starting with mockis respected.

Link to repl or repo (highly encouraged)

envinfo

  System:
    OS: macOS 10.15.5
    CPU: (16) x64 Intel(R) Core(TM) i9-9980HK CPU @ 2.40GHz
  Binaries:
    Node: 12.18.4 - ~/.nvm/versions/node/v12.18.4/bin/node
    npm: 6.14.6 - ~/.nvm/versions/node/v12.18.4/bin/npm
  npmPackages:
    jest: ^26.6.3 => 26.6.3 

Thanks in advance for any help !

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Reactions:13
  • Comments:11

github_iconTop GitHub Comments

16reactions
kylegoetzcommented, Feb 1, 2021

This is happening to me, too:

index.test.ts:

const mockUseAuthToken = jest.fn()

jest.mock('../../../src/hooks/use-auth-token', () => ({
	useAuthToken: mockUseAuthToken,
}))

Jest output:

ReferenceError: Cannot access 'mockUseAuthToken' before initialization

       8 | 
       9 | jest.mock('../../../src/hooks/use-auth-token', () => ({

package.json:

"jest": "26.6.3"

This was working before upgrading Jest. Previously was on `26.0.1`.
5reactions
amitnskycommented, Feb 3, 2021

You may use this:

import { X } from 'path/to/module'

jest.mock('path/to/module', () => ({
    X: jest.fn()
}));

in your test block::

expect(X).toHaveBeenCalled()
Read more comments on GitHub >

github_iconTop Results From Across the Web

jest ReferenceError: Cannot access '' before initialization
I was trying using let outside of the jest.mock to assign it internally and it was failing. Using var solved my problem. Thanks....
Read more >
Fix jest mock 'Cannot access before initialization' error
"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...
Read more >
jest mock cannot access before initialization - You.com
ReferenceError : Cannot access 'myMock' before initialization. Even though i respected jest documentation about the hoisting: A limitation with the factoryĀ ...
Read more >
Fix Jest mock 'cannot access before initialization' error : r/reactjs
If you start your variables with the word 'mock' for jest, you might have fallen into this misconception. If you don't, learn the...
Read more >
Node.js v19.3.0 Documentation
Welcome to the official API reference documentation for Node.js! ... Error names and messages are always compared, even if these are not enumerableĀ ......
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found