@griddo/ax 12.14.3 → 12.15.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (53) hide show
  1. package/README.md +1 -0
  2. package/package.json +7 -4
  3. package/src/GlobalStore.tsx +32 -25
  4. package/src/__tests__/GlobalStore.session.test.tsx +98 -0
  5. package/src/__tests__/api/global.test.ts +64 -0
  6. package/src/__tests__/api/session.test.ts +311 -0
  7. package/src/__tests__/api/sessionRenewal.test.ts +705 -0
  8. package/src/__tests__/api/utils.test.ts +373 -0
  9. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +33 -6
  10. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +5 -3
  11. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +195 -0
  12. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +86 -0
  13. package/src/__tests__/containers/App/reducer.griddoId.test.ts +18 -0
  14. package/src/__tests__/containers/App/session.test.ts +397 -0
  15. package/src/__tests__/helpers/griddoId.test.ts +56 -0
  16. package/src/__tests__/locales/loginLocale.test.ts +52 -0
  17. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +54 -0
  18. package/src/__tests__/modules/Login/Login.test.tsx +151 -0
  19. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +19 -0
  20. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +19 -0
  21. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +19 -0
  22. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +30 -0
  23. package/src/__tests__/routes/publicRoutes.test.ts +36 -0
  24. package/src/api/global.tsx +24 -1
  25. package/src/api/session.tsx +197 -0
  26. package/src/api/sessionRenewal.tsx +114 -0
  27. package/src/api/utils.tsx +22 -12
  28. package/src/{helpers/categoryColumns.tsx → components/CategoryCell/buildCategoryColumns.tsx} +3 -2
  29. package/src/{helpers/fields.tsx → components/FieldsBehavior/getFieldByPath.tsx} +1 -1
  30. package/src/components/FieldsBehavior/index.tsx +3 -1
  31. package/src/components/Login/LoginForm/index.tsx +7 -2
  32. package/src/components/Login/LoginGriddoId/index.tsx +46 -0
  33. package/src/components/Login/LoginGriddoId/style.tsx +35 -0
  34. package/src/components/Login/index.tsx +13 -1
  35. package/src/components/SsoDenied/index.tsx +46 -0
  36. package/src/components/SsoDenied/style.tsx +37 -0
  37. package/src/components/index.tsx +11 -7
  38. package/src/containers/App/actions.tsx +110 -5
  39. package/src/containers/App/interfaces.tsx +2 -2
  40. package/src/containers/App/reducer.tsx +9 -0
  41. package/src/containers/Users/actions.tsx +28 -24
  42. package/src/helpers/griddoId.ts +28 -0
  43. package/src/helpers/index.tsx +4 -5
  44. package/src/locales/en-US.ts +7 -0
  45. package/src/locales/es-ES.ts +7 -0
  46. package/src/locales/index.ts +10 -0
  47. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  48. package/src/modules/Content/PageItem/index.tsx +6 -8
  49. package/src/modules/Login/index.tsx +12 -2
  50. package/src/modules/SsoDenied/index.tsx +9 -0
  51. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +6 -8
  52. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +9 -11
  53. package/src/routes/publicRoutes.tsx +3 -0
