What is a stub in Node.js ? Last Updated : 19 Aug, 2020 Summarize Comments Improve Suggest changes Share Like Article Like Report A small program routine that substitutes for a longer program which is possible to be loaded later or that is remotely located. Features of stub: Stubs can be either anonymous. Stubs can be wrapped into existing functions. When we wrap a stub into the existing function the original function is not called. Stubs are functions or programs that affect the behavior of components or modules. Stubs are dummy objects for testing. Stubs implement a pre-programmed response. Example: javascript var fs = require('fs') var writeFileStub = sinon.stub(fs, 'writeFile', function (path, data, cb) { return cb(null) }) expect(writeFileStub).to.be.called writeFileStub.restore() When to use stubs? Prevent a specific method from being called directly. Controlling method behavior down a specific path from a test to force the code. For example: Error handling. Replacing the problematic pieces of code. Testing asynchronous code easy. Example To Create Asynchronous Stub That Throws An Exception: javascript require("@fatso83/mini-mocha").install(); const sinon = require("sinon"); const PubSub = require("pubsub-js"); const referee = require("@sinonjs/referee"); const assert = referee.assert; describe("PubSub", function() { it("Calling all the subscribers, irrespective of exceptions.", function() { const message = "an example message"; const stub = sinon.stub().throws(); const spy1 = sinon.spy(); const spy2 = sinon.spy(); const clock = sinon.useFakeTimers(); PubSub.subscribe(message, stub); PubSub.subscribe(message, spy1); PubSub.subscribe(message, spy2); assert.exception(()=>{ PubSub.publishSync(message, "some data"); clock.tick(1); }); assert.exception(stub); assert(spy1.called); assert(spy2.called); assert(stub.calledBefore(spy1)); clock.restore(); }); }); Output: Calling all the subscribers, irrespective of exceptions. Example Of Stubs: Let us consider an example of an e-commerce website for purchasing items. If we are successful a mail will be sent to the customer. javascript const purchaseItems(cartItems, user)=>{ let payStatus = user.paymentMethod(cartItems) if (payStatus === "successful") { user.SuccessMail() } else { user.redirect("error_page_of_payment") } } } function() { // Mail will be send for successful payment. let paymentStub = sinon.stub().returns("successful") let mailStub = sinon.stub( let user = { paymentMethod: paymentStub, SuccessMail: mailStub } purchaseItems([], user) assert(mailStub.called) } Example 1: A Simple Example To Execute Stubs. html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <div id="mocha"></div> </body> </html> html <!DOCTYPE html> <html> <head> <script> mocha.setup('bdd'); function saveUser(user, callback) { $.post('/users', { first: user.firstname, last: user.lastname }, callback); } describe('saveUser', function () { it('should call callback after saving', function () { // We'll stub $.post so a // request is not sent var post = sinon.stub($, 'post'); post.yields(); // We can use a spy as the callback // so it's easy to verify var callback = sinon.spy(); saveUser({ firstname: 'Han', lastname: 'Solo' }, callback); post.restore(); sinon.assert.calledOnce(callback); }); }); mocha.run(); </script> </head> </html> Output: Example 2: html <!DOCTYPE html> <html> <head> <title>Page Title</title> </head> <body> <h1>GeeksForGeeks</h1> <div id="mocha"></div> </body> </html> html <!DOCTYPE html> <html> <head> <script> mocha.setup('bdd'); function saveUser(user, callback) { $.post('/users', { first: user.firstname, last: user.lastname }, callback); } describe('saveUser', function () { it( 'It will send the correct parameters to the expected URL', function () { // We'll stub $.post same as before var post = sinon.stub($, 'post'); // We'll set up some variables to // contain the expected results var expectedUrl = '/users'; var expectedParams = { first: 'Expected first name', last: 'Expected last name' }; // We can also set up the user we'll // save based on the expected data var user = { firstname: expectedParams.first, lastname: expectedParams.last } saveUser(user, function () { }); post.restore(); sinon.assert.calledWith(post, expectedUrl, expectedParams); }); }); mocha.run(); </script> </head> </html> Output: Comment More infoAdvertise with us S sharmaanushka Follow Improve Article Tags : Web Technologies Node.js Node.js-Misc Similar Reads JavaScript Tutorial JavaScript is a programming language used to create dynamic content for websites. It is a lightweight, cross-platform, and single-threaded programming language. It's an interpreted language that executes code line by line, providing more flexibility.JavaScript on Client Side: On the client side, Jav 11 min read Web Development Web development is the process of creating, building, and maintaining websites and web applications. It involves everything from web design to programming and database management. Web development is generally divided into three core areas: Frontend Development, Backend Development, and Full Stack De 5 min read React Interview Questions and Answers React is an efficient, flexible, and open-source JavaScript library that allows developers to create simple, fast, and scalable web applications. Jordan Walke, a software engineer who was working for Facebook, created React. Developers with a JavaScript background can easily develop web applications 15+ min read React Tutorial React is a powerful JavaScript library for building fast, scalable front-end applications. Created by Facebook, it's known for its component-based structure, single-page applications (SPAs), and virtual DOM,enabling efficient UI updates and a seamless user experience.Note: The latest stable version 7 min read JavaScript Interview Questions and Answers JavaScript is the most used programming language for developing websites, web servers, mobile applications, and many other platforms. In Both Front-end and Back-end Interviews, JavaScript was asked, and its difficulty depends upon the on your profile and company. Here, we compiled 70+ JS Interview q 15+ min read REST API Introduction REST API stands for REpresentational State Transfer API. It is a type of API (Application Programming Interface) that allows communication between different systems over the internet. REST APIs work by sending requests and receiving responses, typically in JSON format, between the client and server. 7 min read Domain Name System (DNS) DNS is a hierarchical and distributed naming system that translates domain names into IP addresses. When you type a domain name like www.geeksforgeeks.org into your browser, DNS ensures that the request reaches the correct server by resolving the domain to its corresponding IP address.Without DNS, w 8 min read HTML Interview Questions and Answers HTML (HyperText Markup Language) is the foundational language for creating web pages and web applications. Whether you're a fresher or an experienced professional, preparing for an HTML interview requires a solid understanding of both basic and advanced concepts. Below is a curated list of 50+ HTML 14 min read NodeJS Interview Questions and Answers NodeJS is one of the most popular runtime environments, known for its efficiency, scalability, and ability to handle asynchronous operations. It is built on Chromeâs V8 JavaScript engine for executing JavaScript code outside of a browser. It is extensively used by top companies such as LinkedIn, Net 15+ min read Top 10 Projects For Beginners To Practice HTML and CSS Skills Learning to code is an exciting journey, especially when stepping into the world of programming with HTML and CSSâthe foundation of every website you see today. For most beginners, these two building blocks are the perfect starting point to explore the creative side of web development, designing vis 8 min read Like