🧪 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 - 𝗦𝘁𝘂𝗯𝘀 𝘃𝘀 𝗦𝗽𝗶𝗲𝘀 𝘃𝘀 𝗠𝗼𝗰𝗸𝘀 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
Nitin Kumar’s Post
More Relevant Posts
-
⏱️ 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 𝗔𝘀𝘆𝗻𝗰𝗵𝗿𝗼𝗻𝗼𝘂𝘀 𝗖𝗼𝗱𝗲 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁 Async testing in JavaScript is one of those areas where things look correct — but fail silently if done wrong. 📞 🔙 𝗖𝗮𝗹𝗹𝗯𝗮𝗰𝗸-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 When your function depends on callbacks, your test must explicitly tell the test runner when it's done. it("should fetch data (callback)", (done) => { fetchData((err, data) => { if (err) return done(err); expect(data).toBe("hello"); done(); // critical! }); }); ❯❯❯❯ If you see callbacks → use done carefully. ⏳ 𝗣𝗿𝗼𝗺𝗶𝘀𝗲-𝗕𝗮𝘀𝗲𝗱 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 Cleaner than callbacks, but still easy to mess up. You must return the promise from your test. it("should fetch data (promise)", () => { return expect(fetchData()).resolves.toBe("hello"); }); ❯❯❯❯ Always return the promise OR use .resolves/.rejects. 🔄 𝗔𝘀𝘆𝗻𝗰/𝗔𝘄𝗮𝗶𝘁 𝗧𝗲𝘀𝘁𝗶𝗻𝗴 (𝗠𝗼𝗱𝗲𝗿𝗻 𝗦𝘁𝗮𝗻𝗱𝗮𝗿𝗱) The cleanest and most readable approach. it("should fetch data (async/await)", async () => { const data = await fetchData(); expect(data).toBe("hello"); }); Handling errors - it("should throw error", async () => { await expect(fetchData()).rejects.toThrow("error"); }); ❯❯❯❯ If you use async, always use await where needed. ✍ 𝗞𝗲𝘆 𝗧𝗮𝗸𝗲𝗮𝘄𝗮𝘆𝘀 ♦️ Callbacks → use done() ♦️ Promises → return the promise ♦️ Async/Await → use await properly ♦️ Always test both success AND failure paths. 👉 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 #async
To view or add a comment, sign in
-
-
⚡ 𝗦𝗮𝗺𝗲 `...` 𝗦𝘆𝗻𝘁𝗮𝘅, 𝗧𝗼𝘁𝗮𝗹𝗹𝘆 𝗗𝗶𝗳𝗳𝗲𝗿𝗲𝗻𝘁 𝗕𝗲𝗵𝗮𝘃𝗶𝗼𝗿 ⤵️ Spread vs Rest Operators in JavaScript 🧠 🔗 𝗥𝗲𝗮𝗱 𝗵𝗲𝗿𝗲: https://lnkd.in/drV-7dZa 𝗧𝗼𝗽𝗶𝗰𝘀 𝗰𝗼𝘃𝗲𝗿𝗲𝗱 ✍🏻: ⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺⎺ ⇢ Spread vs Rest — simple mental model ⇢ Expanding arrays & objects using spread ⇢ Collecting values using rest parameters ⇢ Key differences based on context ⇢ Real-world use cases (merge, clone, functions) ⇢ Common mistakes developers make ⇢ Tradeoffs: shallow copy & performance Thanks Hitesh Choudhary Sir & Piyush Garg Sir, and the amazing Chai Aur Code community 🙌 #ChaiAurCode #JavaScript #WebDevelopment #Programming #Frontend #CleanCode #Hashnode
To view or add a comment, sign in
-
😵💫𝗢𝗻𝗲 𝗼𝗳 𝘁𝗵𝗲 𝗺𝗼𝘀𝘁 𝗰𝗼𝗻𝗳𝘂𝘀𝗶𝗻𝗴 𝘁𝗵𝗶𝗻𝗴𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: `...` At first glance, it looks simple. But depending on where you use it, it completely changes its role. Same syntax. Different behavior. That’s where most developers get tripped up. So I decided to break it down clearly: ✍️ New Blog Published: 𝗦𝗽𝗿𝗲𝗮𝗱 𝘃𝘀 𝗥𝗲𝘀𝘁 𝗢𝗽𝗲𝗿𝗮𝘁𝗼𝗿𝘀 𝗶𝗻 𝗝𝗮𝘃𝗮𝗦𝗰𝗿𝗶𝗽𝘁: 𝗘𝘅𝗽𝗮𝗻𝗱 𝗼𝗿 𝗖𝗼𝗹𝗹𝗲𝗰𝘁 𝗟𝗶𝗸𝗲 𝗮 𝗣𝗿𝗼 https://lnkd.in/gFPgrdEv 🔍 What you’ll learn: 🔹 When ... acts as a Spread Operator (expanding data) 🔹 When it becomes a Rest Operator (collecting data) 🔹 Real-world use cases to eliminate confusion Hitesh Choudhary Piyush Garg Chai Aur Code Anirudh J. Akash Kadlag Suraj Kumar Jha Nikhil Rathore Jay Kadlag DEV Community #JavaScript #WebDevelopment #TechnicalWriting #LearningInPublic #Chaicode #Cohort
To view or add a comment, sign in
-
JavaScript in 2026: Temporal API makes dates actually good, Iterator helpers bring lazy evaluation, and RegExp.escape() finally exists after 15 years. Plus: TypeScript v6 is here, Vite dominates the build tool landscape, and 92% of devs are using AI to write code. Wild times. https://lnkd.in/gbNKWc4q #javascript #frontend
To view or add a comment, sign in
-
TypeScript 6.0 is here, and it's more than just another version bump. This release fundamentally changes how we think about type safety and performance in JavaScript development for 2026. Here are the key advanced features that will impact your codebase: 🧠 **Context-Aware Type Inference** Method syntax now works identically to arrow functions. TypeScript 6.0 checks if `this` is actually used before marking a function as "contextually sensitive," eliminating a major pain point in generic function calls. 🗺️ **#/ Subpath Imports** No more relative path hell. TypeScript now supports `#/` prefix for subpath imports, matching bundler conventions and cleaning up import statements across your codebase. ⚖️ **Stable Type Ordering** The new `--stableTypeOrdering` flag ensures deterministic type unions, eliminating noise when comparing compiler outputs. This prepares us for TypeScript 7.0's parallel type checking. ⏰ **Temporal API Types** Built-in types for the Temporal API are now included. Say goodbye to Date object headaches with proper timezone awareness, immutability, and a clean API. 🗺️ **Map Upsert Methods** `getOrInsert()` and `getOrInsertComputed()` eliminate the verbose "check-if-exists-then-set" pattern for Maps, reducing boilerplate and potential errors. 🛡️ **RegExp.escape()** Safer regex construction from user input with built-in escaping, preventing regex injection vulnerabilities. 🚨 Breaking Changes Alert TypeScript 6.0 introduces significant defaults changes: - `strict: true` by default - `module: esnext` by default - `types: []` by default (explicit is better!) - `target: es5` is deprecated These changes prepare us for TypeScript 7.0's native port and performance improvements. The migration requires attention but sets the stage for faster builds and more reliable type checking. TypeScript continues to evolve from a type checker into a comprehensive development platform. Full deep dive with code examples: https://lnkd.in/eBGiPbkE What TypeScript 6.0 feature are you most excited about? Share your thoughts below! #TypeScript #JavaScript #WebDevelopment #Programming #TypeScript6 #SoftwareEngineering #DeveloperTools #2026Tech
To view or add a comment, sign in
-
🚀 Async/Await in JavaScript — Write Asynchronous Code Like Synchronous! If Promises made async code cleaner, async/await made it beautiful. Let’s break it down 👇 🔹 What is async/await? • async makes a function return a Promise • await pauses execution until the Promise resolves 👉 It helps you write async code that looks and behaves like synchronous code. 🔹 Basic Example function fetchData() { return new Promise((resolve) => { setTimeout(() => resolve("Data received"), 2000); }); } async function getData() { const data = await fetchData(); console.log(data); } getData(); 🧠 Instead of chaining .then(), you write it step-by-step. 🔹 Error Handling Made Easy async function getData() { try { const data = await fetchData(); console.log(data); } catch (error) { console.error("Error:", error); } } ✅ No more messy .catch() chains ✅ Clean and readable error handling 🔹 Sequential vs Parallel Execution 👉 Sequential (waits one after another) await task1(); await task2(); 👉 Parallel (runs together) const [res1, res2] = await Promise.all([task1(), task2()]); ⚡ Use parallel execution for better performance when tasks are independent. 🔹 Common Mistakes to Avoid ❌ Using await outside async function ❌ Blocking loops with await unnecessarily ❌ Forgetting error handling 💡 Pro Tip: Async/await is just syntactic sugar over Promises — understanding Promises deeply makes async/await even more powerful. 🔥 Interview Question: What will be the output? async function test() { console.log("Start"); await Promise.resolve(); console.log("End"); } test(); console.log("Outside"); 👉 Comment your answer 👇 #JavaScript #AsyncAwait #WebDevelopment #Frontend #Coding #InterviewPrep
To view or add a comment, sign in
-
⚡ Shipped JavaScript & TypeScript support in AI-MR-Reviewer — a GitHub App that reviews your PRs the moment you open them. Inline comments on the diff. Clear severity levels. Zero setup. Built for teams who want fast, reliable feedback without heavy tooling. What lands in this release: ~18 focused JS/TS rules. 🔴 HIGH RISK — 7 rules == / != instead of === / !== Empty catch blocks (silent failures) eval() / new Function() usage innerHTML with dynamic content / dangerouslySetInnerHTML (XSS risk) setTimeout / setInterval with string arguments SQL injection patterns in .query() / .exec() (concat / template literals) Hardcoded secrets (API keys, tokens, passwords in code) 🟡 MID RISK — 7 rules console.log / debug statements in production var usage instead of let/const TypeScript any type usage // @ts-ignore / // @ts-nocheck Non-null assertions (!) on property access new Date() without timezone awareness Promises without .catch() or not awaited 🔵 LOW RISK — 4 rules TODO / FIXME comments left behind Numbered function names (handler2, doThing3) require() used inside ES modules Magic numbers outside constants Every rule is tuned to minimize noise and maximize real signal — so developers focus only on what actually matters. Under the hood: TypeScript · Node.js · Octokit · Express · Docker Reviews land within seconds of opening a PR. Next up: deeper semantic checks on top of this — smarter detection, fewer false positives, and richer context. If your team works with JS/TS daily, this removes friction from every PR. 🚀 Launching publicly by this Sunday, InshaAllah. #JavaScript #TypeScript #CodeReview #DeveloperTools #AI #StaticAnalysis #DevEx #OpenSource
To view or add a comment, sign in
-
-
JavaScript Proxy — A Hidden Superpower You Should Know Most of us create objects like this: const frameworkName = { name: "Next JS" }; But what if you could intercept and control every operation on this object? That’s exactly what JavaScript Proxy does. Think of it like a gatekeeper sitting in front of your object — it can monitor, modify, or block any interaction. const frameworkName = { name: "Angular" }; const proxyFramework = new Proxy(frameworkName, { get(target, prop) { console.log(`Reading ${prop}`); return target[prop]; }, set(target, prop, value) { console.log(`Updating ${prop} to ${value}`); if (value === "React") { console.log("React is not allowed!"); throw new Error("React is not allowed!"); // Throw an error to prevent the update return false; // Prevent the update } target[prop] = value; return true; } }); proxyFramework.name; // 👉 Reading name proxyFramework.name = "Next"; Why should you care? ✔ Track changes (great for debugging) ✔ Add validation before updating values ✔ Build reactive behavior (like frameworks do) ✔ Control or restrict access to data Real-world use cases: • Form validation without extra libraries • Logging state changes for debugging • Building custom state management • Data sanitization before saving Pro Tip: Frameworks like Vue use Proxy internally to make data reactive. Understanding this can level up your frontend skills. Have you used Proxy in your projects, or are you still sticking with plain objects? #JavaScript #FrontendDevelopment #WebDevelopment #ReactJS #Coding #Programming #LearnToCode
To view or add a comment, sign in
-
For years, importing JSON in JavaScript looked native — but it never really was. That illusion was created by bundlers. Now, with import attributes, JSON modules are finally supported natively by the platform — no build step required. What changed? Previously, this syntax was handled by bundlers at build time. The browser itself didn’t understand JSON as a module: import config from "./config.json"; Now we have a real, explicit standard. This tells the runtime exactly how to treat the file — as structured data, not executable code: import config from "./config.json" with { type: "json" }; Why with { type: "json" } matters JavaScript modules are executable, JSON is not. Without explicit typing, the runtime would have to guess how to handle the file — which creates ambiguity and potential security issues. Import attributes remove that guesswork: - no reliance on file extensions - no reliance on server headers - clear contract with the runtime Bundlers are still useful (optimization, hashing, inlining), but for JSON imports, the platform has finally caught up. Reference: https://lnkd.in/eJZW8t2A #javascript #webdev #frontend #esm #webplatform #json
To view or add a comment, sign in
-
🚀 JavaScript Simplified Series — Day 28 Promises made async code better… But still… something feels messy 😵 👉 Too many .then() 👉 Hard to read 👉 Looks like chaining hell What if async code could look like normal synchronous code? 🤔 🔥 Solution → Async / Await 🔹 The Problem with Promises fetchData() .then(data => { console.log(data) return processData(data) }) .then(result => { console.log(result) }) .catch(err => console.log(err)) 👉 Works… but not clean ❌ 🔹 Async / Await (Cleaner Way) async function handleData() { try { let data = await fetchData() console.log(data) let result = await processData(data) console.log(result) } catch (err) { console.log(err) } } handleData() 👉 Looks simple & readable ✅ 🔍 What is happening? 👉 async → function always returns a promise 👉 await → waits for promise to resolve 🔹 Example function fetchData() { return new Promise(resolve => { setTimeout(() => { resolve("Data received") }, 2000) }) } async function getData() { let data = await fetchData() console.log(data) } getData() 👉 Output: Data received 🔥 Real Life Example Think of cooking 🍳 👉 Order ingredients 👉 Wait for delivery 👉 Then cook With async/await: Step by step… clean and clear 🔥 Simple Summary async → makes function async await → waits for result Result → clean & readable code 💡 Programming Rule Write async code like sync code. Clarity > complexity. If you want to learn JavaScript in a simple and practical way, you can follow these YouTube channels: • Rohit Negi • Hitesh Choudhary (Chai aur Code) 📌 Series Progress Day 1 → What is JavaScript Day 2 → Variables & Data Types Day 3 → Type Conversion & Operators Day 4 → Truthy & Falsy + Comparison Operators Day 5 → If Else + Switch + Ternary Day 6 → Loops Day 7 → Break + Continue + Nested Loops Day 8 → Functions Basics Day 9 → Arrow + Default + Rest Parameters Day 10 → Callback & Higher Order Functions Day 11 → Arrays Basics Day 12 → Array Methods Day 13 → Array Iteration Day 14 → Advanced Array Methods Day 15 → Objects Basics Day 16 → Object Methods + this Day 17 → Object Destructuring Day 18 → Spread & Rest Day 19 → Advanced Objects Day 20 → DOM Introduction Day 21 → DOM Selectors Day 22 → DOM Manipulation Day 23 → Events Day 24 → Event Bubbling Day 25 → Event Delegation Day 26 → Async JavaScript Day 27 → Promises Day 28 → Async / Await Day 29 → Fetch API (Next Post) Follow for more 🚀 #JavaScriptSimplified #javascript #webdevelopment #coding #programming #learninpublic #100DaysOfCode #frontenddevelopment #devcommunity #codingjourney #softwaredeveloper #techcommunity #dailylearning #codeeveryday
To view or add a comment, sign in
Explore content categories
- Career
- Productivity
- Finance
- Soft Skills & Emotional Intelligence
- Project Management
- Education
- Technology
- Leadership
- Ecommerce
- User Experience
- Recruitment & HR
- Customer Experience
- Real Estate
- Marketing
- Sales
- Retail & Merchandising
- Science
- Supply Chain Management
- Future Of Work
- Consulting
- Writing
- Economics
- Artificial Intelligence
- Employee Experience
- Workplace Trends
- Fundraising
- Networking
- Corporate Social Responsibility
- Negotiation
- Communication
- Engineering
- Hospitality & Tourism
- Business Strategy
- Change Management
- Organizational Culture
- Design
- Innovation
- Event Planning
- Training & Development
Helpful