@@ -0,0 +1,373 @@
1
+ import { SET_ERROR } from "@ax/containers/App/constants";
2
+
3
+ import type { Mock } from "vitest";
4
+
5
+ import { registerSessionBridge, resetSessionState, setSession } from "../../api/session";
6
+ import utils, {
7
+ getToken,
8
+ handleResponse,
9
+ type IServiceConfig,
10
+ sendInitialRequest,
11
+ sendRequest,
12
+ sendUploadRequest,
13
+ } from "../../api/utils";
14
+ import { setStore } from "../../storeRegistry";
15
+
16
+ // Mock compartido con el módulo de renovación (mismo `axios` en toda la cadena).
17
+ const mockedAxios = vi.hoisted(() => vi.fn());
18
+ vi.mock("axios", () => ({ default: mockedAxios }));
19
+
20
+ const httpError = (status: number | undefined) =>
21
+ Object.assign(
22
+ new Error(`HTTP ${status}`),
23
+ status === undefined ? {} : { response: { status, data: { code: status } } },
24
+ );
25
+
26
+ const service = (extra: Partial<IServiceConfig> = {}): IServiceConfig => ({
27
+ host: "http://api",
28
+ endpoint: "/pages",
29
+ method: "GET",
30
+ headers: { "Content-type": "application/json", accept: "application/json" },
31
+ hasToken: true,
32
+ dynamicUrl: "",
33
+ ...extra,
34
+ });
35
+
36
+ /** Las peticiones con el token viejo dan 401; con el nuevo, 200. La renovación devuelve el par nuevo. */
37
+ const stage = () => {
38
+ mockedAxios.mockImplementation(async (config: any) => {
39
+ if (String(config.url).endsWith("/login_refresh"))
40
+ return { status: 200, data: { token: "new", refreshToken: "r-new" } };
41
+ if (config.headers?.Authorization === "bearer old") throw httpError(401);
42
+ return { status: 200, data: { ok: config.headers?.Authorization } };
43
+ });
44
+ };
45
+
46
+ const refreshCalls = () => mockedAxios.mock.calls.filter(([c]: any[]) => String(c.url).endsWith("/login_refresh"));
47
+
48
+ let onExpired: Mock<() => void>;
49
+
50
+ beforeEach(() => {
51
+ localStorage.clear();
52
+ resetSessionState();
53
+ onExpired = vi.fn();
54
+ registerSessionBridge({ onExpired });
55
+ setSession("old", "r-old");
56
+ });
57
+
58
+ describe("getToken", () => {
59
+ it("devuelve la cabecera con el token de la sesión vigente", () => {
60
+ expect(getToken()).toEqual({ Authorization: "bearer old" });
61
+ });
62
+
63
+ it("sin sesión devuelve null", () => {
64
+ resetSessionState();
65
+ expect(getToken()).toBeNull();
66
+ });
67
+ });
68
+
69
+ describe("las tres vías de petición renuevan y reintentan ante 401", () => {
70
+ it("sendRequest", async () => {
71
+ stage();
72
+ const response = await sendRequest(service());
73
+ expect(response.status).toBe(200);
74
+ expect(response.data).toEqual({ ok: "bearer new" });
75
+ expect(refreshCalls()).toHaveLength(1);
76
+ });
77
+
78
+ it("sendRequest con cuerpo (POST) conserva los datos al reintentar", async () => {
79
+ stage();
80
+ await sendRequest(service({ method: "POST" }), { a: 1 });
81
+ const retry = mockedAxios.mock.calls.at(-1)?.[0] as any;
82
+ expect(retry.data).toEqual({ a: 1 });
83
+ expect(retry.headers.Authorization).toBe("bearer new");
84
+ });
85
+
86
+ it("sendInitialRequest (token explícito)", async () => {
87
+ stage();
88
+ const response = await sendInitialRequest(service(), "old");
89
+ expect(response.data).toEqual({ ok: "bearer new" });
90
+ expect(refreshCalls()).toHaveLength(1);
91
+ });
92
+
93
+ it("sendInitialRequest con PUT envía los datos también en el reintento", async () => {
94
+ stage();
95
+ await sendInitialRequest(service({ method: "PUT" }), "old", { x: 2 });
96
+ const retry = mockedAxios.mock.calls.at(-1)?.[0] as any;
97
+ expect(retry.data).toEqual({ x: 2 });
98
+ expect(retry.headers.Authorization).toBe("bearer new");
99
+ });
100
+
101
+ it("sendUploadRequest conserva el FormData al reintentar", async () => {
102
+ stage();
103
+ const form = new FormData();
104
+ form.append("file", new File(["x"], "a.txt"));
105
+ const response = await sendUploadRequest(service({ method: "POST" }), form);
106
+ expect(response.status).toBe(200);
107
+ expect((mockedAxios.mock.calls[mockedAxios.mock.calls.length - 1][0] as any).data).toBe(form);
108
+ expect(refreshCalls()).toHaveLength(1);
109
+ });
110
+ });
111
+
112
+ describe("sin renovación posible", () => {
113
+ it("devuelve la respuesta 401 original al llamante (como antes) y cierra la sesión una vez", async () => {
114
+ mockedAxios.mockImplementation(async () => {
115
+ throw httpError(401);
116
+ });
117
+ setSession("old", null);
118
+
119
+ const response = await sendRequest(service());
120
+
121
+ expect(response.status).toBe(401);
122
+ expect(onExpired).toHaveBeenCalledTimes(1);
123
+ });
124
+
125
+ it("un servicio con skipAuthRenewal (login, password/init, logout) no renueva ni cierra", async () => {
126
+ mockedAxios.mockImplementation(async () => {
127
+ throw httpError(401);
128
+ });
129
+
130
+ const response = await sendRequest(service({ skipAuthRenewal: true }));
131
+ const initial = await sendInitialRequest(service({ skipAuthRenewal: true }), "old");
132
+ const upload = await sendUploadRequest(service({ skipAuthRenewal: true, method: "POST" }), new FormData());
133
+
134
+ expect([response.status, initial.status, upload.status]).toEqual([401, 401, 401]);
135
+ expect(refreshCalls()).toHaveLength(0);
136
+ expect(onExpired).not.toHaveBeenCalled();
137
+ });
138
+
139
+ it("una petición sin token (hasToken false) con 401 es un error normal", async () => {
140
+ mockedAxios.mockImplementation(async () => {
141
+ throw httpError(401);
142
+ });
143
+
144
+ const response = await sendRequest(service({ hasToken: false }));
145
+
146
+ expect(response.status).toBe(401);
147
+ expect(refreshCalls()).toHaveLength(0);
148
+ expect(onExpired).not.toHaveBeenCalled();
149
+ });
150
+
151
+ it.each([403, 404, 500])("%s llega al llamante sin tocar la sesión", async (status) => {
152
+ mockedAxios.mockImplementation(async () => {
153
+ throw httpError(status);
154
+ });
155
+
156
+ const response = await sendRequest(service());
157
+
158
+ expect(response.status).toBe(status);
159
+ expect(refreshCalls()).toHaveLength(0);
160
+ expect(onExpired).not.toHaveBeenCalled();
161
+ });
162
+
163
+ it("la red caída sigue devolviendo undefined como antes", async () => {
164
+ mockedAxios.mockImplementation(async () => {
165
+ throw Object.assign(new Error("Network Error"), {});
166
+ });
167
+ expect(await sendRequest(service())).toBeUndefined();
168
+ });
169
+ });
170
+
171
+ describe("compatibilidad con la API actual", () => {
172
+ it("si nunca responde 401 funciona igual que antes", async () => {
173
+ setSession("legacy", null);
174
+ mockedAxios.mockResolvedValue({ status: 200, data: { fine: true } });
175
+
176
+ const response = await sendRequest(service());
177
+
178
+ expect(response.data).toEqual({ fine: true });
179
+ expect(mockedAxios).toHaveBeenCalledTimes(1);
180
+ expect((mockedAxios.mock.calls[0][0] as any).headers.Authorization).toBe("bearer legacy");
181
+ });
182
+ });
183
+
184
+ describe("peticiones fuera del interceptor", () => {
185
+ it("una llamada directa a axios con 401 no renueva (comportamiento documentado)", async () => {
186
+ const { default: axios } = await import("axios");
187
+ mockedAxios.mockRejectedValue(httpError(401));
188
+
189
+ await expect(axios({ url: "http://api/x", headers: { Authorization: "bearer old" } })).rejects.toMatchObject({
190
+ response: { status: 401 },
191
+ });
192
+
193
+ expect(refreshCalls()).toHaveLength(0);
194
+ });
195
+ });
196
+
197
+ const lastConfig = () => mockedAxios.mock.calls[mockedAxios.mock.calls.length - 1][0] as any;
198
+
199
+ describe("cabeceras y URL de las peticiones", () => {
200
+ beforeEach(() => {
201
+ mockedAxios.mockResolvedValue({ status: 200, data: {} });
202
+ setStore(null);
203
+ sessionStorage.clear();
204
+ });
205
+
206
+ it("usa host + endpoint, o dynamicUrl si existe, con método y responseType", async () => {
207
+ await sendRequest(service({ responseType: "blob" }));
208
+ expect(lastConfig()).toMatchObject({ url: "http://api/pages", method: "GET", responseType: "blob" });
209
+
210
+ await sendRequest(service({ dynamicUrl: "http://api/custom?x=1" }));
211
+ expect(lastConfig().url).toBe("http://api/custom?x=1");
212
+ });
213
+
214
+ it("incluye el token solo si el servicio lo pide", async () => {
215
+ await sendRequest(service({ hasToken: true }));
216
+ expect(lastConfig().headers.Authorization).toBe("bearer old");
217
+
218
+ await sendRequest(service({ hasToken: false }));
219
+ expect(lastConfig().headers.Authorization).toBeUndefined();
220
+ });
221
+
222
+ it("lang y site salen del store si existe", async () => {
223
+ setStore({ getState: () => ({ app: { lang: { id: 9 } }, sites: { currentSiteInfo: { id: 5 } } }) });
224
+
225
+ await sendRequest(service());
226
+
227
+ expect(lastConfig().headers).toMatchObject({ lang: 9, site: 5 });
228
+ });
229
+
230
+ it("con store pero sin idioma o site, lang y site son null", async () => {
231
+ setStore({ getState: () => ({}) });
232
+
233
+ await sendRequest(service());
234
+
235
+ expect(lastConfig().headers).toMatchObject({ lang: null, site: null });
236
+ });
237
+
238
+ it("con store que devuelve undefined no revienta", async () => {
239
+ setStore({ getState: () => undefined });
240
+
241
+ await sendRequest(service());
242
+
243
+ expect(lastConfig().headers).toMatchObject({ lang: null, site: null });
244
+ });
245
+
246
+ it("sin store lee langID y siteID de localStorage", async () => {
247
+ localStorage.setItem("langID", "3");
248
+ localStorage.setItem("siteID", "8");
249
+
250
+ await sendRequest(service());
251
+
252
+ expect(lastConfig().headers).toMatchObject({ lang: 3, site: 8 });
253
+ });
254
+
255
+ it("sin store ni localStorage envía objetos vacíos", async () => {
256
+ await sendRequest(service());
257
+
258
+ expect(lastConfig().headers).toMatchObject({ lang: {}, site: {} });
259
+ });
260
+
261
+ it("añade las cabeceras de previsualización solo si hay página y entidad", async () => {
262
+ sessionStorage.setItem("previewPageId", "12");
263
+ sessionStorage.setItem("previewEntity", "page");
264
+ await sendRequest(service());
265
+ expect(lastConfig().headers).toMatchObject({ "x-preview-share-page-id": "12", "x-preview-share-entity": "page" });
266
+
267
+ await sendRequest(service({ hasToken: false }));
268
+ expect(lastConfig().headers).toMatchObject({ "x-preview-share-page-id": "12", "x-preview-share-entity": "page" });
269
+
270
+ sessionStorage.removeItem("previewEntity");
271
+ await sendRequest(service());
272
+ expect(lastConfig().headers["x-preview-share-page-id"]).toBeUndefined();
273
+ });
274
+
275
+ it("sendRequest: dataHeader se funde con las cabeceras y los datos solo viajan si no es GET", async () => {
276
+ await sendRequest(service({ method: "POST" }), { a: 1 }, { "x-custom": "v" });
277
+ expect(lastConfig().headers["x-custom"]).toBe("v");
278
+ expect(lastConfig().headers.Authorization).toBe("bearer old");
279
+ expect(lastConfig().data).toEqual({ a: 1 });
280
+
281
+ await sendRequest(service(), { a: 1 });
282
+ expect(lastConfig().data).toBeUndefined();
283
+ });
284
+
285
+ it("sendInitialRequest: token explícito, datos solo en PUT y POST", async () => {
286
+ await sendInitialRequest(service({ method: "GET" }), "tk", { z: 1 });
287
+ expect(lastConfig().headers.Authorization).toBe("bearer tk");
288
+ expect(lastConfig().data).toBeUndefined();
289
+
290
+ await sendInitialRequest(service({ method: "DELETE" }), "tk", { z: 1 });
291
+ expect(lastConfig().data).toBeUndefined();
292
+
293
+ await sendInitialRequest(service({ method: "POST", dynamicUrl: "http://api/dyn" }), "tk", { z: 1 });
294
+ expect(lastConfig()).toMatchObject({ url: "http://api/dyn", data: { z: 1 } });
295
+ });
296
+
297
+ it("sendUploadRequest: el progreso se informa en porcentaje y solo si se pide", async () => {
298
+ const setProgress = vi.fn();
299
+ await sendUploadRequest(service({ method: "POST" }), new FormData(), setProgress);
300
+ lastConfig().onUploadProgress({ loaded: 50, total: 200 });
301
+ expect(setProgress).toHaveBeenCalledTimes(1);
302
+ expect(setProgress).toHaveBeenCalledWith(25);
303
+
304
+ await sendUploadRequest(service({ method: "POST" }), new FormData());
305
+ expect(lastConfig().onUploadProgress).toBeUndefined();
306
+ });
307
+ });
308
+
309
+ describe("errores sin respuesta de la API", () => {
310
+ const platformError = (extra: Record<string, unknown> = {}) => Object.assign(new Error("boom"), extra);
311
+
312
+ it.each([
313
+ ["sendRequest", () => sendRequest(service())],
314
+ ["sendInitialRequest", () => sendInitialRequest(service(), "old")],
315
+ ["sendUploadRequest", () => sendUploadRequest(service({ method: "POST" }), new FormData())],
316
+ ])("%s devuelve un error de plataforma con código y mensaje", async (_n, call) => {
317
+ mockedAxios.mockRejectedValue(platformError({ code: "ECONNABORTED", status: 0 }));
318
+
319
+ expect(await call()).toEqual({ status: 0, data: { code: "ECONNABORTED", message: "boom" } });
320
+ });
321
+
322
+ it.each([
323
+ ["sendRequest", () => sendRequest(service())],
324
+ ["sendInitialRequest", () => sendInitialRequest(service(), "old")],
325
+ ["sendUploadRequest", () => sendUploadRequest(service({ method: "POST" }), new FormData())],
326
+ ])("%s usa valores por defecto si el error no trae código ni mensaje", async (_n, call) => {
327
+ mockedAxios.mockRejectedValue({});
328
+
329
+ expect(await call()).toEqual({ status: undefined, data: { code: "unknown", message: "Platform error" } });
330
+ });
331
+
332
+ it("Network Error devuelve la respuesta (undefined) en las tres vías", async () => {
333
+ mockedAxios.mockRejectedValue(new Error("Network Error"));
334
+
335
+ expect(await sendInitialRequest(service(), "old")).toBeUndefined();
336
+ expect(await sendUploadRequest(service({ method: "POST" }), new FormData())).toBeUndefined();
337
+ });
338
+ });
339
+
340
+ describe("handleResponse", () => {
341
+ it.each([
342
+ [199, false],
343
+ [200, true],
344
+ [399, true],
345
+ [400, false],
346
+ ])("isSuccessful(%s) = %s", (status, expected) => {
347
+ expect(utils.isSuccessful(status)).toBe(expected);
348
+ });
349
+
350
+ it("una respuesta correcta pasa sus datos al successHandler", () => {
351
+ const successHandler = vi.fn().mockReturnValue({ ok: true });
352
+
353
+ expect(handleResponse({ status: 200, data: { a: 1 } } as any, successHandler)).toEqual({ ok: true });
354
+ expect(successHandler).toHaveBeenCalledWith({ a: 1 });
355
+ });
356
+
357
+ it("un error usa el handler propio con el status", () => {
358
+ const customErrorHandler = vi.fn().mockReturnValue({ custom: true });
359
+
360
+ expect(handleResponse({ status: 404, data: {} } as any, vi.fn(), customErrorHandler)).toEqual({ custom: true });
361
+ expect(customErrorHandler).toHaveBeenCalledWith(404);
362
+ });
363
+
364
+ it("un error sin handler propio devuelve la acción de error genérica", () => {
365
+ const successHandler = vi.fn();
366
+
367
+ expect(handleResponse({ status: 500, data: {} } as any, successHandler)).toEqual({
368
+ type: SET_ERROR,
369
+ payload: { errorType: 500, errorText: "This is a generic error" },
370
+ });
371
+ expect(successHandler).not.toHaveBeenCalled();
372
+ });
373
+ });
@@ -1,18 +1,43 @@
1
1
  import React from "react";
