aws-sdk-mock icon indicating copy to clipboard operation
aws-sdk-mock copied to clipboard

Mocking ApiGatewayManagementApi not working

Open kstro21 opened this issue 4 years ago • 3 comments

Here is a reduced example of what I'm trying to do.

I have a class with a function that looks like this:

// at the top of the file
const ApiGatewayManagementApi = require('aws-sdk/clients/apigatewaymanagementapi');

// function definition
async sendSummary(summary, { endpoint, connectionId }) {
    const apiGwManagementApi = new ApiGatewayManagementApi({ endpoint });

    return apiGwManagementApi
      .postToConnection({
        ConnectionId: connectionId,
        Data: JSON.stringify(summary),
      })
      .promise()
      .catch((err) => {
        console.error('Error while sending', err);
        throw err;
      });
  }

That works as expected. Now comes the part of the test

const AWS = require('aws-sdk-mock');

it('send summary', async () => {
    AWS.mock('ApiGatewayManagementApi', 'postToConnection', function (
      params,
      callback
    ) {
      expect(params).toEqual(
      jasmine.objectContaining({
         ConnectionId: connectionId,
        Data: JSON.stringify(summary),
      })
    );
      callback(null, {});
    });

    const { service } = require('../my-service');

    await expectAsync(
      service.sendSummary(summaryMock, connectionMock)
    ).toBeResolved();

    AWS.restore('ApiGatewayManagementApi');
  });

But when running the tests it throws the error

UnknownEndpoint: Inaccessible host: `some.execute-api.us-east-1.amazonaws.com'

Seems like the mock is not working. Any help is appreciated.

kstro21 avatar Oct 02 '20 19:10 kstro21

from READ.me

"Also note that if you initialise an AWS service inside a callback from an async function inside the handler function, that won't work either."

sukruavcuoglu avatar Apr 20 '21 17:04 sukruavcuoglu

So, @sukruavcuoglu, it is not possible?

kstro21 avatar Apr 23 '21 20:04 kstro21

The solution is to replace this const ApiGatewayManagementApi = require('aws-sdk/clients/apigatewaymanagementapi'); and this const apiGwManagementApi = new ApiGatewayManagementApi({ endpoint });

with this const AWS = require('aws-sdk'); and this const apiGwManagementApi = new AWS.ApiGatewayManagementApi(({ endpoint });

nmq64 avatar Feb 09 '23 10:02 nmq64