Unable to retrieve multiple values from a sinon stub

I am trying to stub a method using sinon in my Typescript code with Bluebird promises. However, I'm running into an issue where only the first value I set for the stub is being returned, even though I want it to return a different value on the second call.

import sinon = require('sinon')
import * as MyService from "../main/Service"
import * as Promise from "bluebird"

it("test things", function(done) {
  let serviceStub = sinon.stub(MyService, 'method')

  serviceStub.onFirstCall().returns(Promise.reject("rejected"))
    .onSecondCall().returns(Promise.resolve("resolved"))

  MyService.method().then(function(value) {
    console.log("success 1: "+value.value())
  }, function(error) {
    console.log("error 1: "+error)
  })

  MyService.method().then(function(value) {
    console.log("success 2: "+value.value())
  }, function(error) {
    console.log("error 2: "+error)
  })

  done()
})

I must be doing something wrong with the stubbing since the onSecondCall() method doesn't seem to work as expected. Instead of returning Promise.resolve("resolved"), both calls are returning the first value I specified (Promise.reject("rejected")).

 error 1: rejected
error 2: rejected

If the stub worked correctly, it should have output:

error 1: rejected
success 2: resolved

Can anyone help me figure out what's going awry with my stubbing implementation?

Just as a note for those unfamiliar with Bluebird promises, in the method

then(function(value){}, function(error){})
, the first function handles resolved promises and the second function handles rejected promises.

Answer №1

It seems like your usage is correct, but the dependencies might be causing issues based on the following test:

I tested your example in JavaScript (since it only had import statements from ES6/TypeScript) and made some minor adjustments to make it work as expected.

You could try removing components one by one from the working code until you find the culprit that is not functioning correctly.

In the code below, I am using native Promises from Node version 6.6, with 'value.value()' replaced by just 'value' because a string does not have a method called 'value':

let sinon = require('sinon')

let MyService = { method() {}}

let serviceStub = sinon.stub(MyService, 'method')

serviceStub.onFirstCall().returns(Promise.reject("rejected"))
    .onSecondCall().returns(Promise.resolve("resolved"))

MyService.method().then(function (value) {
    console.log("success 1: " + value)
}, function (error) {
    console.log("error 1: " + error)
})

MyService.method().then(function (value) {
    console.log("success 2: " + value)
}, function (error) {
    console.log("error 2: " + error)
})

The output should be:

>node sinon.js                              
error 1: rejected                                                           
success 2: resolved  

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

Is it possible for two components to send two distinct props to a single component in a React application?

I recently encountered a scenario where I needed to pass a variable value to a Component that already has props for a different purpose. The challenge here is, can two separate components send different props to the same component? Alternatively, is it po ...

Obtain the location of the image source from a text file within an HTML document

I need to create a slideshow displaying a sequence of images. The path to these images will be stored in a text file. How can I read the image paths from the text file? Currently, I have hardcoded code like the example below: <div class="mySlides fade" ...

Issue with ion-select default value not being applied

In my ion-select element, I have multiple options and I want to set a default value based on the CurrentNumber when the view is loaded. Here's the code snippet: <ion-select formControlName="Level"> <ion-option [value]="level.id" *n ...

Access denial encountered when attempting to submit upload in IE8 using JavaScript

When running the submit function on IE8, I am receiving an "access is denied" error (it works fine on Chrome and Firefox for IE versions above 8): var iframe = this._createIframe(id); var form = this._createForm(iframe, params); ... ... ...

Tips for showcasing an item with the chosen value in a dropdown menu

Below is the object I created: export default { data() { return { language: { "en": { welcomeMsg: "Welcome to New York City" }, "de": { ...

The chai expect statement is causing an assertion error that I am currently encountering

Exploring the combination of different data types using a simple addition function. For instance, when adding 1 + 1, we expect to get 2, and when adding 1 + "one", the result should be "1one". Below is the content of my functions.js file: module.exports = ...

How can I determine when a WebSocket connection is closed after a user exits the browser?

Incorporating HTML5 websocket and nodejs in my project has allowed me to develop a basic chat function. Thus far, everything is functioning as expected. However, I am faced with the challenge of determining how to identify if connected users have lost th ...

Make sure to include all enum type values within the function's body to ensure comprehensive coverage

I am defining an enumeration called ApiFunctions with values like "HIDE", "SET_READ_ONLY", and "DESCRIPTION". Also, I have a type ValueOfApiFunction that should include all values of ApiFunctions. Additionally, I have a logic that listens for messages on ...

"Benefit from precise TypeScript error messages for maintaining a streamlined and organized architecture in your

As I dip my toes into the world of functional programming with typescript for a new project, I am encountering some challenges. In the provided code snippet, which follows a clean architecture model, TypeScript errors are popping up, but pinpointing their ...

What is the best way to assign a unique color to each circle?

Struggling to assign random colors to each circle in my canvas. Currently, they all have the same color that changes upon refresh. I'm aiming for unique colors on each circle but my attempts have been unsuccessful so far. Check out my code below: v ...

What is the process of creating a MaterialUI checkbox named "Badge"?

Badge API at https://material-ui.com/api/badge/ includes a prop called component that accepts either a string for a DOM element or a component. In my code: <Badge color="primary" classes={{ badge: classes.badge }} component="checkbox"> <Avatar ...

Javascript favorite star toggling

An excellent illustration is the star icon located on the left side of this post. You have the ability to click on it to save this message as a favorite and click again to remove the flag. I have already set up a page /favorites/add/{post_id}/, but I am ...

The pagination component in React with Material-ui functions properly on a local environment, but encounters issues when deployed

Looking for some assistance with a persistent issue I've run into. Can anyone lend a hand? [x] The problem persists in the latest release. [x] After checking the repository's issues, I'm confident this is not a duplicate. Current Behavior ...

Creating a new row with a dropdown list upon clicking a button

I want to include a Textbox and dropdown list in a new row every time I click a button. However, I seem to be having trouble with this process. Can someone assist me in solving this issue? Thank you in advance. HTML <table> <tr> ...

Issue when Updating Component State: React child cannot be an object

I'm currently in the process of familiarizing myself with React and how to manage component state. My goal is to build a component, set up the initial state using a constructor, make a GET request to the server to fetch an array of objects, and then ...

When the user saves the changes on the pop-up window, the main window will automatically refresh

I currently have a calendar feature that allows users to create, edit, and delete appointments. When a user clicks on the new appointment button, it opens a window above the calendar interface. Once the user fills out the necessary fields and clicks save, ...

"Simply tap on an element that has been dynamically inserted into the

Many individuals are familiar with how to attach a "click" event to an element that is dynamically added using the following syntax: $('#main').on('click','.link',function(){ //some code here }); In this example, .link repr ...

Is there a way to determine the remaining time or percentage until document.ready is reached?

My usual approach is to display a loading animation like this: $('#load').show(); $(document).ready(function(){ $('#load').hide(); }); where the <div id="load"> contains just an animated gif. However, I've been conside ...

Create a Typescript generic function that can return a variety of data types including strings, numbers, and

I have a function written in Typescript and I am looking to determine the return type based on the value retrieved from process.env. For instance, the variables in my Node process.env can be strings, numbers, or booleans. I want to fetch them with their s ...

Enhanced JavaScript Regex for date and time matching with specific keywords, focusing on identifying days with missing first digit

I have a specific regular expression that I am using: https://regex101.com/r/fBq3Es/1 (audiência|sessão virtual)(?:.(?!audiência|sessão virtual|até))*([1-2][0-9]|3[0-1]|0?[1-9])\s*de\s*([^\s]+)\s*de\s*((19|20)?\d\d) ...