summaryrefslogtreecommitdiff
path: root/packages/merchant-backoffice-ui/src/hooks/testing.tsx
blob: fc78f6c586e55625d39251d99fb84449a0ce23c7 (plain)
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
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
/*
 This file is part of GNU Taler
 (C) 2021-2024 Taler Systems S.A.

 GNU Taler is free software; you can redistribute it and/or modify it under the
 terms of the GNU General Public License as published by the Free Software
 Foundation; either version 3, or (at your option) any later version.

 GNU Taler is distributed in the hope that it will be useful, but WITHOUT ANY
 WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR
 A PARTICULAR PURPOSE.  See the GNU General Public License for more details.

 You should have received a copy of the GNU General Public License along with
 GNU Taler; see the file COPYING.  If not, see <http://www.gnu.org/licenses/>
 */

/**
 *
 * @author Sebastian Javier Marchano (sebasjm)
 */

import { MockEnvironment } from "@gnu-taler/web-util/testing";
import { ComponentChildren, FunctionalComponent, h, VNode } from "preact";
import { HttpRequestLibrary, HttpRequestOptions, HttpResponse } from "@gnu-taler/taler-util/http";
import { SWRConfig } from "swr";
import { ApiContextProvider } from "@gnu-taler/web-util/browser";
import { TalerBankIntegrationHttpClient, TalerCoreBankHttpClient, TalerRevenueHttpClient, TalerWireGatewayHttpClient } from "@gnu-taler/taler-util";

interface RequestOptions {
  method?: "GET" | "POST" | "HEAD",
  params?: any,
  token?: string | undefined,
  data?: any,
}
interface HttpResponseOk<T> {
  ok: true,
  data: T,
  loading: boolean,
  clientError: boolean,
  serverError: boolean,
  info: any,
}

export class ApiMockEnvironment extends MockEnvironment {
  constructor(debug = false) {
    super(debug);
  }

  mockApiIfNeeded(): void {
    null; // do nothing
  }

  public buildTestingContext(): FunctionalComponent<{
    children: ComponentChildren;
  }> {
    const __SAVE_REQUEST_AND_GET_MOCKED_RESPONSE =
      this.saveRequestAndGetMockedResponse.bind(this);

    return function TestingContext({
      children,
    }: {
      children: ComponentChildren;
    }): VNode {

      async function request<T>(
        base: string,
        path: string,
        options: RequestOptions = {},
      ): Promise<HttpResponseOk<T>> {
        const _url = new URL(`${base}${path}`);
        // Object.entries(options.params ?? {}).forEach(([key, value]) => {
        //   _url.searchParams.set(key, String(value));
        // });

        const mocked = __SAVE_REQUEST_AND_GET_MOCKED_RESPONSE(
          {
            method: options.method ?? "GET",
            url: _url.href,
          },
          {
            qparam: options.params,
            auth: options.token,
            request: options.data,
          },
        );
        const status = mocked.expectedQuery?.query.code ?? 200;
        const requestPayload = mocked.expectedQuery?.params?.request;
        const responsePayload = mocked.expectedQuery?.params?.response;

        return {
          ok: true,
          data: responsePayload as T,
          loading: false,
          clientError: false,
          serverError: false,
          info: {
            hasToken: !!options.token,
            status,
            url: _url.href,
            payload: options.data,
            options: {},
          },
        };
      }
      const SC: any = SWRConfig;

      const mockHttpClient = new class implements HttpRequestLibrary {
        async fetch(url: string, options?: HttpRequestOptions | undefined): Promise<HttpResponse> {
          const _url = new URL(url);
          const mocked = __SAVE_REQUEST_AND_GET_MOCKED_RESPONSE(
            {
              method: options?.method ?? "GET",
              url: _url.href,
            },
            {
              qparam: _url.searchParams,
              auth: options as any,
              request: options?.body as any,
            },
          );
          const status = mocked.expectedQuery?.query.code ?? 200;
          const requestPayload = mocked.expectedQuery?.params?.request;
          const responsePayload = mocked.expectedQuery?.params?.response;

          // FIXME: complete this implementation to mock any query
          const resp: HttpResponse = {
            requestUrl: _url.href,
            status: status,
            headers: {} as any,
            requestMethod: options?.method ?? "GET",
            json: async () => responsePayload,
            text: async () => responsePayload as any as string,
            bytes: async () => responsePayload as ArrayBuffer,
          };
          return resp
        }
        get(url: string, opt?: HttpRequestOptions): Promise<HttpResponse> {
          return this.fetch(url, {
            method: "GET",
            ...opt,
          });
        }

        postJson(
          url: string,
          body: any,
          opt?: HttpRequestOptions,
        ): Promise<HttpResponse> {
          return this.fetch(url, {
            method: "POST",
            headers: { "Content-Type": "application/json" },
            body: JSON.stringify(body),
            ...opt,
          });
        }

      }
      const bankCore = new TalerCoreBankHttpClient("http://localhost", mockHttpClient)
      const bankIntegration = new TalerBankIntegrationHttpClient(bankCore.getIntegrationAPI().href, mockHttpClient)
      const bankRevenue = new TalerRevenueHttpClient(bankCore.getRevenueAPI("a").href, mockHttpClient)
      const bankWire = new TalerWireGatewayHttpClient(bankCore.getWireGatewayAPI("b").href, "b", mockHttpClient)

      return (
        // <BackendContextProvider defaultUrl="http://backend">
        //   <InstanceContextProvider
        //     value={{
        //       token: undefined,
        //       id: "default",
        //       admin: true,
        //       changeToken: () => null,
        //     }}
        //   >
            <ApiContextProvider value={{ request : undefined as any, bankCore, bankIntegration, bankRevenue, bankWire }}>
              <SC
                value={{
                  loadingTimeout: 0,
                  dedupingInterval: 0,
                  shouldRetryOnError: false,
                  errorRetryInterval: 0,
                  errorRetryCount: 0,
                  provider: () => new Map(),
                }}
              >
                {children}
              </SC>
            </ApiContextProvider>
        //   </InstanceContextProvider>
        // </BackendContextProvider>
      );
    };
  }
}