0

I need to mock the following opensearch response using jest. I've tried several methods but couldn't find a working method.

export default class OpenSearchHandler {
  static async executeOSRequest(
    apiPath: string,
    httpMethod: OSHttpMethods,
    requestBody?: string,
    destroyAtResponse = true
  ): Promise<string> {
    const response = await this.getOSResponse(
      apiPath,
      httpMethod,
      requestBody,
      destroyAtResponse
    );

    let body: string;
    try {
      body = await new Promise((resolve, reject) => {
        const incomingMessage = response.body as IncomingMessage;
        body = '';
        incomingMessage.on('data', (chunk) => {
          body += chunk;
        });
        incomingMessage.on('end', () => {
          resolve(body);
        });
        incomingMessage.on('error', (err) => {
          reject(err);
        });
      });
    } catch (err) {
      body = JSON.stringify({
        error: {
          type: 'failed_to_read_data',
          reason: err,
        },
        status: 400,
      });
    }
    console.log('body...', body);
    return body;
  }

I am trying to test the executeOSRequest method. for that I need to mock the getOSResponse method. I ve tried to mock that using jest.spyOn, but the response of getOSResponse is too large. Is there any other way to mock getOSResponse method using jest?

0 Answers0