-1

I got two difference cases when using vitest to write mocks:

case 1:

const mockedMethod = vi.fn();
vi.mock('./path/to/module.js', () => ({
  originalMethod: mockedMethod,
}));

case 2:

const mockedMethod = [1, 2, 3]; // Defined before vi.mock()
vi.mock('./path/to/module.js', () => ({
  originalMethod: mockedMethod,
}));

I wonder why for case 1, it will raise error to say mockedMethod is undefined. But for case 2, it will pass.

2
  • The question lacks stackoverflow.com/help/mcve , it's unknown what's the context for these cases and whether it's a single case with changed implementation or different ones. mockedMethod is accessed at the time when mocked module is imported. Since vi.mock is hoisted, any values it relies on should be wrapped with vi.hoisted in order to avoid such errors. In case this was the question, that's the answer Commented Apr 22 at 9:46
  • Best to ask this question to the Vitest devs directly, perhaps in a new discussion here. Commented yesterday

0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.