Search code examples
typescriptazure-blob-storagesinon

In Sinon, could not succeed stub/mock a method return


I have been struggling. I do not have a proper learning path to nodejs or the advanced javascript features. I am still working toward this. One of the rest endpoints use this (azure blob storage) method (of containerclient) and convert the results to another form. When writing testing using sinon, there is a point, I must stub/mock/fake this method and its return values. In my rest endpoint, I am iterating through and getting the Blobitem objects.

listBlobsByHierarchy(string, ContainerListBlobsOptions)

this method returns

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

How would I go about this? If I mock this method, and so its return, then how would I do.

This is the reference link ContainerClient.listBlobsByHierarchy


Solution

  • At first, I used the type any to bypass the issue. Since my code expects an iterable object, I have it this way... Good way to learn about type any

    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);
    

    Above code kind of shows the idea. There is another "supposedly preferred" way - to cast it to unknown and then cast it to the real type. Looks like the usage of any type is worse than casting it to unknown

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

    Being a novice in this kind of type script / java script, coming from regular Java world, it is challenging.