-
Notifications
You must be signed in to change notification settings - Fork 40
/
http-mock.ts
59 lines (51 loc) · 1.47 KB
/
http-mock.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
import type { Url } from 'node:url';
import nock from 'nock'; // eslint-disable-line no-restricted-imports
import { afterAll, afterEach, beforeAll } from 'vitest';
type BasePath = string | RegExp | Url;
let missingLog: string[] = [];
interface TestRequest {
method: string;
href: string;
}
function onMissing(req: TestRequest, opts?: TestRequest): void {
if (opts) {
missingLog.push(` ${opts.method} ${opts.href}`);
} else {
missingLog.push(` ${req.method} ${req.href}`);
}
}
/**
* Clear nock state. Will be called in `afterEach`
* @argument throwOnPending Use `false` to simply clear mocks.
*/
export function clear(throwOnPending = true): void {
const isDone = nock.isDone();
const pending = nock.pendingMocks();
nock.abortPendingRequests();
nock.cleanAll();
const missing = missingLog;
missingLog = [];
if (missing.length && throwOnPending) {
throw new Error(`Missing mocks!\n * ${missing.join('\n * ')}`);
}
if (!isDone && throwOnPending) {
throw new Error(`Pending mocks!\n * ${pending.join('\n * ')}`);
}
}
export function scope(basePath: BasePath, options?: nock.Options): nock.Scope {
return nock(basePath, options);
}
// init nock
beforeAll(() => {
nock.emitter.on('no match', onMissing);
nock.disableNetConnect();
});
// clean nock to clear memory leack from http module patching
afterAll(() => {
nock.emitter.removeListener('no match', onMissing);
nock.restore();
});
// clear nock state
afterEach(() => {
clear();
});