How to mock nested functions within sinon

There are several questions similar to this one, but none of them quite match the scenario I'm dealing with.

The situation involves a function that takes another function as a parameter:

var myfunc = (func_outer) => {
    return func_outer().func_inner();
}

In my unit tests, I want to create a stub for a function called myfunc2. Essentially, I need to stub a nested stub. Currently, I manually create the stub like this, but I'd prefer to use sinon stubs if there's a better way:

const func_outer = () => {
    return {
       func_inner: () => {return mockResponse;}
    }
};

Has anyone else encountered this particular situation before? Is there a simple solution to address this issue?

Answer №1

For detailed information on how to make stubs return values, refer to the Sinon documentation.

Using stub.returns(obj); will ensure that the stub returns the specified value.

To implement this, follow these steps:

Start by stubbing your inner function and setting it to return a mock response:

func_innerStub = sinon.stub().returns('mockResponse')

Next, create a stub for your outer function and have it return an object containing the previously stubbed inner function:

func_outerStub = sinon.stub().returns({func_inner: func_innerStub})

You can apply this same method to the myfunc function as well, passing the func_outerStub as a parameter.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Utilizing destructuring and Object.entries for advanced formatting

I'm embarking on a new React project and facing an issue with the JSON data structure returned by my API for meetings. I attempted to utilize destructuring and Object.entries. This is what I currently have: { "meetings": [ ...

Executing Actions Prior to Redirecting

I am working on implementing a timer process using a custom JQuery plugin that will redirect to the login page after a specific number of minutes. Additionally, when the timer reaches zero, I need to execute a task, which in this case involves making a cal ...

Get rid of the horizontal scroll bar and expand the width of the table

Normally, Tabulator limits the maximum width of the table and adds a horizontal scroll bar at the bottom. Is there a way to eliminate this scroll bar and make Tabulator expand the width of the table instead (resulting in the horizontal scrollbar appearin ...

Using Vue.js: Execute a function with a delay, but start the delay over if there is any user input

Imagine a scenario where I have a form that is connected to an API and displays information based on user input. Whenever the user makes changes, such as adjusting the number of results per page, the component should react dynamically by loading new data. ...

Is there a way for me to manipulate the RGB values of the canvas in such a manner that the Red and Green components of the gradient are determined by dividing the position of my mouse cursor

My homework assignment requires using RGB colors where the red value is set to 0, green is the x-coordinate divided by 2, and blue is the y-coordinate divided by 2. I've been trying to control the colors on a canvas using addColorStop functions, but I ...

Utilizing ng-repeat to display a collection of Angular Highcharts charts

As I work on developing a KPI app using Angular JS, my goal is to establish a collection of charts. Each item in the list will display distinct values and feature a different chart type based on my Model. I am relying on the highcharts-ng directive for th ...

Looking for a way to automatically update your JavaScript code on your Minecraft (Bukkit)

One of my clients has requested a website design that includes a player display for each server, updating every five seconds. I'm not sure where to start with this task. Below is an example for reference. Any guidance on how to achieve this would be g ...

What is the process for triggering an unordered list when I click on a table data cell within the Hospitals category?

Hi there! I need help with writing a JavaScript function for Hospitals in the code below. When I click on Hospitals, I want to display the values in the unordered list. Expected output: Hospitals--->onclick Bangalore| salem |Goa| Mangalore| Visakhapatnam ...

When comparing strings, if they match, replace them with bold text

Today, I faced a challenging brain teaser that kept me occupied for over an hour. The task at hand is to compare two strings: the text input from the field and data-row-internalnumber. The goal is to determine if they match and then bold only the last let ...

"Triggering CSS changes with the click of a

I am developing a basic calendar application in PHP and I would like to dynamically change the style of the <td> block based on user interactions. Specifically, I want to implement a behavior where once the "menuclick" class is active, the other cl ...

Executing a function from index.html that continuously loops without any limits

I'm currently working on creating a function that displays specific HTML content only to users with certain roles. Here are the functions I've set up for this: nodejs/server.js app.get('/api/isadmin', ensureAuthenticated, function (re ...

Update the data in Firebase, but revert it back to the original state after a few seconds with the use of "angularFire."

I'm currently working on updating data in the Firebase Realtime Database using Angular and AngularFire. The issue I'm facing is that even though the data changes successfully, it reverts back to the original data after a few seconds. Below is the ...

Struggles with handling asynchronous events in Angular

I'm currently working on a piece of code that iterates through an array containing 10 items. For each item, a request is made and the returned data is stored in another array. The entire process goes smoothly until reaching the line that contains $q.a ...

Retrieve binary data of an image from an API and render it on an HTML page

I have been working on storing images in a MongoDB database and trying to display the response I receive from an Express API as an image on the client side. The image source URL looks like this: src="/image/data/5a44dde172aa021d107e7d33" When I try to wr ...

Issue with Vue 2: Promise does not resolve after redirecting to another page

Although I realize this question might seem like a repetition, I have been tirelessly seeking a solution without success. The issue I am facing involves a method that resolves a promise only after the window has fully loaded. Subsequently, in my mounted h ...

What are the steps to create custom Typescript RecursiveOmit and RecursivePick declarations for efficient cloning routines?

For some time now, I have been attempting to create a declaration for RecursiveOmit and RecursivePick in cloning methods such as JSON.parse(JSON.stringify(obj, ['myProperty'])) type RecursiveKey<T> = T extends object ? keyof T | RecursiveKe ...

Passing parameters to JavaScript onload event from PHP

Looking for help with integrating date data from PHP into a JavaScript countdown function. I have extracted the date from a database using PHP, but struggling to pass it correctly to the JavaScript function. My attempt so far: <body onload="countIt(< ...

Modifying button appearance upon clicking using JavaScript

JavaScript: const buttons = document.getElementsByClassName("togglebtn"); for (let i = 0; i < buttons.length; i++) { buttons[i].onclick = function () { this.classList.toggle("active"); } } html: <md-butt ...

`I'm having issues trying to use ajax and load simultaneously``

Can anyone help me figure out why my AJAX call to sessions.php is not correctly loading and returning true or false each time a user accesses the page? var section = $("#header a"); section.on('click', function() { $.ajax({ type: "PO ...

Leverage Jasmine for testing a jQuery plugin

I'm currently utilizing the angular-minicolors library () within an angular controller: angular.element("myelement").minicolors({ position: 'top left', change: function() { //custom code to run upon color change } }) Wh ...