Home
Jobs

Mocking & Stubbing Interview Questions

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

26 Questions Available

Questions Overview

1. What is the difference between mocks and stubs?

Basic

Key differences include: 1) Stubs provide canned answers to calls, 2) Mocks verify behavior and interactions, 3) Stubs don't typically fail tests, 4) Mocks can fail tests if expected behavior doesn't occur, 5) Stubs are simpler and used for state testing while mocks are used for behavior testing.

2. What mocking libraries can be used with Mocha?

Basic

Common mocking libraries: 1) Sinon.js for comprehensive mocking, 2) Jest mocks when using Jest, 3) testdouble.js for test doubles, 4) Proxyquire for module mocking, 5) Nock for HTTP mocking. Each has specific use cases and features.

3. How do you create a basic stub with Sinon?

Basic

Creating stubs with Sinon: 1) sinon.stub() creates stub function, 2) .returns() sets return value, 3) .throws() makes stub throw error, 4) .callsFake() provides implementation, 5) .resolves()/.rejects() for promises. Example: const stub = sinon.stub().returns('value');

4. What are spies and how are they used?

Basic

Spies are used to: 1) Track function calls, 2) Record arguments, 3) Check call count, 4) Verify call order, 5) Monitor return values. Example: const spy = sinon.spy(object, 'method'); Test wraps existing functions without changing behavior.

5. How do you mock HTTP requests?

Basic

HTTP mocking approaches: 1) Use Nock for HTTP mocks, 2) Mock fetch/axios globally, 3) Stub specific endpoints, 4) Mock response data, 5) Simulate network errors. Example: nock('http://api.example.com').get('/data').reply(200, { data: 'value' });

6. What is module mocking and how is it implemented?

Basic

Module mocking involves: 1) Using Proxyquire or similar tools, 2) Replacing module dependencies, 3) Mocking specific exports, 4) Maintaining module interface, 5) Handling module side effects. Helps isolate code under test.

7. How do you verify mock/stub calls?

Basic

Call verification includes: 1) Check call count with calledOnce/Twice, 2) Verify arguments with calledWith, 3) Check call order with calledBefore/After, 4) Verify call context with calledOn, 5) Assert on return values.

8. What are sandboxes in Sinon and why use them?

Basic

Sinon sandboxes: 1) Group mocks/stubs together, 2) Provide automatic cleanup, 3) Isolate test setup, 4) Prevent mock leakage, 5) Simplify test maintenance. Example: const sandbox = sinon.createSandbox(); sandbox.restore();

9. How do you handle mock cleanup?

Basic

Mock cleanup approaches: 1) Use afterEach hooks, 2) Implement sandbox restoration, 3) Reset individual mocks, 4) Clean up module mocks, 5) Restore original implementations. Prevents test interference.

10. What are fake timers and how are they used?

Basic

Fake timers: 1) Mock Date/setTimeout/setInterval, 2) Control time progression, 3) Test time-dependent code, 4) Simulate delays without waiting, 5) Handle timer cleanup. Example: sinon.useFakeTimers();

11. How do you mock promises with Sinon?

Moderate

Promise mocking: 1) Use stub.resolves() for success, 2) Use stub.rejects() for failure, 3) Chain promise behavior, 4) Mock async operations, 5) Test error handling. Example: stub.resolves('value');

12. What are strategies for mocking databases?

Moderate

Database mocking: 1) Mock database drivers, 2) Stub query methods, 3) Mock connection pools, 4) Simulate database errors, 5) Handle transactions. Isolates tests from actual database.

13. How do you mock file system operations?

Moderate

File system mocking: 1) Mock fs module, 2) Stub file operations, 3) Simulate file errors, 4) Mock file content, 5) Handle async operations. Example: using mock-fs or similar libraries.

14. What are patterns for mocking event emitters?

Moderate

Event emitter mocking: 1) Stub emit methods, 2) Mock event handlers, 3) Simulate event sequences, 4) Test error events, 5) Verify event data. Important for event-driven code.

15. How do you mock external APIs?

Moderate

API mocking approaches: 1) Use HTTP mocking libraries, 2) Mock API clients, 3) Simulate API responses, 4) Handle API errors, 5) Mock authentication. Isolates from external dependencies.

16. What are strategies for mocking WebSocket connections?

Moderate

WebSocket mocking: 1) Mock socket events, 2) Simulate messages, 3) Test connection states, 4) Handle disconnects, 5) Mock real-time data. Important for real-time applications.

17. How do you handle partial mocking?

Moderate

Partial mocking: 1) Mock specific methods, 2) Keep original behavior, 3) Combine real/mock functionality, 4) Control mock scope, 5) Handle method dependencies. Useful for complex objects.

18. What are patterns for mocking class instances?

Moderate

Instance mocking: 1) Mock constructors, 2) Stub instance methods, 3) Mock inheritance chain, 4) Handle static methods, 5) Mock instance properties. Important for OOP testing.

19. How do you mock environment variables?

Moderate

Environment mocking: 1) Mock process.env, 2) Stub configuration, 3) Handle different environments, 4) Restore original values, 5) Mock system info. Important for configuration testing.

20. How do you implement advanced mock behaviors?

Advanced

Advanced behaviors: 1) Dynamic responses, 2) Conditional mocking, 3) State-based responses, 4) Complex interactions, 5) Chainable behaviors. Enables sophisticated testing scenarios.

21. What are strategies for mocking microservices?

Advanced

Microservice mocking: 1) Mock service communication, 2) Simulate service failures, 3) Test service discovery, 4) Mock service registry, 5) Handle distributed state. Important for distributed systems.

22. How do you implement custom mock factories?

Advanced

Mock factories: 1) Create reusable mocks, 2) Generate test data, 3) Configure mock behavior, 4) Handle mock lifecycle, 5) Maintain mock consistency. Improves test maintainability.

23. What are patterns for mocking streaming data?

Advanced

Stream mocking: 1) Mock stream events, 2) Simulate data flow, 3) Test backpressure, 4) Handle stream errors, 5) Mock transformations. Important for stream processing.

24. How do you mock complex authentication flows?

Advanced

Auth flow mocking: 1) Mock auth providers, 2) Simulate tokens, 3) Test permissions, 4) Mock sessions, 5) Handle auth errors. Important for security testing.

25. What are strategies for mocking native modules?

Advanced

Native module mocking: 1) Mock binary modules, 2) Handle platform specifics, 3) Mock system calls, 4) Test native interfaces, 5) Handle compilation. Important for low-level testing.

26. How do you implement mock monitoring?

Advanced

Mock monitoring: 1) Track mock usage, 2) Monitor interactions, 3) Collect metrics, 4) Analyze patterns, 5) Generate reports. Important for test analysis.

Mocking & Stubbing 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.