Skip to content

Commit 8accba7

Browse files
committed
test: add mock requestUrl method by @Fevol
1 parent 395bad1 commit 8accba7

File tree

1 file changed

+32
-0
lines changed

1 file changed

+32
-0
lines changed

__mocks__/obsidian.ts

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,32 @@
1+
import { RequestUrlParam, RequestUrlResponse } from "obsidian";
2+
3+
export function requestUrl(request: RequestUrlParam): Promise<RequestUrlResponse> {
4+
return fetch(request.url, {
5+
method: request.method,
6+
headers: request.headers,
7+
body: request.body,
8+
}).then(async (response) => {
9+
if (response.status >= 400 && request.throw) {
10+
throw new Error(`Request failed, ${response.status}`);
11+
}
12+
13+
// Turn response headers into Record<string, string> object
14+
const headers: Record<string, string> = {};
15+
response.headers.forEach((value, key) => {
16+
headers[key] = value;
17+
});
18+
19+
const arraybuffer = await response.arrayBuffer();
20+
const text = arraybuffer ? new TextDecoder().decode(arraybuffer) : '';
21+
const json = text ? JSON.parse(text) : {};
22+
23+
let response_body: RequestUrlResponse = {
24+
status: response.status,
25+
headers: headers,
26+
arrayBuffer: arraybuffer,
27+
json: json,
28+
text: text,
29+
};
30+
return response_body;
31+
});
32+
}

0 commit comments

Comments
 (0)