`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 mock
is 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:
- Created 3 years ago
- Reactions:13
- Comments:11
This is happening to me, too:
index.test.ts
:Jest output:
package.json
:You may use this:
in your test block::