Skip to content

Variables with names starting with mock are not considered when hoisting jest.mock() calls #5448

@jackyef

Description

@jackyef

With babel-jest it seems like jest.mock() calls are hoisted to the top of the file. swc seems to have this transformation as well, so no issue with that.

The problem occurs when the jest.mock() calls depends on other variable, for instance:

const mockCreate = jest.fn().mockResolvedValue(undefined)
jest.mock('twilio', () => () => ({ messages: { create: mockCreate } }))

With babel, this code works fine because jest makes an exception for variables with names starting with mock. With swc, it seems like this isn't the case and we end up with the following error:

ReferenceError: Cannot access 'mockCreate' before initialization

Quoting this comment from ts-jest repo: kulshekhar/ts-jest#1088 (comment)

What happens is that when doing the hoisting for mock, the babel plugin checks variables that are being used in the mock factory to ensure that everything being used will be within scope after hoisting.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions