Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

ReferenceError: Cannot access mock before initialization when using vitest

On the top of my test file, I have:

const setExMock = vi.fn()

Then I mock the Redis module (which works)

vi.mock('redis', () => {
  return {
    createClient: () => {
      return {
        connect: vi.fn(),
        get: vi.fn(),
        setEx: setExMock,
      }
    },
  }
})

Then I get the error:

ReferenceError: Cannot access 'setExMock' before initialization

Why I'm doing this? Because I want to check on my tests if setExMock was called with some parameters.

I know that vitest hoistes the mock, but how can I do this? I looked at the documentation and haven't found anything.

like image 203
Rodrigo Avatar asked Jul 13 '26 12:07

Rodrigo


1 Answers

Found the solution, it is necessary to wrap into a hoisted method

const { setExMock } = vi.hoisted(() => {
  return { setExMock: vi.fn() }
})
like image 184
Rodrigo Avatar answered Jul 15 '26 07:07

Rodrigo