Skip to content

How to create ResponseErrors in TypeScript #17

@seantalbot-jisc

Description

@seantalbot-jisc

Hi, thanks for this excellent library.

I'm trying to mock specific ResponseErrors in TypeScript but I'm getting stuck. The ResponseError constructor takes a huge amount of arguments that I'm unable to workaround without the compiler complaining or it not working.

This is as far as I've got:

import ClientMock from "@elastic/elasticsearch-mock";
import { Client, Connection } from "@elastic/elasticsearch";
import { ResponseError } from "@elastic/elasticsearch/lib/errors";

type RootCause = {
    type: string;
    reason: string;
};

export function addResponseError(
    clientMock: ClientMock,
    method: string,
    path: string,
    statusCode: number,
    rootCauses: RootCause[]
): void {
    const connection = clientMock.getConnection();
    clientMock.add(
        {
            method,
            path,
        },
        () => {
            return new ResponseError({
                body: {
                    errors: {
                        root_cause: rootCauses,
                    },
                    status: statusCode
                },
                statusCode,
                headers: {},
                meta: {
                    name: "foo",
                    context: {},
                    aborted: false,
                    attempts: 0,
                    request: {
                        id: 1,
                        options: {},
                        params: {
                            method,
                            path,
                        },
                    },
                    connection,
                },
                warnings: [],
            });
        }
    );
}

I had previously set connection to {} as Connection but I received no response in my test, so I thought I could use the one from ClientMock.getConnection() instead. However, I get an error:

Type 'typeof Connection' is missing the following properties from type 'Connection': url, ssl, id, headers, and 13 more.ts(2740)
Transport.d.ts(63, 5): The expected type comes from property 'connection' which is declared here on type '{ context: Context; name: string | symbol; request: { params: TransportRequestParams; options: TransportRequestOptions; id: any; }; connection: Connection; attempts: number; aborted: boolean; sniff?: { ...; } | undefined; }'

Any suggestions?

Metadata

Metadata

Assignees

No one assigned

    Labels

    enhancementNew feature or request

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions