-
Notifications
You must be signed in to change notification settings - Fork 72
Expand file tree
/
Copy pathaxios-mock.ts
More file actions
48 lines (41 loc) · 1.08 KB
/
axios-mock.ts
File metadata and controls
48 lines (41 loc) · 1.08 KB
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
import axios from "axios";
jest.mock("axios");
interface RecordedCall {
method: string;
url: string;
data: any;
headers: any;
}
export function createAxiosMock() {
const calls: RecordedCall[] = [];
const responses: Record<string, any> = {};
const mockedAxios = axios as jest.MockedFunction<typeof axios>;
mockedAxios.mockImplementation(async (config: any) => {
const call: RecordedCall = {
method: config.method,
url: config.url,
data: config.data,
headers: config.headers,
};
calls.push(call);
const matchingKey = Object.keys(responses).find(
(k) => config.url?.includes(k)
);
if (matchingKey) {
return { data: responses[matchingKey], status: 200 };
}
return { data: { uuid: `mock-uuid-${calls.length}` }, status: 200 };
});
return {
mock: mockedAxios,
calls,
setResponse(endpoint: string, response: any) {
responses[endpoint] = response;
},
reset() {
calls.length = 0;
Object.keys(responses).forEach((k) => delete responses[k]);
mockedAxios.mockClear();
},
};
}