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

An easy way to test params sent to command

Open DominicGBauer opened this issue 3 years ago • 2 comments

Hi

First thanks so much for creating this :)!

Second, I was wondering if a function could be made to easily retrieve the params sent to the command

e.g.

    EndpointArn: endpointArn ?? '',
    Attributes: {
      Enabled: 'true',
      Token: token,
      CustomUserData: JSON.stringify(userData),
    },
  }
  const updatePlatformEndpoint = snsClient.send(
    new SetEndpointAttributesCommand(params),
  )

Then you could have the mock do something like:

params = snsMock.on(SetEndpointAttributesCommand).params()

So it's easy to test the params being sent through?

DominicGBauer avatar Jan 13 '22 07:01 DominicGBauer

I was looking for this as well. It would definitely be nice to have something like this built in. I hacked around at it a bit and came up with this:

// you will already have this transitive dependency, which is used by all of the v3 sdk client types
import { Command } from '@aws-sdk/smithy-client';
import { AwsStub } from 'aws-sdk-client-mock';

// returns an array of the inputs for commands of type T that were sent to the mock client
export const getCommandInputs = <T extends Command<any, any, any>>(
  mock: AwsStub<any, any>,
  commandClass: { new (...args: any[]): T },
) => {
  return mock
    .calls()
    .filter((call) => call.args[0] instanceof commandClass)
    .map((call) => call.args[0].input as T['input']);
};

A simple example of usage:

it('gets the url', async () => {
  const mockSqs = mockClient(SQSClient);
  const sqsClient = new SQSClient({});

  await sqsClient.send(new GetQueueUrlCommand({ QueueName: 'test-queue' }));

  // the result is properly typed as `GetQueueUrlCommandInput[]`
  const input = getCommandInputs(mockSqs, GetQueueUrlCommand)[0];
  expect(input).toEqual({ QueueName: 'test-queue' });
});

A method on the mock instance itself could probably do a better job of inferring the types and enforce that the supplied command is one that is valid for that particular client type. That could be done with the above, but the types were getting too gnarly for the example to be clear.

ehaynes99 avatar Jan 16 '22 23:01 ehaynes99

I like the idea. I want to spend time on a few other feature requests, but it may be an easy win (thanks for the code @ehaynes99 !) so I will try to include it.

m-radzikowski avatar Feb 10 '22 21:02 m-radzikowski