@griddo/ax 12.15.0-beta.1 → 12.15.0

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 (75) hide show
  1. package/README.md +0 -1
  2. package/package.json +4 -7
  3. package/src/GlobalStore.tsx +25 -32
  4. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +6 -33
  5. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +3 -5
  6. package/src/__tests__/modules/GlobalSettings/Llms/Llms.uc.test.tsx +2861 -0
  7. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +0 -19
  8. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +0 -19
  9. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +0 -19
  10. package/src/api/domains.tsx +98 -2
  11. package/src/api/global.tsx +1 -24
  12. package/src/api/utils.tsx +12 -22
  13. package/src/components/FieldsBehavior/index.tsx +1 -3
  14. package/src/components/Login/LoginForm/index.tsx +2 -7
  15. package/src/components/Login/index.tsx +1 -13
  16. package/src/components/index.tsx +7 -11
  17. package/src/containers/App/actions.tsx +5 -110
  18. package/src/containers/App/interfaces.tsx +2 -2
  19. package/src/containers/App/reducer.tsx +0 -9
  20. package/src/containers/Users/actions.tsx +24 -28
  21. package/src/{components/CategoryCell/buildCategoryColumns.tsx → helpers/categoryColumns.tsx} +2 -3
  22. package/src/{components/FieldsBehavior/getFieldByPath.tsx → helpers/fields.tsx} +1 -1
  23. package/src/helpers/index.tsx +5 -4
  24. package/src/locales/en-US.ts +0 -7
  25. package/src/locales/es-ES.ts +0 -7
  26. package/src/locales/index.ts +0 -10
  27. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  28. package/src/modules/Content/PageItem/index.tsx +8 -6
  29. package/src/modules/GlobalSettings/Llms/AutomaticSelection/index.tsx +317 -0
  30. package/src/modules/GlobalSettings/Llms/DomainList/index.tsx +65 -0
  31. package/src/modules/GlobalSettings/Llms/IndexModelEditor/index.tsx +325 -0
  32. package/src/modules/GlobalSettings/Llms/MirrorExample/index.tsx +61 -0
  33. package/src/modules/GlobalSettings/Llms/MirrorOptions/index.tsx +82 -0
  34. package/src/modules/GlobalSettings/Llms/Outline/index.tsx +183 -0
  35. package/src/modules/GlobalSettings/Llms/PagePicker/index.tsx +105 -0
  36. package/src/modules/GlobalSettings/Llms/Preview/index.tsx +65 -0
  37. package/src/modules/GlobalSettings/Llms/ResolvedPages/index.tsx +191 -0
  38. package/src/modules/GlobalSettings/Llms/SectionEditor/index.tsx +262 -0
  39. package/src/modules/GlobalSettings/Llms/atoms.tsx +37 -0
  40. package/src/modules/GlobalSettings/Llms/index.tsx +383 -0
  41. package/src/modules/GlobalSettings/Llms/style.tsx +541 -0
  42. package/src/modules/GlobalSettings/Llms/utils.tsx +307 -0
  43. package/src/modules/GlobalSettings/index.tsx +7 -0
  44. package/src/modules/Login/index.tsx +2 -12
  45. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +8 -6
  46. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +11 -9
  47. package/src/routes/multisite.tsx +8 -1
  48. package/src/routes/publicRoutes.tsx +0 -3
  49. package/src/schemas/pages/GlobalPage.ts +2 -2
  50. package/src/schemas/pages/Page.ts +2 -2
  51. package/src/types/index.tsx +80 -12
  52. package/src/types/llms.tsx +315 -0
  53. package/src/__tests__/GlobalStore.session.test.tsx +0 -98
  54. package/src/__tests__/api/global.test.ts +0 -64
  55. package/src/__tests__/api/session.test.ts +0 -311
  56. package/src/__tests__/api/sessionRenewal.test.ts +0 -705
  57. package/src/__tests__/api/utils.test.ts +0 -373
  58. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +0 -195
  59. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +0 -86
  60. package/src/__tests__/containers/App/reducer.griddoId.test.ts +0 -18
  61. package/src/__tests__/containers/App/session.test.ts +0 -397
  62. package/src/__tests__/helpers/griddoId.test.ts +0 -56
  63. package/src/__tests__/locales/loginLocale.test.ts +0 -52
  64. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +0 -54
  65. package/src/__tests__/modules/Login/Login.test.tsx +0 -151
  66. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +0 -30
  67. package/src/__tests__/routes/publicRoutes.test.ts +0 -36
  68. package/src/api/session.tsx +0 -197
  69. package/src/api/sessionRenewal.tsx +0 -114
  70. package/src/components/Login/LoginGriddoId/index.tsx +0 -46
  71. package/src/components/Login/LoginGriddoId/style.tsx +0 -35
  72. package/src/components/SsoDenied/index.tsx +0 -46
  73. package/src/components/SsoDenied/style.tsx +0 -37
  74. package/src/helpers/griddoId.ts +0 -28
  75. package/src/modules/SsoDenied/index.tsx +0 -9
