Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat(core): ability to use custom Sinon Sandbox #200

Merged
merged 1 commit into from
Jan 1, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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
Loading