Skip to content

Commit

Permalink
feat: allow throwing errors in callsFake()
Browse files Browse the repository at this point in the history
fixes #8
  • Loading branch information
m-radzikowski committed Jun 26, 2023
1 parent 09d3e98 commit 67c37e6
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.md
Original file line number Diff line number Diff line change
Expand Up @@ -229,7 +229,7 @@ snsMock
if (input.Message === 'My message') {
return {MessageId: '12345678-1111-2222-3333-111122223333'};
} else {
return {MessageId: '12345678-4444-5555-6666-111122223333'};
throw new Error('mocked rejection');
}
});
```
Expand Down
13 changes: 11 additions & 2 deletions packages/aws-sdk-client-mock/src/awsClientStub.ts
Original file line number Diff line number Diff line change
Expand Up @@ -335,14 +335,23 @@ export class CommandBehavior<TInput extends object, TOutput extends MetadataBear
}

callsFake(fn: (input: any, getClient: () => Client<TInput, TOutput, TConfiguration>) => any): AwsStub<TInput, TOutput, TConfiguration> {
this.send.callsFake(cmd => fn(cmd.input, this.getClient));
this.send.callsFake(cmd => this.fakeFnWrapper(cmd, fn));
return this.clientStub;
}

callsFakeOnce(fn: (input: any, getClient: () => Client<TInput, TOutput, TConfiguration>) => any): CommandBehavior<TInput, TOutput, TCommandOutput, TConfiguration> {
this.send.onCall(this.nextChainableCallNumber++).callsFake(cmd => fn(cmd.input, this.getClient));
this.send.onCall(this.nextChainableCallNumber++).callsFake(cmd => this.fakeFnWrapper(cmd, fn));
return this;
}

private fakeFnWrapper(cmd: AwsCommand<TInput, TOutput>, fn: (input: any, getClient: () => Client<TInput, TOutput, TConfiguration>) => any) {
try {
// eslint-disable-next-line @typescript-eslint/no-unsafe-return
return fn(cmd.input, this.getClient);
} catch (err) {
return Promise.reject(CommandBehavior.normalizeError(err as string | object));
}
}
}

export type AwsCommand<Input extends ClientInput, Output extends ClientOutput, ClientInput extends object = any, ClientOutput extends MetadataBearer = any> = Command<ClientInput, Input, ClientOutput, Output, any>;
Expand Down
10 changes: 10 additions & 0 deletions packages/aws-sdk-client-mock/test/mockClient.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -315,6 +315,16 @@ describe('mocking behaviors in different ways', () => {

expect(publish1.MessageId).toBe(uuid1);
});

it('throws an error', async () => {
behavior.callsFake(() => {
throw new Error('Invalid parameter: TopicArn');
});

const sns = new SNSClient({});

await expect(sns.send(publishCmd1)).rejects.toThrow('Invalid parameter: TopicArn');
});
});

describe('supporting alternative send() calls', () => {
Expand Down

0 comments on commit 67c37e6

Please sign in to comment.