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

Jest depends on mock function variable name #8148

Closed
MathObsessed opened this issue Mar 18, 2019 · 3 comments
Closed

Jest depends on mock function variable name #8148

MathObsessed opened this issue Mar 18, 2019 · 3 comments

Comments

@MathObsessed
Copy link

MathObsessed commented Mar 18, 2019

Hello, kind people!

I'm very puzzled at the moment with the following behaviour:

const mockRequestHandler = jest.fn(async context => (context.body = ''))

jest.mock('../requestHandler', () => mockRequestHandler)

const server = require('../server')
const request = require('supertest')

afterEach(() => {
    server.close()
    jest.clearAllMocks()
})

it('Returns HTTP code 200 on GET request to "/"', async () => {
    const response = await request(server).get('/')

    expect(mockRequestHandler).toHaveBeenCalledTimes(1)
    expect(response.status).toBe(200)
})

This code works. But once I change the variable name from "mockRequestHandler" to "requestHandler" or "requestHandlerMock" Jest throws an exception:

babel-plugin-jest-hoist: The module factory of `jest.mock()` is not allowed to reference any out-of-scope variables.
    Invalid variable access: requestHandlerMock
@thymikee
Copy link
Collaborator

Can you please follow the bug report template and add a repro?

@SimenB
Copy link
Member

SimenB commented Mar 18, 2019

Yeah, this is expected. Since we hoist jest.mock calls, most initializing code does not run. You can tell Jest that you know what you're doing by prefixing the variable with mock

@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 May 12, 2021
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Projects
None yet
Development

No branches or pull requests

3 participants