-
Notifications
You must be signed in to change notification settings - Fork 0
/
shr.mocks.ts
39 lines (33 loc) · 1.34 KB
/
shr.mocks.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
import debug = require('debug');
let debugLog = debug('shr');
import { RequestOptions, RequestOptionsParameters, SimpleHttpsRequest } from './shr';
// Functions we can use to test consumers of this library
export class ShrMockerIoPair {
public opts: RequestOptions;
constructor(
optsParams: RequestOptionsParameters,
public result: string | object // Allow object to simulate automatic parsing of server's JSON response
) {
this.opts = new RequestOptions(optsParams);
}
}
export class ShrMocker implements SimpleHttpsRequest {
constructor(public ioPairs: ShrMockerIoPair[]) {};
public req(options: RequestOptions): Promise<any> {
debugLog(`${options.method} ${options.fullUrl}`);
let resultPromise: Promise<any> | undefined;
this.ioPairs.forEach((pair) => {
if (options.equals(pair.opts)) {
resultPromise = Promise.resolve(pair.result)
return;
}
});
if (resultPromise) {
return resultPromise;
} else {
let errMsg = `\n${options.method} ${options.fullUrl} (input request) do not match any known input/output pair:\n`;
this.ioPairs.forEach(pair => errMsg += `${pair.opts.method} ${pair.opts.fullUrl}\n`);
return Promise.reject(new Error(errMsg));
}
}
}