m-radzikowski / aws-sdk-client-mock

AWS JavaScript SDK v3 mocks for easy unit testing. 🖋️ Typed 🔬 Tested 📄 Documented 🛠️ Maintained
https://m-radzikowski.github.io/aws-sdk-client-mock/
MIT License
812 stars 40 forks source link

remock support (or clarity on the pattern) #226

Closed ahammond closed 6 months ago

ahammond commented 6 months ago

When I'm porting over tests from v2, a common pattern I see is a set of default mock with their resolves, etc in the beforeEach() and then using remock to tweak the behaviour for one or two of the mocks involved. Is there a pattern for doing this?

m-radzikowski commented 6 months ago

If I understand correctly, yes, you can set default mocking behavior in beforeEach() and then extend or override it in individual tests:

import {mockClient} from "aws-sdk-client-mock";
import {ConfirmSubscriptionCommand, PublishCommand, SNSClient} from "@aws-sdk/client-sns";
import {beforeEach, expect, it} from "@jest/globals";
import 'aws-sdk-client-mock-jest';

const sns = new SNSClient();
const snsMock = mockClient(SNSClient);

beforeEach(() => {
  snsMock.reset();
  snsMock
    .on(PublishCommand).resolves({MessageId: '000'})
    .on(ConfirmSubscriptionCommand).resolves({SubscriptionArn: 'arn:mock'});
})

it('with default mocks', async () => {
  const result = await sns.send(new PublishCommand({
    TopicArn: '',
    Message: 'hello world',
  }));

  expect(result.MessageId).toBe('000');
});

it('with overriden mocks', async () => {
  snsMock
    .on(PublishCommand).resolves({MessageId: '111'});

  const result = await sns.send(new PublishCommand({
    TopicArn: '',
    Message: 'hello world',
  }));

  expect(result.MessageId).toBe('111');
});

it('with added mocks for command matching input', async () => {
  snsMock
    .on(PublishCommand, {TopicArn: 'special'}).resolves({MessageId: '111'});

  const result1 = await sns.send(new PublishCommand({
    TopicArn: '',
    Message: 'hello world',
  }));
  const result2 = await sns.send(new PublishCommand({
    TopicArn: 'special',
    Message: 'hello world',
  }));

  expect(result1.MessageId).toBe('000');
  expect(result2.MessageId).toBe('111');
});

it('back with default mocks', async () => {
  const result = await sns.send(new PublishCommand({
    TopicArn: '',
    Message: 'hello world',
  }));

  expect(result.MessageId).toBe('000');
});

Please reopen if this is not what you meant.