When using Jest mocks, it’s easy to hit this error:

ReferenceError: Cannot access '...' before initialization


This is a bit vague and difficult to figure out if you don’t know what the issue is.

This error is due to the way Jest hoists mocks to the top.

For example if you have this in a test file:

const fooServiceFooFunction = jest.fn();

jest.mock("@foo-provider/some-library", () => ({
fooService: () => ({
foobar: fooServiceFooFunction,
}),
}));


It looks like it should work fine as the fooServiceFooFunction mock function is initialised before jest.mock() is called to apply the mock.

The problem is that Jest hoists the mock to the top, so what actually runs is more like this:

jest.mock("@foo-provider/some-library", () => ({
fooService: () => ({
foobar: fooServiceFooFunction,
}),
}));

const fooServiceFooFunction = jest.fn();


Now you’ll get the ReferenceError: Cannot access 'fooServiceFooFunction' before initialization error, because the mock set up call is trying to access that variable before it’s initialised.

You can avoid this problem by not referencing the mock function immediately, and instead wrapping it in an outer function call so that it only gets referenced at call time:

const fooServiceFooFunction = jest.fn();

jest.mock("@foo-provider/some-library", () => ({
fooService: () => ({
foobar: async () => fooServiceFooFunction(),
}),
}));


Now the mock function won’t be referenced until it’s actually called, by which time the function has been initialised.

By the way, you can hire me as a freelance TypeScript developer to work on your project.