1 import noop from '@proton/utils/noop';
3 type HttpMethod = 'get' | 'post' | 'put' | 'delete';
5 type ApiMockHandler = (...arg: any[]) => any;
9 handler: (...arg: any[]) => any;
12 type ApiMock = { [url: string]: ApiMockEntry[] | undefined };
14 export const apiMocksMap: ApiMock = {};
17 export const enableMockApiLogging = () => (logging = true);
18 export const disableMockApiLogging = () => (logging = false);
20 export const apiMock = jest.fn<Promise<any>, any>(async (args: any) => {
21 const entryKey = Object.keys(apiMocksMap).find((path) => {
22 return args.url === path;
24 const entry = apiMocksMap[entryKey || '']?.find(
25 (entry) => entry.method === undefined || entry.method === args.method
29 console.log('apiMock', args);
30 console.log('apiMock entry', entry);
32 const result = entry.handler({ ...args });
34 console.log('apiMock result', result);
41 export const addApiMock = (url: string, handler: ApiMockHandler, method?: HttpMethod) => {
42 const newEntry = { method, handler };
43 if (!apiMocksMap[url]) {
44 apiMocksMap[url] = [newEntry];
46 apiMocksMap[url] = apiMocksMap[url]?.filter((entry) => entry.method !== newEntry.method).concat([newEntry]);
50 export const addApiResolver = (url: string, method?: HttpMethod) => {
51 let resolveLastPromise: (result: any) => void = noop;
52 let rejectLastPromise: (result: any) => void = noop;
54 const resolve = (value: any) => resolveLastPromise(value);
55 const reject = (value: any) => rejectLastPromise(value);
57 const promise = new Promise((resolve, reject) => {
58 resolveLastPromise = resolve;
59 rejectLastPromise = reject;
61 addApiMock(url, () => promise, method);
62 return { resolve, reject };
65 export const clearApiMocks = () => {
66 Object.keys(apiMocksMap).forEach((key) => delete apiMocksMap[key]);