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

Utilizing AngularJS filter in JavaScript without AngularJS Framework

This is a test to experiment and learn. Currently, I have a JSON object called obj. My goal is to utilize the angular Json filter to format this JSON object and display it in the chrome console. This should be achieved without the need for any button click ...

Saving URLSearchParams to a file using javascript

I am currently implementing jstree and I need to be able to click on a file within the tree structure in order to display a PDF file. Below is the relevant code snippet: $(function () { $('#tree').jstree({ 'core' : { ...

Obtaining the text from an element in Selenium using JavaScript

I've been trying to figure this out, and it seems like it should be a simple task, but how can I extract the text from a table displayed in a browser? When I use the "inspect" tool, the code snippet looks something like this: <tr role="row&qu ...

Utilizing event listeners with image elements in React for interactive typing experience

When I attempt to type the event as React.ChangeEvent<HTMLImageElement> in order to make the e.target.src work, I encounter the following error messages in the imageFound and ImageNotFound functions: Type '(evt: React.ChangeEvent) => void&a ...

Display or conceal a division underneath a dropdown menu based on selections retrieved from a SQL Server database

Presented here is my JavaScript code. function appendItemforPurchaseOrder() { debugger var rowNumber = parseInt($(".itemmapContainer").attr("data-rownumber")); rowNumber = isNaN(rowNumber) ? 1 : rowNumber + 1; var addNewItemDetailHtml = ...

Managing simultaneous asynchronous updates to the local state

There is a scenario where a series of asynchronous calls are made that read from a local state S, perform certain computations based on its current value, and return an updated value of the local state S'. All these operations occur at runtime, with ...

Is it possible for a function within a nodejs module to be defined but display as undefined upon access?

I am currently developing a Discord bot using NodeJS and TypeScript, and I'm facing an issue while trying to import custom modules in a loop with the following code: const eventFiles = fs.readdirSync("./src/events/").filter((file: string) =& ...

Avoid using <input oninput="this.value = this.value.toUpperCase()" /> as it should not convert the text displayed on the "UI", rather it should send the uppercase value

<input oninput="this.value = this.value.toUpperCase()" type="text" id="roleName" name="roleName" class="form-control width200px" [(ngModel)]="role.roleName"> Even though the UI is changing ...

Invoke the function once the database information has been retrieved

I am new to Node.js and I am attempting to execute a function after running a select query using the code below: private displayUserInfo(): any { let connect = this.connect(); connect.connect(function(err: any) { if (err) throw err; ...

TypeScript: implementing function overloading in an interface by extending another interface

I'm currently developing a Capacitor plugin and I'm in the process of defining possible event listeners for it. Previously, all the possible event listeners were included in one large interface within the same file: export interface Plugin { ...

Can you explain the inner workings of the provided code in a step-by-step manner?

I stumbled upon this code snippet that checks if the number of occurrences of an element in an array is greater than a specified value, and if so, it will remove the number: function deleteNth(arr,x) { var cache = {}; return arr.filter(function(n) { ...

How to remove the horizontal scrollbar from material-ui's Drawer element

My drawer is displaying a horizontal scroll, despite my efforts to prevent it. I've tried adjusting the max-width and width settings in Menu and MenuItems, as well as using box-sizing: border-box. I also attempted setting overflow: hidden on the Drawe ...

What is the best way to add selected values from a multi-select dropdown into an array?

Attempting to populate an array from a multiple select dropdown, I've encountered an issue. Despite using splice to set the order of values being pushed into the array, they end up in a different order based on the selection in the dropdown. For insta ...

Switching from a TypeOrm custom repository to Injectable NestJs providers can be a smooth transition with the

After updating TypeORM to version 0.3.12 and @nestjs/typeorm to version 9.0.1, I followed the recommended approach outlined here. I adjusted all my custom repositories accordingly, but simply moving dependencies into the providers metadata of the createTe ...

Creating detailed documentation comments for TypeScript within Visual Studio

When using C# with ReSharper and StyleCop, I am able to automatically generate basic documentation comments for methods. This includes sections such as: /// <summary> /// The login. /// </summary> /// <param name="returnUrl" ...

What is the best way to modify the colors of two specific elements using a combination of CSS and JavaScript

I am currently developing a browser-based game and have encountered an issue. Here is the relevant line of my HTML/PHP code: echo '<div id="div'.$n.'" class="d'.$rand.'" onclick="swapit(this.id, this.className)"></di ...

Angular 2.0 encountered an unexpected value from the module 'AppModule' which appears to be an '[object Object]'

Every time I attempt to load my angular version 2.0 application, I encounter the following error: (index):21 Error: Error: Unexpected value '[object Object]' imported by the module 'AppModule' import { ModuleWithProviders } from ' ...

The Material UI React radio buttons have the ability to modify the value of previous buttons

I'm facing an issue with my Material UI React Stepper Component that contains a group of radio buttons. The problem is that changing the radio button in one step affects the selected value in previous and future steps. I've experimented with diff ...

I encountered a function overload error while creating a component for the API service

As a developer venturing into API design with a backend server that handles client-side calls, I find myself grappling with Typescript, transitioning from a Java background. Encountering the error message "No overload matches this call" has left me seeking ...

"Make your slides smooth and responsive with the unslick option in slick

Currently implementing the Slick Slider on a WordPress website. The slider is designed to display 3 columns at a screen size of 1024px and above. When the screen size drops below 1024px, the slider adjusts to show 2 columns, and on mobile devices, it swit ...