Explore essential concepts and best practices for mocking functions using Jest, a popular JavaScript testing tool. This quiz challenges your understanding of spy utilities, mock implementations, and advanced mocking behaviors within Jest's tools ecosystem.
Which method allows you to mock a specific function from an imported module when writing tests in Jest?
Explanation: jest.mock('moduleName') is correct, as it enables you to replace the entire module, including its exported functions, with mocked implementations. jest.fn('moduleFunction') only creates standalone mock functions and cannot directly mock imported module functions. spyOn('moduleFunction') is not the correct syntax for Jest, and mockFunction('moduleName') is not a valid Jest method.
If you need a mocked function in Jest to return different values for each call, which method should you use in your test definition?
Explanation: mockReturnValueOnce is the correct way to set up a Jest mock that returns different values on consecutive calls, ideal for testing various scenarios. mockResolvedValue is used for promises but always returns the same value. mockCalledWith is not a recognized Jest method. mockOnCall sounds similar but is not part of the Jest API.
When using Jest to mock a function, which property stores the arguments passed to the mock in each invocation?
Explanation: mock.calls is the correct property that contains arrays of arguments used in each invocation of the mock function. mock.arguments does not exist in Jest. mock.instances stores instances created by the mock when used as a constructor. mockValues is not a recognized property in Jest.
In which scenario should you use jest.clearAllMocks() instead of jest.resetAllMocks() to manage mocks between tests?
Explanation: jest.clearAllMocks() clears usage information like call count and arguments, but retains the mock implementation. jest.resetAllMocks() resets both usage data and implementation to the default state. Removing mock functions entirely or one-time mocking is not the purpose of either method.
What is the correct way in Jest to make a mocked function resolve to a specific value when it is awaited?
Explanation: mockResolvedValue sets up the mock to return a promise that resolves to the given value, which is suitable for async tests. mockReturnThisValue is not a Jest method. mockPromiseValue and resolveValueMock are also incorrect, as they do not exist in Jest's API.