-
Notifications
You must be signed in to change notification settings - Fork 40
/
jestMatchers.ts
364 lines (338 loc) Β· 12.4 KB
/
jestMatchers.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
/* eslint-disable @typescript-eslint/no-explicit-any, @typescript-eslint/no-empty-interface */
import assert from 'assert';
import type {MetadataBearer} from '@aws-sdk/types';
import type {AwsCommand, AwsStub} from 'aws-sdk-client-mock';
import type {SinonSpyCall} from 'sinon';
interface AwsSdkJestMockBaseMatchers<R> extends Record<string, any> {
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} exact number of {@link times}
*
* @param command aws-sdk command constructor
* @param times
*/
toHaveReceivedCommandTimes<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
times: number,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} at least one time
*
* @param command aws-sdk command constructor
*/
toHaveReceivedCommand<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} at least one time with matching {@link input}
*
* @param command aws-sdk command constructor
* @param input
*/
toHaveReceivedCommandWith<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
input: Partial<TCmdInput>,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} as defined {@link call} number
* with matching {@link input}
*
* @param call call number to assert
* @param command aws-sdk command constructor
* @param input
*/
toHaveReceivedNthCommandWith<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
call: number,
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
input: Partial<TCmdInput>,
): R;
}
interface AwsSdkJestMockAliasMatchers<R> {
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} exact number of {@link times}
*
* @alias {@link AwsSdkJestMockBaseMatchers.toHaveReceivedCommandTimes}
* @param command aws-sdk command constructor
* @param times
*/
toReceiveCommandTimes<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
times: number,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} at least one time
*
* @alias {@link AwsSdkJestMockBaseMatchers.toHaveReceivedCommand}
* @param command aws-sdk command constructor
*/
toReceiveCommand<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} at least one time with matching {@link input}
*
* @alias {@link AwsSdkJestMockBaseMatchers.toHaveReceivedCommandWith}
* @param command aws-sdk command constructor
* @param input
*/
toReceiveCommandWith<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
input: Partial<TCmdInput>,
): R;
/**
* Asserts {@link AwsStub Aws Client Mock} received a {@link command} as defined {@link call} number
* with matching {@link input}
*
* @alias {@link AwsSdkJestMockBaseMatchers.toHaveReceivedNthCommandWith}
* @param call call number to assert
* @param command aws-sdk command constructor
* @param input
*/
toReceiveNthCommandWith<TCmdInput extends object,
TCmdOutput extends MetadataBearer>(
call: number,
command: new (input: TCmdInput) => AwsCommand<TCmdInput, TCmdOutput>,
input: Partial<TCmdInput>,
): R;
}
/**
* Provides {@link jest} matcher for testing {@link AwsStub} command calls
*
* @example
*
* ```ts
* import { mockClient } from "aws-sdk-client-mock";
* import { ScanCommand } from "@aws-sdk/client-dynamodb";
*
* const awsMock = mockClient(DynamoDBClient);
*
* awsMock.on(ScanCommand).resolves({
* Items: [{ Info: { S: '{ "val": "info" }' }, LockID: { S: "fooId" } }],
* });
*
* it("Should call scan command", async () => {
* // check result ... maybe :)
* await expect(sut()).resolves.toEqual({ ... });
*
* // Assert awsMock to have recevied a Scan Command at least one time
* expect(awsMock).toHaveReceivedCommand(ScanCommand);
* });
* ```
*/
export interface AwsSdkJestMockMatchers<R> extends AwsSdkJestMockBaseMatchers<R>, AwsSdkJestMockAliasMatchers<R>, Record<string, any> {
}
declare global {
namespace jest {
interface Matchers<R = void> extends AwsSdkJestMockMatchers<R> {
}
}
}
type ClientMock = AwsStub<any, any>;
type AnyCommand = AwsCommand<any, any>;
type AnySpyCall = SinonSpyCall<[AnyCommand]>;
type MessageFunctionParams<CheckData> = {
cmd: string;
client: string;
commandCalls: AnySpyCall[];
data: CheckData;
notPrefix: string;
};
/**
* Prettyprints command calls for message
*/
const printCalls = (ctx: jest.MatcherContext, calls: AnySpyCall[]): string[] =>
calls.length > 0
? [
'',
'Calls:',
...calls.map(
(c, i) =>
` ${i + 1}. ${c.args[0].constructor.name}: ${ctx.utils.printReceived(
c.args[0].input,
)}`,
)]
: [];
const processMatch = <CheckData = undefined>({ctx, mockClient, command, check, message}: {
ctx: jest.MatcherContext;
mockClient: ClientMock;
command: new () => AnyCommand;
check: (params: { calls: AnySpyCall[]; commandCalls: AnySpyCall[] }) => {
pass: boolean;
data: CheckData;
};
message: (params: MessageFunctionParams<CheckData>) => string[];
}): jest.CustomMatcherResult => {
assert(
command &&
typeof command === 'function' &&
typeof command.name === 'string' &&
command.name.length > 0,
'Command must be valid AWS SDK Command',
);
const calls = mockClient.calls();
const commandCalls = mockClient.commandCalls(command);
const {pass, data} = check({calls, commandCalls});
const msg = (): string => {
const cmd = ctx.utils.printExpected(command.name);
const client = mockClient.clientName();
return [
...message({
client,
cmd,
data,
commandCalls,
notPrefix: ctx.isNot ? 'not ' : '',
}),
...printCalls(ctx, calls),
].join('\n');
};
return {pass, message: msg};
};
const baseMatchers: { [P in keyof AwsSdkJestMockBaseMatchers<unknown>]: jest.CustomMatcher } = {
/**
* implementation of {@link AwsSdkJestMockMatchers.toHaveReceivedCommand} matcher
*/
toHaveReceivedCommand(
this: jest.MatcherContext,
mockClient: ClientMock,
command: new () => AnyCommand,
) {
return processMatch({
ctx: this,
mockClient,
command,
check: ({commandCalls}) => ({pass: commandCalls.length > 0, data: undefined}),
message: ({client, cmd, notPrefix, commandCalls}) => [
`Expected ${client} to ${notPrefix}receive ${cmd}`,
`${client} received ${cmd} ${this.utils.printReceived(commandCalls.length)} times`,
],
});
},
/**
* implementation of {@link AwsSdkJestMockMatchers.toHaveReceivedCommandTimes} matcher
*/
toHaveReceivedCommandTimes(
this: jest.MatcherContext,
mockClient: ClientMock,
command: new () => AnyCommand,
expectedCalls: number,
) {
return processMatch({
ctx: this,
mockClient,
command,
check: ({commandCalls}) => ({pass: commandCalls.length === expectedCalls, data: undefined}),
message: ({client, cmd, commandCalls, notPrefix}) => [
`Expected ${client} to ${notPrefix}receive ${cmd} ${this.utils.printExpected(expectedCalls)} times`,
`${client} received ${cmd} ${this.utils.printReceived(commandCalls.length)} times`,
],
});
},
/**
* implementation of {@link AwsSdkJestMockMatchers.toHaveReceivedCommandWith} matcher
*/
toHaveReceivedCommandWith(
this: jest.MatcherContext,
mockClient: ClientMock,
command: new () => AnyCommand,
input: Record<string, unknown>,
) {
return processMatch<{ matchCount: number }>({
ctx: this,
mockClient,
command,
check: ({commandCalls}) => {
const matchCount = commandCalls
.map(call => call.args[0].input) // eslint-disable-line @typescript-eslint/no-unsafe-return
.map(received => {
try {
expect(received).toEqual(
expect.objectContaining(input),
);
return true;
} catch (e) {
return false;
}
})
.reduce((acc, val) => acc + Number(val), 0);
return {pass: matchCount > 0, data: {matchCount}};
},
message: ({client, cmd, notPrefix, data}) => [
`Expected ${client} to ${notPrefix}receive ${cmd} with ${this.utils.printExpected(input)}`,
`${client} received matching ${cmd} ${this.utils.printReceived(data.matchCount)} times`,
],
});
},
/**
* implementation of {@link AwsSdkJestMockMatchers.toHaveReceivedNthCommandWith} matcher
*/
toHaveReceivedNthCommandWith(
this: jest.MatcherContext,
mockClient: ClientMock,
call: number,
command: new () => AnyCommand,
input?: Record<string, unknown>,
) {
assert(
call && typeof call === 'number' && call > 0,
'Call number must be a number greater than 0',
);
return processMatch<{ received: AnyCommand | undefined }>({
ctx: this,
mockClient,
command,
check: ({calls}) => {
if (calls.length < call) {
return {pass: false, data: {received: undefined}};
}
const received = calls[call - 1].args[0];
let pass = false;
if (received instanceof command) {
try {
expect(received.input).toEqual(
expect.objectContaining(input),
);
pass = true;
} catch (e) { // eslint-disable-line no-empty
}
}
return {
pass,
data: {received},
};
},
message: ({cmd, client, data, notPrefix}) => [
`Expected ${client} to ${notPrefix}receive ${call}. ${cmd} with ${this.utils.printExpected(input)}`,
...(data.received
? [
`${client} received ${this.utils.printReceived(data.received.constructor.name)} with input:`,
this.utils.printDiffOrStringify(
input,
data.received.input,
'Expected',
'Received',
false,
),
]
: []),
],
});
},
};
/* typing ensures keys matching */
const aliasMatchers: { [P in keyof AwsSdkJestMockAliasMatchers<unknown>]: jest.CustomMatcher } = {
toReceiveCommandTimes: baseMatchers.toHaveReceivedCommandTimes,
toReceiveCommand: baseMatchers.toHaveReceivedCommand,
toReceiveCommandWith: baseMatchers.toHaveReceivedCommandWith,
toReceiveNthCommandWith: baseMatchers.toHaveReceivedNthCommandWith,
};
// Skip registration if jest expect does not exist
if (typeof expect !== 'undefined' && typeof expect.extend === 'function') {
expect.extend({...baseMatchers, ...aliasMatchers});
}