forked from Unleash/unleash-proxy-client-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.ts
44 lines (37 loc) · 1.24 KB
/
index.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
import type { FetchMock } from 'jest-fetch-mock';
/**
* Extract request body from given `FetchMock` object.
* @param fetchedMock - mocked fetch body to get the request body from
* @param callIndex - index of call in given `fetcheMock`
*/
function getTypeSafeRequest(
fetchedMock: FetchMock,
callIndex: number | undefined = 0
): RequestInit {
const mockedCall = fetchedMock.mock.calls[callIndex];
const [, mockedReq] = mockedCall;
const typeSafeRequest = mockedReq ?? {};
return typeSafeRequest;
}
/**
* Extract request url from given `FetchMock` object.
* @param fetchedMock - mocked fetch body to get the request url from
* @param callIndex - index of call in given `fetcheMock`
*/
function getTypeSafeRequestUrl(
fetchedMock: FetchMock,
callIndex: number | undefined = 0
): string {
const mockedCall = fetchedMock.mock.calls[callIndex];
const [url] = mockedCall;
return url as string;
}
/**
* parses given `RequestInit` with `JSON.parse()` and return
* its body with passed type.
*/
function parseRequestBodyWithType<T>(requestBody: RequestInit): T {
const body = JSON.parse(`${requestBody.body}`) as T;
return body;
}
export { getTypeSafeRequest, getTypeSafeRequestUrl, parseRequestBodyWithType };