2
- import { ThemeProvider } from "styled-components";
2
+
3
+ import FileField, { type IFileFieldProps } from "@ax/components/Fields/FileField";
3
4
  import { parseTheme } from "@ax/helpers";
4
5
  import globalTheme from "@ax/themes/theme.json";
5
- import { mock } from "vitest-mock-extended";
6
- import { render, screen, cleanup } from "../../../../../config/tests/test-utils";
7
- import FileField, { type IFileFieldProps } from "@ax/components/Fields/FileField";
6
+
8
7
  import { act } from "react-dom/test-utils";
9
- import thunk from "redux-thunk";
10
8
  import configureStore from "redux-mock-store";
9
+ import thunk from "redux-thunk";
10
+ import { ThemeProvider } from "styled-components";
11
+ import { mock } from "vitest-mock-extended";
11
12
 
13
+ import { cleanup, render, screen } from "../../../../../config/tests/test-utils";
12
14
  import { defaultStore } from "./../../../../__mocks__/store/GenericStore";
13
15
 
16
+ // FileGallery pide la carpeta y el árbol al montarse y, al resolver, hace
17
+ // `setIsLoading(false)`. Con la API real esa petición acababa después de que
18
+ // vitest desmontara jsdom y reventaba con "window is not defined" (flaky en CI).
19
+ vi.mock("@ax/api", async (importOriginal) => {
20
+ const actual = (await importOriginal()) as any;
21
+
22
+ return {
23
+ ...actual,
24
+ files: {
25
+ ...actual.files,
26
+ getFolderContent: () => Promise.resolve({ status: 200, data: { folders: [], files: [] } }),
27
+ getFoldersTree: () => Promise.resolve({ status: 200, data: [] }),
28
+ },
29
+ };
30
+ });
31
+
14
32
  afterEach(cleanup);
