The Wayback Machine - https://web.archive.org/web/20240622023306/https://www.geeksforgeeks.org/what-is-a-stub-in-node-js/
Open In App

What is a stub in Node.js ?

Last Updated : 19 Aug, 2020
Improve
Improve
Like Article
Like
Save
Share
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:




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?

  1. Prevent a specific method from being called directly.
  2. Controlling method behavior down a specific path from a test to force the code. For example: Error handling.
  3. Replacing the problematic pieces of code.
  4. Testing asynchronous code easy.

Example To Create Asynchronous Stub That Throws An Exception:




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.




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.




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
</head>
  
<body>
    <div id="mocha"></div>
</body>
  
</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:




<!DOCTYPE html>
<html>
  
<head>
    <title>Page Title</title>
</head>
  
<body>
    <h1>GeeksForGeeks</h1>
    <div id="mocha"></div>
</body>
  
</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:



Similar Reads

Node.js Automatic restart Node.js server with nodemon
We generally type following command for starting NodeJs server: node server.js In this case, if we make any changes to the project then we will have to restart the server by killing it using CTRL+C and then typing the same command again. node server.js It is a very hectic task for the development process. Nodemon is a package for handling this rest
1 min read
Top 3 Best Packages Of Node.js that you should try being a Node.js Developer
Node.js is an open-source and server-side platform built on Google Chrome's JavaScript Engine (V8 Engine). Node.js has its own package manager called NPM( Node Package Manager) which has very useful and incredible libraries and frameworks that makes our life easier as a developer to work with Node.js. The 3 Best Packages of Node.js that you should
4 min read
Javascript Program For Inserting A Node After The N-th Node From The End
Insert a node x after the nth node from the end in the given singly linked list. It is guaranteed that the list contains the nth node from the end. Also 1 &lt;= n. Examples: Input : list: 1-&gt;3-&gt;4-&gt;5 n = 4, x = 2 Output : 1-&gt;2-&gt;3-&gt;4-&gt;5 4th node from the end is 1 and insertion has been done after this node. Input : list: 10-&gt;8
5 min read
Javascript Program For Swapping Kth Node From Beginning With Kth Node From End In A Linked List
Given a singly linked list, swap kth node from beginning with kth node from end. Swapping of data is not allowed, only pointers should be changed. This requirement may be logical in many situations where the linked list data part is huge (For example student details line Name, RollNo, Address, ..etc). The pointers are always fixed (4 bytes for most
5 min read
Node.js Connect Mysql with Node app
Node.js is a powerful platform for building server-side applications, and MySQL is a widely used relational database. Connecting these two can enable developers to build robust, data-driven applications. In this article, we'll explore how to connect a Node.js application with a MySQL database, covering the necessary setup, configuration, and basic
2 min read
How to resolve 'node' is not recognized as an internal or external command error after installing Node.js ?
Encountering the error message ‘node’ is not recognized as an internal or external command after installing Node.js can be frustrating, especially when you’re eager to start working on your project. This error usually means that your system cannot find the Node.js executable because the path to it is not set correctly in your system's environment v
2 min read
How to do pagination Node.js with MySQL ?
Node.js is a runtime environment like Chrome's V8 JavaScript engine. Node.js is an open-source, cross-platform, and backend runtime environment that executes outside a web browser. MySQL is an open-source relational database management system that is fast, reliable, flexible, and robust. Both MySQL and Node.js are trendy choices when building web a
9 min read
How to resolve unhandled exceptions in Node.js ?
There are two approaches to resolve unhandled exceptions in Node.js that are discussed below: Approach 1: Using try-catch block: We know that Node.js is a platform built on JavaScript runtime for easily building fast and scalable network applications. Being part of JavaScript, we know that the most prominent way to handle the exception is we can ha
2 min read
HTTP Cookies in Node.js
Cookies are small data that are stored on a client side and sent to the client along with server requests. Cookies have various functionality, they can be used for maintaining sessions and adding user-specific features in your web app. For this, we will use cookie-parser module of npm which provides middleware for parsing of cookies. First set your
4 min read
Node.js String Decoder Complete Reference
The string Decoder module provides an API for decoding Buffer objects into strings. Example: C/C++ Code // Node.js program to demonstrate the // stringDecoder.write() Method // Import the string_decoder module // and get the StringDecoder class // using object destructuring const { StringDecoder } = require(&quot;string_decoder&quot;); // Create a
1 min read