Home
Jobs

Mocking & Spies Interview Questions

Comprehensive mocking & spies interview questions and answers for Jest. Prepare for your next job interview with expert guidance.

24 Questions Available

Questions Overview

1. What is jest.fn() and how is it used?

Basic

jest.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()?

Basic

jest.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()?

Basic

Key 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?

Basic

Module 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?

Basic

Mock 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?

Basic

Mock 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?

Basic

mockClear(): 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?

Basic

Async 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?

Basic

Manual 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?

Basic

ES6 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?

Moderate

Partial 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?

Moderate

Mock 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?

Moderate

Timer 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?

Moderate

HTTP 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?

Moderate

Complex 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?

Moderate

Limitations 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?

Moderate

Native 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?

Moderate

Mock 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?

Moderate

Mock 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?

Moderate

Mock 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?

Advanced

Advanced 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?

Advanced

Complex 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?

Advanced

Stateful 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?

Advanced

Orchestration 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.

Mocking & Spies Interview Questions Faq

What types of interview questions are available?

Explore a wide range of interview questions for freshers and professionals, covering technical, business, HR, and management skills, designed to help you succeed in your job interview.

Are these questions suitable for beginners?

Yes, the questions include beginner-friendly content for freshers, alongside advanced topics for experienced professionals, catering to all career levels.

How can I prepare for technical interviews?

Access categorized technical questions with detailed answers, covering coding, algorithms, and system design to boost your preparation.

Are there resources for business and HR interviews?

Find tailored questions for business roles (e.g., finance, marketing) and HR roles (e.g., recruitment, leadership), perfect for diverse career paths.

Can I prepare for specific roles like consulting or management?

Yes, the platform offers role-specific questions, including case studies for consulting and strategic questions for management positions.

How often are the interview questions updated?

Questions are regularly updated to align with current industry trends and hiring practices, ensuring relevance.

Are there free resources for interview preparation?

Free access is available to a variety of questions, with optional premium resources for deeper insights.

How does this platform help with interview success?

Get expert-crafted questions, detailed answers, and tips, organized by category, to build confidence and perform effectively in interviews.