15
33
 
34
+ // Deja que se asienten las peticiones simuladas del FileGallery antes de que
35
+ // acabe el test: un macrotask vacía toda la cadena de promesas ya resueltas.
36
+ const flushRequests = () =>
37
+ act(async () => {
38
+ await new Promise((resolve) => setTimeout(resolve, 0));
39
+ });
40
+
16
41
  // Props por test. Antes se compartía un objeto mutable: el segundo test dejaba
17
42
  // `value` en undefined y los dos de "onClick events" contaban con eso sin
18
43
  // decirlo, así que al reordenarlos se caían.
@@ -70,7 +95,7 @@ describe("FileField component rendering", () => {
70
95
  });
71
96
 
72
97
  describe("onClick events", () => {
73
- it("should open FileDragAndDrop when clicking the file button", () => {
98
+ it("should open FileDragAndDrop when clicking the file button", async () => {
74
99
  const Component = (
75
100
  <ThemeProvider theme={parseTheme(globalTheme)}>
76
101
  <FileField {...makeProps({ value: undefined })} />
@@ -84,6 +109,8 @@ describe("onClick events", () => {
84
109
 
85
110
  rerender(Component);
86
111
 
112
+ await flushRequests();
113
+
87
114
  const fileDragAndDropWrapper = screen.queryByTestId("file-drag-and-drop-wrapper");
88
115
  expect(fileDragAndDropWrapper).toBeTruthy();
89
116
  });
@@ -3,7 +3,7 @@ import "@testing-library/jest-dom";
3
3
 
4
4
  import FieldsBehavior from "@ax/components/FieldsBehavior";
5
5
  import { getValidity } from "@ax/forms";
6
- import { getFieldByPath, isEmptyContainer, parseTheme, slugify } from "@ax/helpers";
6
+ import { isEmptyContainer, parseTheme, slugify } from "@ax/helpers";
7
7
  import globalTheme from "@ax/themes/theme.json";
8
8
 
9
9
  import { cleanup, fireEvent, render, screen, waitFor } from "@testing-library/react";
@@ -15,13 +15,15 @@ vi.mock("@ax/forms", async () => ({
15
15
  }));
16
16
  vi.mock("@ax/helpers", async () => ({
17
17
  ...(await vi.importActual("@ax/helpers")),
18
- getFieldByPath: vi.fn(() => () => <div data-testid="mock-field" />),
19
18
  isEmptyContainer: vi.fn(() => ({ isEmpty: false })),
20
19
  slugify: vi.fn((text: string) => (text || "").toLowerCase().replace(/\s+/g, "-")),
21
20
  }));
22
21
 
22
+ vi.mock("@ax/components/FieldsBehavior/getFieldByPath", () => ({
23
+ getFieldByPath: vi.fn(() => () => <div data-testid="mock-field" />),
24
+ }));
25
+
23
26
  const mockGetValidity = getValidity as MockedFunction<typeof getValidity>;
24
- const _mockGetFieldByPath = getFieldByPath as MockedFunction<typeof getFieldByPath>;
25
27
  const mockIsEmptyContainer = isEmptyContainer as MockedFunction<typeof isEmptyContainer>;
26
28
  const mockSlugify = slugify as MockedFunction<typeof slugify>;
27
29
 
@@ -0,0 +1,195 @@
1
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
2
+ import { ThemeProvider } from "styled-components";
3
+ import "@testing-library/jest-dom";
4
+
5
+ import Login, { type ILoginProps } from "@ax/components/Login";
6
+ import { parseTheme } from "@ax/helpers";
7
+ import globalTheme from "@ax/themes/theme.json";
8
+
9
+ afterEach(cleanup);
10
+
11
+ const baseSettings = {
12
+ cloudinaryName: "cloudinary",
13
+ globalLogoBig: "",
14
+ globalLogoMini: "",
15
+ siteLogoBig: "",
16
+ siteLogoMini: "",
17
+ welcomeText1: "Welcome back to",
18
+ welcomeText2: "Griddo",
19
+ autoSummary: false,
20
+ autoTranslation: false,
21
+ SSOActivated: false,
22
+ GriddoIdEnabled: false,
23
+ SSOWelcomeText: "",
24
+ useForms: false,
25
+ };
26
+
27
+ const renderLoginContainer = (settings: Partial<typeof baseSettings>, props: Partial<ILoginProps> = {}) => {
28
+ const handlers = {
29
+ handleSubmit: vi.fn((e: React.FormEvent) => e.preventDefault()),
30
+ handleSSO: vi.fn(),
31
+ handleGriddoId: vi.fn(),
32
+ };
33
+
34
+ const { container } = render(
35
+ <ThemeProvider theme={parseTheme(globalTheme)}>
36
+ <Login
37
+ email=""
38
+ handleEmail={vi.fn()}
39
+ password=""
40
+ handlePassword={vi.fn()}
41
+ isLoggingIn={false}
42
+ rememberMe={false}
43
+ handleRememberMe={vi.fn()}
44
+ isLoginSuccess={false}
45
+ handleLoginSuccess={vi.fn()}
46
+ errorSSO={null}
47
+ {...handlers}
48
+ {...props}
49
+ settings={{ ...baseSettings, ...settings } as ILoginProps["settings"]}
50
+ />
51
+ </ThemeProvider>,
52
+ );
53
+
54
+ return { container, ...handlers };
55
+ };
56
+
57
+ const renderLogin = (settings: Partial<typeof baseSettings>, props: Partial<ILoginProps> = {}) => {
58
+ const { container: _container, ...handlers } = renderLoginContainer(settings, props);
59
+
60
+ return handlers;
61
+ };
62
+
63
+ const setLanguage = (language: string) => vi.spyOn(window.navigator, "language", "get").mockReturnValue(language);
64
+
65
+ describe("Login con auth.griddo.io", () => {
66
+ beforeEach(() => setLanguage("es-ES"));
67
+
68
+ it("con el flag activo el formulario sigue siendo la pantalla principal y «Entrar con Griddo» va debajo", () => {
69
+ renderLogin({ GriddoIdEnabled: true });
70
+
71
+ const email = screen.getByPlaceholderText("Type your email");
72
+ const login = screen.getByText("Login");
73
+ const griddo = screen.getByRole("button", { name: "Entrar con Griddo" });
74
+
75
+ expect(screen.getByText("Lost your password?")).toBeInTheDocument();
76
+ expect(email.compareDocumentPosition(griddo) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
77
+ expect(login.compareDocumentPosition(griddo) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
78
+ expect(screen.queryByText("Microsoft ID")).toBeNull();
79
+ });
80
+
81
+ it("entre el formulario y el botón hay un separador «o»", () => {
82
+ renderLogin({ GriddoIdEnabled: true });
83
+
84
+ const divider = screen.getByText("o");
85
+
86
+ expect(screen.getByText("Login").compareDocumentPosition(divider) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy();
87
+ expect(
88
+ divider.compareDocumentPosition(screen.getByRole("button", { name: "Entrar con Griddo" })) &
89
+ Node.DOCUMENT_POSITION_FOLLOWING,
90
+ ).toBeTruthy();
91
+ });
92
+
93
+ it("con el flag activo se puede iniciar sesión con usuario y contraseña", () => {
94
+ const { handleSubmit } = renderLogin({ GriddoIdEnabled: true });
95
+
96
+ fireEvent.click(screen.getByText("Login"));
97
+
98
+ expect(handleSubmit).toHaveBeenCalledTimes(1);
99
+ });
100
+
101
+ it("ya no existe el enlace «Acceso de administración»", () => {
102
+ renderLogin({ GriddoIdEnabled: true, SSOActivated: true });
103
+
104
+ expect(screen.queryByText("Acceso de administración")).toBeNull();
105
+ expect(screen.queryByText("Administrator access")).toBeNull();
106
+ });
107
+
108
+ it("con el flag apagado el login es el de siempre y no hay botón nuevo ni separador", () => {
109
+ renderLogin({ GriddoIdEnabled: false });
110
+
111
+ expect(screen.queryByText("Entrar con Griddo")).toBeNull();
112
+ expect(screen.queryByText("o")).toBeNull();
113
+ expect(screen.getByPlaceholderText("Type your email")).toBeInTheDocument();
114
+ expect(screen.getByText("Login")).toBeInTheDocument();
115
+ });
116
+
117
+ it("con Comillas y Griddo ID la pantalla es la de Comillas: sin formulario, sin «Entrar con Griddo» y sin separador", () => {
118
+ const { handleGriddoId } = renderLogin({ GriddoIdEnabled: true, SSOActivated: true });
119
+
120
+ expect(screen.getByRole("button", { name: /Microsoft ID/ })).toBeInTheDocument();
121
+ expect(screen.queryByRole("button", { name: "Entrar con Griddo" })).toBeNull();
122
+ expect(screen.queryByText("Sign in with Griddo")).toBeNull();
123
+ expect(screen.queryByText("o")).toBeNull();
124
+ expect(screen.queryByPlaceholderText("Type your email")).toBeNull();
125
+ expect(screen.queryByText("Login")).toBeNull();
126
+ expect(screen.getAllByRole("button")).toHaveLength(1);
127
+ expect(handleGriddoId).not.toHaveBeenCalled();
128
+ });
129
+
130
+ it("la pantalla de Comillas es idéntica con y sin GriddoIdEnabled", () => {
131
+ const { container: withFlag } = renderLoginContainer({ SSOActivated: true, GriddoIdEnabled: true });
132
+ const { container: withoutFlag } = renderLoginContainer({ SSOActivated: true, GriddoIdEnabled: false });
133
+
134
+ expect(withFlag.innerHTML).toBe(withoutFlag.innerHTML);
135
+ });
136
+
137
+ it("con solo SSOActivated (Comillas) la pantalla es la de hoy: sin formulario, sin botón de Griddo ni separador", () => {
138
+ renderLogin({ SSOActivated: true });
139
+
140
+ expect(screen.getByRole("button", { name: /Microsoft ID/ })).toBeInTheDocument();
141
+ expect(screen.queryByText("Entrar con Griddo")).toBeNull();
142
+ expect(screen.queryByText("o")).toBeNull();
143
+ expect(screen.queryByPlaceholderText("Type your email")).toBeNull();
144
+ });
145
+
146
+ it("el botón navega una sola vez aunque se pulse dos veces seguidas", () => {
147
+ const { handleGriddoId } = renderLogin({ GriddoIdEnabled: true });
148
+ const button = screen.getByRole("button", { name: "Entrar con Griddo" });
149
+
150
+ fireEvent.click(button);
151
+ fireEvent.click(button);
152
+
153
+ expect(handleGriddoId).toHaveBeenCalledTimes(1);
154
+ });
155
+
156
+ it("el botón de Microsoft sigue llamando a handleSSO", () => {
157
+ const { handleSSO } = renderLogin({ SSOActivated: true });
158
+
159
+ fireEvent.click(screen.getByRole("button", { name: /Microsoft ID/ }));
160
+
161
+ expect(handleSSO).toHaveBeenCalledTimes(1);
162
+ });
163
+
164
+ it.each([
165
+ ["solo Comillas", { SSOActivated: true }],
166
+ ["Comillas y Griddo ID", { SSOActivated: true, GriddoIdEnabled: true }],
167
+ ])("%s: muestra el error del SSO de Comillas una sola vez", (_name, flags) => {
168
+ renderLogin(flags, { errorSSO: "Error de Comillas" });
169
+
170
+ expect(screen.getAllByText("Error de Comillas")).toHaveLength(1);
171
+ });
172
+
173
+ it("con Comillas la pantalla es la de siempre aunque se pase handleGriddoId: sin formulario, sin botón ni separador", () => {
174
+ renderLogin({ SSOActivated: true, GriddoIdEnabled: false });
175
+
176
+ expect(screen.queryByPlaceholderText("Type your email")).toBeNull();
177
+ expect(screen.queryByText("Login")).toBeNull();
178
+ expect(screen.queryByRole("button", { name: "Entrar con Griddo" })).toBeNull();
179
+ expect(screen.queryByText("o")).toBeNull();
180
+ expect(screen.getByText(/Welcome/)).toBeInTheDocument();
181
+ expect(screen.getAllByRole("button")).toHaveLength(1);
182
+ });
183
+
184
+ it.each([
185
+ ["en-US", "Sign in with Griddo", "or"],
186
+ ["es-ES", "Entrar con Griddo", "o"],
187
+ ["fr-FR", "Entrar con Griddo", "o"],
188
+ ])("idioma %s", (language, button, or) => {
189
+ setLanguage(language);
190
+ renderLogin({ GriddoIdEnabled: true });
191
+
192
+ expect(screen.getByRole("button", { name: button })).toBeInTheDocument();
193
+ expect(screen.getByText(or)).toBeInTheDocument();
194
+ });
195
+ });