Nitin Kumar’s Post

🧪 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 - 𝗦𝘁𝘂𝗯𝘀 𝘃𝘀 𝗦𝗽𝗶𝗲𝘀 𝘃𝘀 𝗠𝗼𝗰𝗸𝘀 When you start writing serious unit tests in JavaScript, you quickly realize that testing real dependencies (APIs, databases) makes your tests slow, flaky, and produces side effects. That’s where Stubs, Spies and Mocks come in. 🔍 𝗦𝗽𝗶𝗲𝘀 — “𝗢𝗯𝘀𝗲𝗿𝘃𝗲, 𝗱𝗼𝗻’𝘁 𝗶𝗻𝘁𝗲𝗿𝗳𝗲𝗿𝗲” A spy is used when you want to track how a function is called without changing its actual behavior. 𝗨𝘀𝗲 𝗖𝗮𝘀𝗲𝘀 ♦️ Was the function called? ♦️ How many times? ♦️ With what arguments? 👉 The original function still runs — you're just watching it. 🎭 𝗦𝘁𝘂𝗯𝘀 — “𝗖𝗼𝗻𝘁𝗿𝗼𝗹 𝘁𝗵𝗲 𝗯𝗲𝗵𝗮𝘃𝗶𝗼𝗿” A stub not only tracks calls but also replaces the actual implementation. 𝗨𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 ♦️ Avoid calling real APIs ♦️ Return predefined values ♦️ Simulate function execution 👉 The real function is never executed. 🎯 𝗠𝗼𝗰𝗸𝘀 — “𝗘𝘅𝗽𝗲𝗰𝘁𝗮𝘁𝗶𝗼𝗻 + 𝗩𝗲𝗿𝗶𝗳𝗶𝗰𝗮𝘁𝗶𝗼𝗻” A mock is like a strict version of a stub, you define expectations upfront and test fails if expectations are not met. 𝗨𝘀𝗲 𝗰𝗮𝘀𝗲𝘀 ♦️ When interaction itself is critical ♦️ You want strict contract testing Example -  const mock = sinon.mock(api); mock.expects("getUser")   .once()   .returns({ id: 1 }); api.getUser(); mock.verify(); 👉 If getUser() is not called → test fails. 🧠 𝗪𝗵𝗲𝗻 𝘁𝗼 𝗨𝘀𝗲 𝗪𝗵𝗮𝘁? 🔍 Use Spies → When you want visibility (logging, analytics, side effects) 🎭 Use Stubs → When you need control (API, DB, randomness) 🎯 Use Mocks → When behavior contract matters (critical flows) 🧰 𝗦𝗶𝗻𝗼𝗻.𝗷𝘀 𝗟𝗶𝗯𝗿𝗮𝗿𝘆 Sinon.js is a powerful standalone library for -  ♦️ Spies ♦️ Stubs ♦️ Mocks ♦️ Fake timers ♦️ Works with any test framework (Mocha, Jest, etc.) 👉 We’ll dive deeper into 𝗔𝘀𝘆𝗻𝗰 𝗖𝗼𝗱𝗲 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 in the upcoming posts. Stay tuned!! 🔔 Follow Nitin Kumar for daily valuable insights on LLD, HLD, Distributed Systems and AI. ♻️ Repost to help others in your network. #javascript #nodejs #testing #tdd #mocha #sinon

  • graphical user interface, text

To view or add a comment, sign in

Explore content categories