@@ -1,373 +0,0 @@
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,195 +0,0 @@
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
- });
@@ -1,86 +0,0 @@
1
- import { cleanup, render, screen } from "@testing-library/react";
2
- import { ThemeProvider } from "styled-components";
3
- import "@testing-library/jest-dom";
4
-
5
- import SsoDenied from "@ax/components/SsoDenied";
6
- import { parseTheme } from "@ax/helpers";
7
- import globalTheme from "@ax/themes/theme.json";
8
-
9
- afterEach(() => {
10
- cleanup();
11
- window.history.pushState({}, "", "/");
12
- });
13
-
14
- const SWITCH_URL = "https://api.uni.es/sso/switch-account";
15
-
16
- const renderS6 = () =>
17
- render(
18
- <ThemeProvider theme={parseTheme(globalTheme)}>
19
- <SsoDenied switchAccountUrl={SWITCH_URL} />
20
- </ThemeProvider>,
21
- );
22
-
23
- const setLanguage = (language: string) => vi.spyOn(window.navigator, "language", "get").mockReturnValue(language);
24
-
25
- describe("S6 — acceso denegado", () => {
26
- beforeEach(() => setLanguage("es-ES"));
27
-
28
- it("dice «No tienes acceso a esta instancia» y no menciona motivo ni email", () => {
29
- const { container } = renderS6();
30
-
31
- expect(screen.getByRole("heading", { name: "No tienes acceso a esta instancia" })).toBeInTheDocument();
32
- expect(container.textContent).not.toMatch(/motivo|reason|@/i);
33
- });
34
-
35
- it("«Entrar con otra cuenta» es un enlace al cambio de cuenta de la API", () => {
36
- renderS6();
37
-
38
- expect(screen.getByRole("link", { name: "Entrar con otra cuenta" })).toHaveAttribute("href", SWITCH_URL);
39
- });
40
-
41
- it("el enlace está subrayado", () => {
42
- renderS6();
43
-
44
- expect(getComputedStyle(screen.getByRole("link", { name: "Entrar con otra cuenta" })).textDecoration).toContain(
45
- "underline",
46
- );
47
- });
48
-
49
- it("el foco va al título al abrirla", () => {
50
- renderS6();
51
-
52
- expect(screen.getByRole("heading")).toHaveFocus();
53
- });
54
-
55
- it("no refleja parámetros de la URL: texto fijo con ?reason=<script> y ?email=x", () => {
56
- window.history.pushState({}, "", "/sso-denied?reason=%3Cscript%3Ealert(1)%3C/script%3E&email=x@y.z");
57
-
58
- const { container } = renderS6();
59
-
60
- expect(container.textContent).not.toContain("<script>");
61
- expect(container.textContent).not.toContain("x@y.z");
62
- expect(container.querySelector("script")).toBeNull();
63
- expect(screen.getByRole("heading", { name: "No tienes acceso a esta instancia" })).toBeInTheDocument();
64
- });
65
-
66
- it("abierta por URL directa muestra la misma pantalla", () => {
67
- window.history.pushState({}, "", "/sso-denied");
68
-
69
- renderS6();
70
-
71
- expect(screen.getByRole("heading", { name: "No tienes acceso a esta instancia" })).toBeInTheDocument();
72
- expect(screen.getByRole("link", { name: "Entrar con otra cuenta" })).toBeInTheDocument();
73
- });
74
-
75
- it.each([
76
- ["en-US", "You don't have access to this instance", "Sign in with another account"],
77
- ["es-ES", "No tienes acceso a esta instancia", "Entrar con otra cuenta"],
78
- ["fr-FR", "No tienes acceso a esta instancia", "Entrar con otra cuenta"],
79
- ])("idioma %s", (language, title, link) => {
80
- setLanguage(language);
81
- renderS6();
82
-
83
- expect(screen.getByRole("heading", { name: title })).toBeInTheDocument();
84
- expect(screen.getByRole("link", { name: link })).toBeInTheDocument();
85
- });
86
- });
@@ -1,18 +0,0 @@
1
- import { SET_GLOBAL_SETTINGS } from "@ax/containers/App/constants";
2
- import { appInitialState, appReducer } from "@ax/containers/App/reducer";
3
-
4
- describe("GriddoIdEnabled en los settings de AX", () => {
5
- it("está apagado por defecto: si GET /settings falla se ve el login de siempre", () => {
6
- expect(appInitialState.globalSettings.GriddoIdEnabled).toBe(false);
7
- expect(appInitialState.globalSettings.SSOActivated).toBe(false);
8
- });
9
-
10
- it("el valor de la API llega al estado", () => {
11
- const state = appReducer(appInitialState, {
12
- type: SET_GLOBAL_SETTINGS,
13
- payload: { globalSettings: { ...appInitialState.globalSettings, GriddoIdEnabled: true } },
14
- });
15
-
16
- expect(state.globalSettings.GriddoIdEnabled).toBe(true);
17
- });
18
- });