Node.js Course
Node.js
/
Advanced

Mocking Dependencies

Definition

Creating fake versions of external dependencies or functions to isolate the code being tested. It allows you to simulate scenarios that are difficult to trigger in reality.

Explain Like I'm New

Imagine testing a function that charges a user's credit card via Stripe. If you run the test 50 times, you don't want to actually charge your credit card $500! Mocking intercepts the call to Stripe, blocks the real network request, and instantly returns a fake 'Success!' response so your test can continue safely.

Real World Example

Using `jest.mock('axios')` to fake network requests. You tell the mock: 'If the code calls axios.get, immediately return this fake JSON object instead of hitting the internet'.

Common Use Cases

  • •Bypassing payment gateways during tests
  • •Simulating rare database crashes to test error handling
  • •Keeping unit tests fast

Interactive Example

Loading...
Console output will appear here...

Interview Questions

basic

  • What does a Mock function do?

intermediate

  • How does mocking help test Error Handlers?

Flash Cards

Question

What does a Mock do?

Click to reveal answer
Answer

It replaces a real function with a fake spy function. It tracks how many times it was called, what arguments it was passed, and allows you to force it to return specific values.

Question

How does it help test Errors?

Click to reveal answer
Answer

You can instruct a mock to intentionally throw an error (e.g., `mock.mockRejectedValue(new Error('Network Down'))`). This allows you to verify that your app's `catch` block safely handles a crashed API without actually having to unplug your internet.