Sinon made it difficult to successfully stub/mock a method return

I find myself facing a challenge as I navigate the learning path to nodejs and explore advanced javascript features. Progress is slow but steady. One of the rest endpoints utilizes the (azure blob storage) method from containerclient, which requires converting the results into a different format. When it comes to writing tests using sinon, there is a need to stub/mock/fake this method along with its return values. As I iterate through the Blobitem objects in my rest endpoint.

listBlobsByHierarchy(string, ContainerListBlobsOptions)

This method yields

PagedAsyncIterableIterator<({ kind: "prefix"; } & BlobPrefix) | ({ kind: "blob"; } & BlobItem), ContainerListBlobHierarchySegmentResponse>

The question arises - how should I proceed with this task? If I mock this method and alter its return value, what steps should I take next?

To learn more, check out the following reference link: ContainerClient.listBlobsByHierarchy

Answer №1

Originally, I opted for the any type to work around the problem. Given that my code necessitates an iterable object, I implemented it in this manner... A great way to familiarize oneself with the any type

const obj: any = [ {...} ];
containerStub.listBlobsByHierarchy.returns(obj);
const actualResponse = await (await client.get('ENDPOINT')).body;
const expectedobj: any = [ {...} ]; // whatever the method will return
expect(actualResponse).deepEqual(expectedobj);

The code above reflects the concept. There is also a different approach believed to be more favorable - converting it to unknown and then transitioning it to the actual type. Apparently, utilizing the any type is less preferable than converting it to unknown.

const obj = [ {...} ] as unknown as PagedAsyncIterableIterator< 
                ({ kind: 'prefix' } & BlobPrefix) | ({ kind: 'blob' } & BlobItem), 
                ContainerListBlobHierarchySegmentResponse 
            >;
containerStub.listBlobsByHierarchy.returns(obj);

Transitioning from the realm of traditional Java into typescript / JavaScript poses a challenge for a beginner like me.

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

Tips for modifying an axios instance during response interception

Is there a way to automatically update an axios instance with the latest token received in a response, without making a second request? The new token can be included in any response after any request, and I want to make sure that the last received token ...

What is the process of transforming an array of string variables into TypeScript types?

I am inquiring about the process of converting an array of string variables to TypeScript types. It is worth noting that there are two existing SO answers addressing this issue, but they involve passing strings hardcoded to maintain their original values. ...

Generate a blueprint for a TypeScript interface

In my coding project, I've been noticing a pattern of redundancy when it comes to creating TypeScript interfaces as the code base expands. For example: interface IErrorResponse { code: number message: string } // Feature 1 type FEATURE_1_KEYS = ...

ADAL-Node: Unable to locate tenant groups

When the authority URL is similar to (where the domain name belongs to your tenant), an error occurs: The Get Token request returned an HTTP error: 400 with the server response stating "error description AADSTS90002 Tenant 'organizations' not ...

Filtering data in Angular from an HTML source

Looking to filter a simple list I have. For example: <div *ngFor="let x of data"></div> Example data: data = [ { "img" : "assets/img/photos/05.jpg", "title" : "Denim Jeans", "overview": "today" ...

exclude a few countries from ngx-intl-tel-input

I'm facing an issue where I need to remove certain countries, like Mexico, from the list displayed in ngx-intl-tel-input. Even after trying the 'excludeCountries' option, it doesn't seem to be working for me. Below is a snippet of my ...

Error 415 Unsupported Media Type when uploading files using Angular 12 with TypeScript

I'm currently working on a project using Angular 12 and Spring Boot for image uploads. I have successfully tested the API with Postman and it's working correctly on the backend. However, when I try to test the front end, I encounter the following ...

Tips for converting a string array constant into a union type

I have a string array that I want to use to create a new type where the properties correspond to the elements in the array. There are different types of arrays and I have a function that generates different output types based on the input array. const RG ...

What steps can I take to resolve the "Unable to call a potentially 'undefined' object" error?

I'm currently working with CreateContext in Typescript and I have encountered a problem in the code that I can't seem to resolve. I am trying to use typesafe TX to provide state and dispatch (via useReducer) in a component hierarchy. Here is the ...

Tips on preventing the duplication of component instances in your project

Check out the plunker link to see that the child component "Loader" is being loaded multiple times every time the button is clicked. How can I prevent creating multiple instances of the same component? I want the new instance to replace the existing one wh ...

Angular data binding with an object instead of an array list

Currently, I am implementing Angular and attempting to iterate through an object. Data in JSON format employee {"fName":"mike","email":"<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="ebb3b3b3b3b3b3b3b3ab83849f868a8287c588848 ...

Utilizing *ngIf for Showing Elements Once Data is Completely Loaded

While working on my Angular 2 app, I encountered an issue with the pagination UI loading before the data arrives. This causes a visual glitch where the pagination components initially appear at the top of the page and then shift to the bottom once the data ...

How can I determine the existence of an S3 bucket and, if it doesn't exist, create it using TypeScript CDK?

I am currently facing an issue where I need to verify the existence of a bucket in the account and either create a new one if it doesn't exist or use the existing bucket My attempt at achieving this is as follows: import {Bucket} from 'aws-cdk-l ...

Response received through GET call in text format

Implementing a typed response in a simple GET request seems to be causing a strange behavior in the compiler. The application compiles successfully, but a red error is returned with the message displayed in the VS Code screenshot below: ERROR in src/app/s ...

The comprehensive guide to using ambient enum types in an exhaustive switch statement

Here is a function that maps a place to an emoji: function mapPlaceToEmoji(place: Place): string { switch (place) { case Place.FIRST: return ' ...

Is it considered an anti-pattern for certain components within a tile system to share a viewmodel when the parent web component has multiple child components?

Creating an Angular application involves a parent component that contains child components. I am looking for a way to share functionality among the components without resorting to creating services for each one. One approach would be to build services and ...

Have there been any instances of combining AngularJS, ASP.NET-WebApi, OData, Breeze.js, and Typescript?

I am attempting to combine different technologies, but I am facing challenges as the entity framework meta-datas are not being consumed properly by breeze.js. Despite setting up all configurations, it's proving to be a bit tricky since there are no ex ...

The HttpClient.get('/') request with {observe: 'response'} is failing to retrieve some headers

Currently, I'm in the process of writing an API GET request by utilizing HttpClient.get(). Upon passing in the option to observe the response, I've encountered an issue where accessing the .keys() does not provide me with any headers apart from C ...

Utilize the useState hook to update state when changes occur in the

I currently have a functional component that utilizes a useState hook. The values it holds are sourced from my redux store, and I aim to update the state with the new store state every time an action is dispatched. At the moment, I've manually set an ...

By utilizing a function provided within the context, React state will consistently have its original value

After passing functions from one component to its parent and then through context, updating the state works fine. However, there is an issue with accessing the data inside these functions. They continue to show as the initial data rather than the updated v ...