I am using OpenSearch client and I would like to test the indices.exists
, however when I run jest test, I get the error openSearchClient.indices.exists is not a function
. How can I access the exists
property using jest?
I understand the below code is trying to access mockOpenSearchClient.indices().exists()
but I've looked at the documentation but can't seem to figure out how to make it mock mockOpenSearchClient.indices.exists()
,
below is my mock setup
const mockOpenSearchClient = {
indices: jest.fn().mockImplementation(() => {
return {
exists: jest.fn((obj, cb) => {
return cb("", existsResp);
}),
};
}),
} as unknown as Client;
After following the jest documentation and example here I was able to modify my setup to the below code but still no success,
const mockOpenSearchClient = {
indices: jest.fn().mockImplementation(() => {
return {
exists: jest.fn().mockImplementation(() => {
return {
statusCode: 200,
body: true,
};
}),
};
}),
} as unknown as Client;
If I log mockOpenSearchClient this is what I get back
openSearchClient {
indices: [Function: mockConstructor] {
_isMockFunction: true,
getMockImplementation: [Function (anonymous)],
mock: [Getter/Setter],
mockClear: [Function (anonymous)],
mockReset: [Function (anonymous)],
mockRestore: [Function (anonymous)],
mockReturnValueOnce: [Function (anonymous)],
mockResolvedValueOnce: [Function (anonymous)],
mockRejectedValueOnce: [Function (anonymous)],
mockReturnValue: [Function (anonymous)],
mockResolvedValue: [Function (anonymous)],
mockRejectedValue: [Function (anonymous)],
mockImplementationOnce: [Function (anonymous)],
withImplementation: [Function: bound withImplementation],
mockImplementation: [Function (anonymous)],
mockReturnThis: [Function (anonymous)],
mockName: [Function (anonymous)],
getMockName: [Function (anonymous)]
}
}
How do I successfully access the mockOpenSearchClient.indices.exists
method?
So I was finally able to mock it by simply constructing an object and then mocking the resolved value to the function:
const mockOpenSearchClient = {
indices: {
exists: jest.fn().mockResolvedValue(existsResp);
get: jest.fn().mockResolvedValue(getResp);
}
} as unknown as Client;