Skip to content

Commit

Permalink
feat(core): ability to use custom Sinon Sandbox (#200)
Browse files Browse the repository at this point in the history
  • Loading branch information
m-radzikowski authored Jan 1, 2024
1 parent 6f7bb59 commit 31ff180
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 2 deletions.
4 changes: 4 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -487,6 +487,10 @@ The behavior is preserved.
The `restore()` removes the mock altogether,
restoring the normal behavior of `client.send()`.

You can also pass custom [Sinon Sandbox](https://sinonjs.org/releases/latest/sandbox/)
with `mockClient(client, { sandbox: mySandbox })`
to manage all mocks lifecycle at once.

### Jest matchers

Custom [Jest](https://jestjs.io/) matchers simplify verification
Expand Down
7 changes: 5 additions & 2 deletions packages/aws-sdk-client-mock/src/mockClient.ts
Original file line number Diff line number Diff line change
@@ -1,16 +1,18 @@
import {Client, Command, MetadataBearer} from '@smithy/types';
import {SinonStub, stub} from 'sinon';
import sinon, {SinonSandbox, SinonStub} from 'sinon';
import {isSinonStub} from './sinon';
import {AwsClientStub, AwsStub} from './awsClientStub';

/**
* Creates and attaches a stub of the `Client#send()` method. Only this single method is mocked.
* If method is already a stub, it's replaced.
* @param client `Client` type or instance to replace the method
* @param sandbox Optional sinon sandbox to use
* @return Stub allowing to configure Client's behavior
*/
export const mockClient = <TInput extends object, TOutput extends MetadataBearer, TConfiguration>(
client: InstanceOrClassType<Client<TInput, TOutput, TConfiguration>>,
{sandbox}: { sandbox?: SinonSandbox } = {},
): AwsClientStub<Client<TInput, TOutput, TConfiguration>> => {
const instance = isClientInstance(client) ? client : client.prototype;

Expand All @@ -19,7 +21,8 @@ export const mockClient = <TInput extends object, TOutput extends MetadataBearer
send.restore();
}

const sendStub = stub(instance, 'send') as SinonStub<[Command<TInput, any, TOutput, any, any>], Promise<TOutput>>;
const sinonSandbox = sandbox || sinon;
const sendStub = sinonSandbox.stub(instance, 'send') as SinonStub<[Command<TInput, any, TOutput, any, any>], Promise<TOutput>>;

// eslint-disable-next-line @typescript-eslint/no-unsafe-argument
return new AwsStub<TInput, TOutput, TConfiguration>(instance, sendStub);
Expand Down

0 comments on commit 31ff180

Please sign in to comment.