Mocking & Spies Interview Questions
Comprehensive mocking & spies interview questions and answers for Jest. Prepare for your next job interview with expert guidance.
Questions Overview
1. What is jest.fn() and how is it used?
Basic2. How do you use jest.spyOn()?
Basic3. What is the difference between jest.fn() and jest.spyOn()?
Basic4. How do you mock modules in Jest?
Basic5. What are mock return values and how are they set?
Basic6. How do you verify mock calls?
Basic7. What is mock.mockClear() and when should it be used?
Basic8. How do you mock async functions?
Basic9. What are manual mocks and how are they created?
Basic10. How do you mock ES6 classes in Jest?
Basic11. How do you implement partial module mocking?
Moderate12. What are mock implementations and how are they used?
Moderate13. How do you mock timers in Jest?
Moderate14. What are the strategies for mocking HTTP requests?
Moderate15. How do you handle complex mock return sequences?
Moderate16. What are mocked modules limitations?
Moderate17. How do you mock native JavaScript objects?
Moderate18. What are mock contexts and how are they used?
Moderate19. How do you handle mock cleanup and restoration?
Moderate20. What are mock factories and how are they implemented?
Moderate21. How do you implement advanced module mocking patterns?
Advanced22. What are strategies for mocking complex async patterns?
Advanced23. How do you implement stateful mocks?
Advanced24. What are mock orchestration patterns?
Advanced1. What is jest.fn() and how is it used?
Basicjest.fn() creates a mock function that allows: 1) Tracking calls and arguments, 2) Setting return values using mockReturnValue(), 3) Implementing custom behavior using mockImplementation(), 4) Clearing/resetting mock data, 5) Verifying call conditions. Example: const mock = jest.fn().mockReturnValue('result');
2. How do you use jest.spyOn()?
Basicjest.spyOn() is used to: 1) Monitor method calls on objects, 2) Preserve original implementation while tracking calls, 3) Temporarily mock method behavior, 4) Restore original implementation using mockRestore(), 5) Access call history and mock functionality. Example: jest.spyOn(object, 'method')
3. What is the difference between jest.fn() and jest.spyOn()?
BasicKey differences: 1) jest.fn() creates new mock functions while spyOn monitors existing ones, 2) spyOn can restore original implementation, jest.fn() cannot, 3) spyOn requires an object and method, jest.fn() is standalone, 4) spyOn preserves original method by default, 5) jest.fn() starts as empty function.
4. How do you mock modules in Jest?
BasicModule mocking uses: 1) jest.mock() for automatic mocking, 2) Manual mocks in __mocks__ directory, 3) mockImplementation() for custom behavior, 4) requireActual() for partial mocking, 5) hoisting of jest.mock() calls. Example: jest.mock('./module', () => ({ method: jest.fn() }));
5. What are mock return values and how are they set?
BasicMock return values can be set using: 1) mockReturnValue() for fixed values, 2) mockReturnValueOnce() for single calls, 3) mockImplementation() for custom logic, 4) mockResolvedValue() for promises, 5) mockRejectedValue() for promise rejections. Example: mock.mockReturnValue('result');
6. How do you verify mock calls?
BasicMock calls verified using: 1) toHaveBeenCalled() for call checking, 2) toHaveBeenCalledWith() for argument checking, 3) toHaveBeenCalledTimes() for call count, 4) mock.calls array for detailed inspection, 5) mock.results for return values. Example: expect(mock).toHaveBeenCalledWith(arg);
7. What is mock.mockClear() and when should it be used?
BasicmockClear(): 1) Resets call history of mock function, 2) Used between tests to ensure isolation, 3) Doesn't reset implementation or return values, 4) Often used in beforeEach, 5) Helps prevent test interdependence. Example: beforeEach(() => { mock.mockClear(); });
8. How do you mock async functions?
BasicAsync mocking involves: 1) mockResolvedValue() for successful promises, 2) mockRejectedValue() for failed promises, 3) mockImplementation() with async functions, 4) Chain .then handlers for complex cases, 5) Await mock function calls in tests. Example: mock.mockResolvedValue('result');
9. What are manual mocks and how are they created?
BasicManual mocks: 1) Created in __mocks__ directory, 2) Match module name and structure, 3) Exported as module.exports, 4) Can include complex implementations, 5) Automatically used when module is required. Used for consistent mock implementations across tests.
10. How do you mock ES6 classes in Jest?
BasicES6 class mocking: 1) Use jest.mock() for class, 2) Mock constructor and methods, 3) Implement instance methods with mockImplementation, 4) Mock static methods directly, 5) Handle inheritance if needed. Example: jest.mock('./MyClass', () => { return jest.fn().mockImplementation(() => { return {method: jest.fn()}; }); });
11. How do you implement partial module mocking?
ModeratePartial mocking involves: 1) Using jest.mock() with partial implementations, 2) requireActual() for original methods, 3) Mixing real and mocked exports, 4) Careful management of module state, 5) Clear documentation of mixed implementation. Example: jest.mock('./module', () => ({ ...jest.requireActual('./module'), specificMethod: jest.fn() }));
12. What are mock implementations and how are they used?
ModerateMock implementations: 1) Set using mockImplementation(), 2) Define custom behavior, 3) Can access call arguments, 4) Support async operations, 5) Can be changed between tests. Example: mock.mockImplementation((arg) => arg * 2);
13. How do you mock timers in Jest?
ModerateTimer mocking uses: 1) jest.useFakeTimers(), 2) jest.advanceTimersByTime(), 3) jest.runAllTimers(), 4) jest.runOnlyPendingTimers(), 5) jest.clearAllTimers(). Helps test setTimeout, setInterval, etc. Example: jest.useFakeTimers(); jest.advanceTimersByTime(1000);
14. What are the strategies for mocking HTTP requests?
ModerateHTTP request mocking: 1) Mock fetch/axios globally, 2) Use jest.mock() for HTTP clients, 3) Implement custom response handling, 4) Mock different response scenarios, 5) Handle async behavior properly. Consider using libraries like jest-fetch-mock.
15. How do you handle complex mock return sequences?
ModerateComplex sequences using: 1) mockReturnValueOnce() chain, 2) mockImplementation with state, 3) Array of return values, 4) Conditional return logic, 5) Mock result queues. Example: mock.mockReturnValueOnce(1).mockReturnValueOnce(2).mockReturnValue(3);
16. What are mocked modules limitations?
ModerateLimitations include: 1) Hoisting requirements, 2) ES6 module constraints, 3) Dynamic import challenges, 4) Circular dependency issues, 5) Reset complexities. Understanding helps avoid common pitfalls and design better tests.
17. How do you mock native JavaScript objects?
ModerateNative object mocking: 1) Use jest.spyOn on prototype, 2) Mock specific methods, 3) Restore original behavior, 4) Handle inheritance chain, 5) Consider side effects. Example: jest.spyOn(console, 'log').mockImplementation();
18. What are mock contexts and how are they used?
ModerateMock contexts provide: 1) Custom this binding, 2) Shared state between calls, 3) Instance method simulation, 4) Constructor behavior, 5) Method chaining support. Used for complex object mocking scenarios.
19. How do you handle mock cleanup and restoration?
ModerateMock cleanup involves: 1) Using mockReset(), 2) mockRestore() for spies, 3) Cleanup in afterEach, 4) Handling partial restorations, 5) Managing global mocks. Ensures test isolation and prevents side effects.
20. What are mock factories and how are they implemented?
ModerateMock factories: 1) Create reusable mock configurations, 2) Generate consistent test doubles, 3) Support parameterization, 4) Enable mock composition, 5) Facilitate maintenance. Example: const createMock = (config) => jest.fn().mockImplementation(config);
21. How do you implement advanced module mocking patterns?
AdvancedAdvanced patterns include: 1) Dynamic mock generation, 2) Mock inheritance chains, 3) Conditional mock behavior, 4) Mock composition, 5) State-dependent mocking. Used for complex module interactions.
22. What are strategies for mocking complex async patterns?
AdvancedComplex async mocking: 1) Chain multiple async operations, 2) Handle race conditions, 3) Mock streaming interfaces, 4) Simulate timeouts, 5) Test error scenarios. Example: mock.mockImplementation(async () => { /* complex async logic */ });
23. How do you implement stateful mocks?
AdvancedStateful mocks require: 1) Internal state management, 2) State-dependent behavior, 3) State reset mechanisms, 4) State verification, 5) Thread-safe state handling. Used for complex behavioral simulation.
24. What are mock orchestration patterns?
AdvancedOrchestration patterns: 1) Coordinate multiple mocks, 2) Manage mock interactions, 3) Synchronize mock behavior, 4) Handle mock dependencies, 5) Implement mock workflows. Used for system-level testing.