Can you explain the functionality of sinon's stub.yields method?

The explanation given in the documentation for sinon regarding stub.yields is as follows:

By using stub.yields([arg1, arg2, ...]), you are essentially performing a function similar to callsArg.

This will result in the stub executing the first callback it receives with the specified arguments (if any).

In scenarios where a method has multiple callbacks, yieldsRight must be used to call the last callback or callsArg should be utilized to have the stub trigger callbacks other than the first or last one.

After reading this particular section multiple times, it still remains unclear and especially confusing when trying to comprehend the emphasized part.

To aid my understanding, I require a more detailed explanation along with a couple of examples demonstrating the usage of yields (which the official documentation fails to provide).

Answer №1

When you are stubbing a function that requires a callback, such as an asynchronous database request, it allows the stub to mimic the results that the function would typically provide to your callback.

Let's make this easier to understand with an example:

// simulated db api
let db = {
  get(query, cb) {
    cb(null, "your results from the query")
  }
}

function runQuery(q) {
  db.get(q, (err, val) => {
    if (err) console.log("error!", err)
    else console.log("value:", val)
  })
}
// call it normally
runQuery("some query")

// stub the DB get method
let stub = sinon.stub(db, 'get');

// fake query results
stub.yields(null, "results from Sinon Stub")

// now stubbed
runQuery("some query")
// assert that `runQuery` did what it should
// given a value of `results from Sinon Stub`
// from db.get

// see how it handles an error:
stub.yields("Some error")

runQuery("some query")
// assert that `runQuery` did what it should
// when db errors with "Some error"
<script src="https://cdnjs.cloudflare.com/ajax/libs/sinon.js/7.3.2/sinon.min.js"></script>

This technique is useful for testing an asynchronous function that uses callbacks and verifying different outcomes. For instance, if you were working with a database function that required a callback like this:

db.get("someVal", (err, val) => {/* do something */}

You could simulate various responses from the database by yielding different values and then perform assertions against your code.

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

Express.js post method malfunctioning for BMI calculation

Currently, I am working on a BMI calculator application in JavaScript as part of my practice. The app is supposed to take two inputs - weight and height, calculate the BMI, and display the result on the web page. However, after inputting the data and submi ...

Is it possible to create a THREE.js form using a sequence of outlines?

Consider the scenario where three two-dimensional shapes are present. To keep things simple, let's envision them all as circles: Is there a method in THREE.js that allows for these shapes to be 'stacked' on top of each other vertically, res ...

Utilizing auto-generated Nonce for Content Security Policy in a Node.js/Express web application

I've exhausted all possible solutions in my attempt to create a nonce and pass it successfully to the CSP and inline scripts with the nonce variable. Despite reading numerous articles, the guidance on accomplishing this task remains vague. Fortunately ...

Methods for presenting text from an object array using Angular

I'm running into a bit of trouble with getting my text to show up properly in my code. In the HTML, I have <td>{{cabinetDetails.cabinetType}}</td> and my data source is set as $scope.cabinetDetails = [{cabinetType: 'panel'}]; De ...

unable to retrieve the value of the table row with a particular class designation

I'm currently working with a table code and I need to retrieve the value of the table row with the class "highlight". However, when trying to do so with the code below, I'm getting a null result. Can someone please assist me? Table name: itemtab ...

How can I combine multiple textures from mtlLoader and objLoader in three.js?

I have the files .mtl, .obj, and several .jpg textures. I have been attempting to use different textures in the export loader OBJ, and while I can see my object on the scene, it appears as a black color. Can anyone spot what might be incorrect or missing ...

What is the best way to calculate the total sum of a column in Vue JS?

To manually add a row, each row is stored in the "items" array items: [ { occuGroup:'', constType:'', bfloorArea: 0, cfloorArea: 0 }, ], Below is the code I wrote to calculate the total: subTotal: function() { var ...

Why is it that useEffect is functioning correctly only on the first occasion?

Recently, I've been facing significant challenges with React's useEffect and States. The issue arises when I redirect to the main page of my app and then attempt to use them again. In the following component, everything seems to function correct ...

Testing the Mongoose save() method by mocking it in an integration test

I am currently facing an issue while trying to create a test scenario. The problem arises with the endpoint I have for a REST-API: Post represents a Mongoose model. router.post('/addPost', (req, res) => { const post = new Post(req.body); ...

Exploring the Depths of Javascript Variable Scope

bar: function () { var cValue = false; car(4, function () { cValue = true; if (cValue) alert("cvalue is true 1"); }); if (cValue) alert("cvalue is true 2"); } car: function (val, fn) { fn(); } I have encountered a similar is ...

Step-by-step guide on how to include the "content-based-recommender" package in a Reactjs project

I recently started learning React.js and I'm interested in using the "Content-Based Recommender" package from npm. However, after downloading it, I encountered an issue with importing it. The documentation suggests the following: const ContentBasedRec ...

What is the best way to test a JavaScript function that includes nested timeouts using Jasmine?

I have a function that clears an input on blur. It's designed for use with Angular Materials, and I've created a directive for when this functionality is needed. function clearTextOnBlurLink(scope, element, attrs, controller) { $timeout(f ...

Perform a series of tasks concurrently within a function using Grunt

I am currently utilizing grunt-shell along with other custom tasks in my project. In one of my tasks, I need to execute these tasks sequentially and verify the output of each task. Here is a simplified representation: grunt.task.registerTask('test&ap ...

refreshing the webpage with information from an API request

I am completely new to web development, so please bear with me. I am attempting to make a simple API call: const getWorldTotal = async () => { const response = await fetch('https://cors-anywhere.herokuapp.com/https://health-api.com/api/v1/cov ...

Is it possible to trigger a reflow prior to initiating a lengthy JavaScript operation?

Ready to face the criticism, I understand that this question has been asked many times before, and I am aware that there are likely more efficient ways to achieve what I'm trying to do... In a JavaScript function, I have a process that can take up to ...

Avoiding redundant EventEmitters when transferring @Output to a child component

While working on a form component, I decided to separate the form action buttons into a child component. This led me to create two EventEmitter and handlers for the same action. I'm wondering if there is a way to directly pass the 'onDiscard&apo ...

An undefined value error occurred while attempting to save data to a MongoDB collection through a node/express server

Anticipated Outcome I am looking to successfully save a new page to mongo db after server validation of input, without encountering any errors in the console. The issue seems to be originating from the post method in the routes in admin_pages.js and I&apos ...

"Experience the power of MVC single page CRUD operations paired with dynamic grid functionality

Currently attempting to create a single page application CRUD functionality using UI Grid, however encountering an error during post request. ...

Javascript Snake: I am having trouble making my snake's tail grow longer

I've created a snake game that is almost fully functional. The issue I'm facing is that when the snake eats food, the food changes location but the tail of the snake doesn't grow in size. I suspect that my understanding of arrays might be la ...

A step-by-step guide on incorporating box-shadow for the jackColor in the Switchery Plugin

I am looking to add a box shadow to my iOS7 style switches for checkboxes when they are checked. Here is the code I have so far: var elems = Array.prototype.slice.call(document.querySelectorAll('.js-switch')); elems.forEach(function (html) { va ...