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?