首页 > 解决方案 > Getting error testing readstream response with Jest

问题描述

I am getting timeout error while testing a function that returns readStream from google cloud store.

// Test case
import { createResponse } from 'node-mocks-http';
it('getImage from google cloud storage', async done => {
    let res: Response = createResponse();
    let data = await controller.getImage({ image: "text data"},object, response);
});

// Function that calls google gloud storage and return object.
public async getImage(imageReqDto, baseDto, response){
    let bucket = this.storage.bucket(process.env.IMAGE_BUCKET);
    let file = bucket.file(image);
    return file.createReadStream().pipe(response);;
}

Any solution how to pass the test case successfully after receiving the buffer data.

标签: node.jsjestjsmocha.jsnestjschai

解决方案


这取决于您要测试的内容。如果您只是想确保返回 ReadStream,请尝试使用.toBeInstanceOf()

it('readstream is returned, when .getImage() is invoked with image data', async () => {
    const response: Response = createResponse();

    const stream = await controller.getImage({image: "text data"}, object, response);

    expect(stream).toBeInstanceOf(ReadStream)
});

然而,更好的测试是了解预期响应并断言 ReadStream 与预期值匹配。如果它是一个小图像,您可以将其加载到缓冲区中并进行比较。如果图像很大,您可以考虑将其存储为 base64 并将实际与预期进行比较。


推荐阅读