@griddo/ax 12.15.1-astro-rc.0 → 12.17.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 (93) hide show
  1. package/README.md +1 -0
  2. package/config/__tests__/getCSSModuleLocalIdent.test.js +30 -0
  3. package/config/griddo-config/index.js +3 -2
  4. package/config/webpack/getCSSModuleLocalIdent.js +10 -0
  5. package/config/webpack.config.js +1 -1
  6. package/package.json +8 -6
  7. package/public/img/logos/logoGriddoDxp.svg +22 -0
  8. package/public/img/logos/logoGriddoG.svg +10 -0
  9. package/src/GlobalStore.tsx +32 -25
  10. package/src/__tests__/GlobalStore.session.test.tsx +98 -0
  11. package/src/__tests__/api/global.test.ts +64 -0
  12. package/src/__tests__/api/session.test.ts +311 -0
  13. package/src/__tests__/api/sessionRenewal.test.ts +705 -0
  14. package/src/__tests__/api/utils.test.ts +373 -0
  15. package/src/__tests__/components/Fields/FileField/FileField.test.tsx +33 -6
  16. package/src/__tests__/components/Fields/TranslateButton/TranslateButton.test.tsx +121 -4
  17. package/src/__tests__/components/FieldsBehavior/FieldsBehavior.test.tsx +5 -3
  18. package/src/__tests__/components/Login/BrandPalette.test.tsx +145 -0
  19. package/src/__tests__/components/Login/Login.test.tsx +2 -33
  20. package/src/__tests__/components/Login/LoginCollapsible.test.tsx +271 -0
  21. package/src/__tests__/components/Login/LoginDropdownCard.test.tsx +311 -0
  22. package/src/__tests__/components/Login/LoginFooter.test.tsx +128 -0
  23. package/src/__tests__/components/Login/LoginGriddoId.test.tsx +213 -0
  24. package/src/__tests__/components/Login/LoginInlineError.test.tsx +116 -0
  25. package/src/__tests__/components/Login/RecoveryModal/RecoveryModal.test.tsx +3 -4
  26. package/src/__tests__/components/SsoDenied/SsoDenied.test.tsx +86 -0
  27. package/src/__tests__/config/webpackAliases.test.ts +18 -0
  28. package/src/__tests__/containers/App/reducer.griddoId.test.ts +18 -0
  29. package/src/__tests__/containers/App/session.test.ts +397 -0
  30. package/src/__tests__/containers/App/signInOut.test.ts +159 -0
  31. package/src/__tests__/helpers/griddoId.test.ts +56 -0
  32. package/src/__tests__/hooks/useShouldBeSaved.test.tsx +78 -0
  33. package/src/__tests__/locales/loginLocale.test.ts +37 -0
  34. package/src/__tests__/modules/App/Routing/NavMenu.test.tsx +54 -0
  35. package/src/__tests__/modules/App/Routing/PrivateRoute.test.tsx +64 -0
  36. package/src/__tests__/modules/App/Routing/Routing.startup.test.tsx +79 -0
  37. package/src/__tests__/modules/Login/Login.test.tsx +169 -0
  38. package/src/__tests__/modules/Login/loginError.uc.test.tsx +294 -0
  39. package/src/__tests__/modules/Login/signInOut.test.tsx +125 -0
  40. package/src/__tests__/modules/Redirects/RedirectPanel/RedirectPanel.test.tsx +9 -0
  41. package/src/__tests__/modules/Redirects/Redirects/Redirects.create.test.tsx +19 -0
  42. package/src/__tests__/modules/Redirects/Redirects/Redirects.edit.test.tsx +19 -0
  43. package/src/__tests__/modules/Redirects/Redirects/Redirects.filter.test.tsx +19 -0
  44. package/src/__tests__/modules/SsoDenied/SsoDenied.test.tsx +30 -0
  45. package/src/__tests__/routes/publicRoutes.test.ts +36 -0
  46. package/src/api/global.tsx +24 -1
  47. package/src/api/session.tsx +197 -0
  48. package/src/api/sessionRenewal.tsx +114 -0
  49. package/src/api/utils.tsx +22 -12
  50. package/src/{helpers/categoryColumns.tsx → components/CategoryCell/buildCategoryColumns.tsx} +3 -2
  51. package/src/components/Circle/index.tsx +1 -1
  52. package/src/components/Circle/style.tsx +4 -2
  53. package/src/components/ErrorPage/index.tsx +1 -1
  54. package/src/components/ErrorPage/style.tsx +11 -9
  55. package/src/components/ErrorToast/index.tsx +2 -0
  56. package/src/components/Fields/TranslateButton/index.tsx +4 -9
  57. package/src/{helpers/fields.tsx → components/FieldsBehavior/getFieldByPath.tsx} +1 -1
  58. package/src/components/FieldsBehavior/index.tsx +3 -1
  59. package/src/components/Login/LoginFooter/index.tsx +16 -0
  60. package/src/components/Login/LoginFooter/style.tsx +17 -0
  61. package/src/components/Login/LoginForm/index.tsx +147 -79
  62. package/src/components/Login/LoginForm/style.tsx +147 -24
  63. package/src/components/Login/LoginGriddoId/index.tsx +56 -0
  64. package/src/components/Login/LoginGriddoId/style.tsx +35 -0
  65. package/src/components/Login/LoginSSO/index.tsx +4 -7
  66. package/src/components/Login/LoginSSO/style.tsx +10 -26
  67. package/src/components/Login/LoginSlider/style.tsx +5 -5
  68. package/src/components/Login/index.tsx +35 -6
  69. package/src/components/Login/style.tsx +40 -24
  70. package/src/components/Notification/index.tsx +3 -1
  71. package/src/components/SsoDenied/index.tsx +46 -0
  72. package/src/components/SsoDenied/style.tsx +37 -0
  73. package/src/components/index.tsx +11 -7
  74. package/src/containers/App/actions.tsx +114 -6
  75. package/src/containers/App/interfaces.tsx +2 -2
  76. package/src/containers/App/reducer.tsx +9 -0
  77. package/src/containers/Users/actions.tsx +28 -24
  78. package/src/helpers/griddoId.ts +28 -0
  79. package/src/helpers/index.tsx +4 -5
  80. package/src/hooks/forms.tsx +8 -5
  81. package/src/locales/en-US.ts +13 -0
  82. package/src/locales/es-ES.ts +13 -0
  83. package/src/locales/index.ts +9 -1
  84. package/src/modules/App/Routing/NavMenu/index.tsx +4 -4
  85. package/src/modules/Content/PageItem/index.tsx +6 -8
  86. package/src/modules/Login/index.tsx +33 -14
  87. package/src/modules/SsoDenied/index.tsx +9 -0
  88. package/src/modules/StructuredData/StructuredDataList/GlobalPageItem/index.tsx +6 -8
  89. package/src/modules/StructuredData/StructuredDataList/StructuredDataItem/index.tsx +9 -11
  90. package/src/modules/Users/UserEdit/index.tsx +9 -2
  91. package/src/routes/publicRoutes.tsx +3 -0
  92. package/src/themes/brandPalette.ts +16 -0
  93. package/public/img/logos/logoSQY.svg +0 -3
@@ -0,0 +1,159 @@
1
+ import { global, languages } from "@ax/api";
2
+ import { appActions } from "@ax/containers/App";
3
+ import { SET_GLOBAL_SETTINGS, SET_TOKEN } from "@ax/containers/App/constants";
4
+ import { usersActions } from "@ax/containers/Users";
5
+ import { SET_USERS } from "@ax/containers/Users/constants";
6
+
7
+ import { createMemoryHistory } from "history";
8
+
9
+ import { getSession, resetSessionState, setSession } from "../../../api/session";
10
+ import { GlobalStore } from "../../../GlobalStore";
11
+ import history from "../../../routes/history";
12
+
13
+ // Trazabilidad de UC-AX-sign-in-out (AC1, AC2, AC3, AC5) sobre el store real de la app: las acciones
14
+ // se despachan contra `GlobalStore` y se asierta el estado resultante, no las acciones sueltas.
15
+
16
+ const bootstrap = async () => {
17
+ const { store, persistor } = new GlobalStore().configureStore(createMemoryHistory() as never);
18
+
19
+ await vi.waitFor(() => expect(persistor.getState().bootstrapped).toBe(true));
20
+
21
+ return store;
22
+ };
23
+
24
+ beforeEach(() => {
25
+ localStorage.clear();
26
+ resetSessionState();
27
+ });
28
+
29
+ describe("[UC-AX-sign-in-out] iniciar sesión", () => {
30
+ const mockOkLogin = () => {
31
+ vi.spyOn(global, "login").mockResolvedValue({
32
+ status: 200,
33
+ data: { id: 7, token: "jwt", refreshToken: "r1" },
34
+ } as never);
35
+ vi.spyOn(languages, "getLanguages").mockResolvedValue({
36
+ status: 200,
37
+ data: { items: [{ id: 1, locale: "es" }] },
38
+ } as never);
39
+
40
+ return vi.spyOn(usersActions, "getUser").mockReturnValue((async () => undefined) as never);
41
+ };
42
+
43
+ it("AC1 · login válido: guarda el token, carga idiomas y usuario, marca sessionStartedAt y devuelve true", async () => {
44
+ const getUser = mockOkLogin();
45
+ const store = await bootstrap();
46
+ const before = Date.now();
47
+
48
+ const result = await store.dispatch(appActions.login({ email: "a@b.c", password: "x" }) as never);
49
+ const { app } = store.getState();
50
+
51
+ expect(result).toBe(true);
52
+ expect(app.token).toBe("jwt");
53
+ expect(getSession()).toMatchObject({ token: "jwt", refreshToken: "r1" });
54
+ expect(app.globalLangs).toEqual([{ id: 1, locale: "es" }]);
55
+ expect(getUser).toHaveBeenCalledWith(7, "jwt", false);
56
+ expect(new Date(app.sessionStartedAt as never).getTime()).toBeGreaterThanOrEqual(before);
57
+ expect(app.hasAnimation).toBe(true);
58
+ });
59
+
60
+ it("AC2 · credenciales inválidas (403): no guarda token, muestra «Lost your password?» y devuelve false", async () => {
61
+ vi.spyOn(global, "login").mockResolvedValue({
62
+ status: 403,
63
+ data: { code: 403, message: "Bad credentials" },
64
+ } as never);
65
+ const store = await bootstrap();
66
+
67
+ // el persist diferido de un store anterior puede reescribir la sesión: se parte de limpio
68
+ localStorage.clear();
69
+ resetSessionState();
70
+ const result = await store.dispatch(appActions.login({ email: "a@b.c", password: "mala" }) as never);
71
+ const { app } = store.getState();
72
+
73
+ expect(result).toBe(false);
74
+ expect(app.token).toBe("");
75
+ expect(getSession()).toBeNull();
76
+ expect(app.error).toMatchObject({ code: 403, text: "Bad credentials", btnText: "Lost your password?" });
77
+ expect(app.isLoggingIn).toBe(false);
78
+ });
79
+
80
+ it("AC3 · «Remember me» guarda localStorage.user = { token }", async () => {
81
+ mockOkLogin();
82
+ const store = await bootstrap();
83
+
84
+ await store.dispatch(appActions.login({ email: "a@b.c", password: "x", rememberMe: true }) as never);
85
+
86
+ expect(JSON.parse(localStorage.getItem("user") as string)).toEqual({ token: "jwt" });
87
+ });
88
+
89
+ it("AC3 (borde) · sin «Remember me» no se persiste el token", async () => {
90
+ mockOkLogin();
91
+ const store = await bootstrap();
92
+
93
+ await store.dispatch(appActions.login({ email: "a@b.c", password: "x", rememberMe: false }) as never);
94
+
95
+ expect(localStorage.getItem("user")).toBeNull();
96
+ });
97
+ });
98
+
99
+ describe("[UC-AX-sign-in-out] cerrar sesión", () => {
100
+ const URL_OK = "https://api.uni.es/sso/logout";
101
+ let assign: ReturnType<typeof vi.fn>;
102
+ let push: ReturnType<typeof vi.spyOn>;
103
+
104
+ beforeEach(() => {
105
+ assign = vi.fn();
106
+ vi.stubGlobal("location", { ...window.location, assign });
107
+ push = vi.spyOn(history, "push").mockImplementation(() => undefined);
108
+ });
109
+
110
+ afterEach(() => {
111
+ vi.unstubAllGlobals();
112
+ });
113
+
114
+ /** Store con sesión iniciada, Griddo ID activo y algo en los slices que el logout debe vaciar. */
115
+ const loggedInStore = async () => {
116
+ setSession("jwt", "r1");
117
+ localStorage.setItem("sitesConfig", "keep");
118
+ localStorage.setItem("other", "drop");
119
+ const store = await bootstrap();
120
+
121
+ store.dispatch({ type: SET_TOKEN, payload: { token: "jwt", refreshToken: "r1", sessionUpdatedAt: 1 } });
122
+ store.dispatch({ type: SET_GLOBAL_SETTINGS, payload: { globalSettings: { GriddoIdEnabled: true } } });
123
+ store.dispatch({ type: SET_USERS, payload: { users: [{ id: 1 }] } });
124
+
125
+ return store;
126
+ };
127
+
128
+ it("AC5 · logout: limpia localStorage salvo sitesConfig, vacía los slices salvo router/app, token vacío y cierra la sesión central", async () => {
129
+ const logoutApi = vi
130
+ .spyOn(global, "logout")
131
+ .mockResolvedValue({ status: 200, data: { endSessionUrl: URL_OK } } as never);
132
+ const store = await loggedInStore();
133
+ const router = store.getState().router;
134
+
135
+ await store.dispatch(appActions.logoutAndEndCentralSession() as never);
136
+ const state = store.getState();
137
+
138
+ expect(logoutApi).toHaveBeenCalledWith({ token: "jwt", refreshToken: "r1" });
139
+ expect(assign).toHaveBeenCalledExactlyOnceWith(URL_OK);
140
+ expect(localStorage.getItem("other")).toBeNull();
141
+ expect(localStorage.getItem("sitesConfig")).toBe("keep");
142
+ expect(state.app.token).toBe("");
143
+ expect(state.users.users).toEqual([]);
144
+ expect(state.router).toBe(router);
145
+ });
146
+
147
+ it("AC5 (borde) · si el cierre de la sesión central falla, el estado local queda limpio y se llega a /logout", async () => {
148
+ vi.spyOn(global, "logout").mockRejectedValue(new Error("boom"));
149
+ const store = await loggedInStore();
150
+
151
+ await store.dispatch(appActions.logoutAndEndCentralSession() as never);
152
+
153
+ expect(store.getState().app.token).toBe("");
154
+ expect(getSession()).toBeNull();
155
+ expect(localStorage.getItem("other")).toBeNull();
156
+ expect(assign).not.toHaveBeenCalled();
157
+ expect(push).toHaveBeenCalledWith("/logout", undefined);
158
+ });
159
+ });
@@ -0,0 +1,56 @@
1
+ import { buildGriddoIdStartUrl, MAX_LOGIN_HINT_LENGTH } from "@ax/helpers";
2
+
3
+ const API = "https://api.uni.es";
4
+ const START = `${API}/sso/start`;
5
+
6
+ const emailOfLength = (length: number) => `${"a".repeat(length - "@uni.es".length)}@uni.es`;
7
+
8
+ describe("buildGriddoIdStartUrl", () => {
9
+ it.each([
10
+ ["ana@uni.es", `${START}?login_hint=ana%40uni.es`],
11
+ [" ana@uni.es ", `${START}?login_hint=ana%40uni.es`],
12
+ ["\t\nana@uni.es\r\n", `${START}?login_hint=ana%40uni.es`],
13
+ ["Ana@UNI.es", `${START}?login_hint=Ana%40UNI.es`],
14
+ ["ana @uni.es", `${START}?login_hint=ana%20%40uni.es`],
15
+ ["ana+x@uni.es", `${START}?login_hint=ana%2Bx%40uni.es`],
16
+ ["a&b=c@uni.es", `${START}?login_hint=a%26b%3Dc%40uni.es`],
17
+ ["ñandú@uni.es", `${START}?login_hint=%C3%B1and%C3%BA%40uni.es`],
18
+ ])("con %j navega con el hint codificado", (typed, expected) => {
19
+ expect(buildGriddoIdStartUrl(API, typed)).toBe(expected);
20
+ });
21
+
22
+ it("el tope es 254 caracteres", () => {
23
+ expect(MAX_LOGIN_HINT_LENGTH).toBe(254);
24
+ });
25
+
26
+ it("254 caracteres con @ llevan el hint", () => {
27
+ const email = emailOfLength(254);
28
+
29
+ expect(buildGriddoIdStartUrl(API, email)).toBe(`${START}?login_hint=${encodeURIComponent(email)}`);
30
+ });
31
+
32
+ it("254 caracteres con espacios en los extremos llevan el hint recortado", () => {
33
+ const email = emailOfLength(254);
34
+
35
+ expect(buildGriddoIdStartUrl(API, ` ${email} `)).toBe(`${START}?login_hint=${encodeURIComponent(email)}`);
36
+ });
37
+
38
+ it.each([
39
+ ["vacío", ""],
40
+ ["solo espacios", " "],
41
+ ["sin arroba", "ana"],
42
+ ["255 caracteres con @", emailOfLength(255)],
43
+ ["un texto de 20 KB con @", `${"a".repeat(20 * 1024)}@uni.es`],
44
+ ["un sustituto suelto", "\uD800@uni.es"],
45
+ ])("con %s navega a /sso/start sin query", (_case, typed) => {
46
+ expect(buildGriddoIdStartUrl(API, typed)).toBe(START);
47
+ });
48
+
49
+ it("no cambia mayúsculas ni espacios interiores (la normalización es de la app de login)", () => {
50
+ expect(buildGriddoIdStartUrl(API, "A B@UNI.es")).toBe(`${START}?login_hint=A%20%20B%40UNI.es`);
51
+ });
52
+
53
+ it("con una URL de API sin definir no inventa un host", () => {
54
+ expect(buildGriddoIdStartUrl("", "ana@uni.es")).toBe("/sso/start?login_hint=ana%40uni.es");
55
+ });
56
+ });
@@ -0,0 +1,78 @@
1
+ import { useState } from "react";
2
+
3
+ import { act, renderHook } from "@testing-library/react";
4
+
5
+ import "@testing-library/jest-dom";
6
+
7
+ import { useShouldBeSaved } from "@ax/hooks";
8
+
9
+ type Form = Record<string, unknown>;
10
+
11
+ const setup = (initial: Form) =>
12
+ renderHook(() => {
13
+ const [form, setForm] = useState<Form>(initial);
14
+ const saved = useShouldBeSaved(form);
15
+
16
+ return { form, setForm, ...saved };
17
+ });
18
+
19
+ const A: Form = { id: 1, name: "Ana", sites: [] };
20
+ const B: Form = { id: 1, name: "Ana", sites: [10] }; // lo que edita el usuario
21
+ const C: Form = { id: 1, name: "Ana", sites: [10], modifiedBy: "server" }; // lo que devuelve el servidor tras guardar
22
+
23
+ describe("useShouldBeSaved", () => {
24
+ it("marca dirty al editar y limpio al volver al original", () => {
25
+ const { result } = setup(A);
26
+
27
+ act(() => result.current.setForm(B));
28
+ expect(result.current.isDirty).toBe(true);
29
+
30
+ act(() => result.current.setForm(A));
31
+ expect(result.current.isDirty).toBe(false);
32
+ });
33
+
34
+ it("setIsDirty(false) sin base toma el form de ese render como referencia", () => {
35
+ const { result } = setup(A);
36
+
37
+ act(() => result.current.setForm(B));
38
+ act(() => result.current.setIsDirty(false));
39
+
40
+ expect(result.current.isDirty).toBe(false);
41
+ });
42
+
43
+ it("tras guardar, si el servidor devuelve el form ya sincronizado y se fija como base, queda limpio (respuesta ANTES del setIsDirty)", () => {
44
+ const { result } = setup(A);
45
+
46
+ act(() => result.current.setForm(B));
47
+ const staleSetIsDirty = result.current.setIsDirty; // el del render del clic en guardar
48
+
49
+ act(() => result.current.setForm(C)); // llega la respuesta y el form se sincroniza
50
+ act(() => staleSetIsDirty(false, C));
51
+
52
+ expect(result.current.isDirty).toBe(false);
53
+ });
54
+
55
+ it("tras guardar, la respuesta DESPUÉS del setIsDirty tampoco deja el form sucio si la base es la del servidor", () => {
56
+ const { result } = setup(A);
57
+
58
+ act(() => result.current.setForm(B));
59
+ const staleSetIsDirty = result.current.setIsDirty;
60
+
61
+ act(() => staleSetIsDirty(false, C)); // se guarda y se fija ya la base que traerá el servidor
62
+ act(() => result.current.setForm(C)); // la respuesta llega después
63
+
64
+ expect(result.current.isDirty).toBe(false);
65
+ });
66
+
67
+ it("sin pasar la base del servidor, ese orden deja el botón sucio (el bug que se corrige)", () => {
68
+ const { result } = setup(A);
69
+
70
+ act(() => result.current.setForm(B));
71
+ const staleSetIsDirty = result.current.setIsDirty;
72
+
73
+ act(() => staleSetIsDirty(false)); // base = B (form viejo del cierre)
74
+ act(() => result.current.setForm(C)); // el servidor devuelve C ≠ B
75
+
76
+ expect(result.current.isDirty).toBe(true);
77
+ });
78
+ });
@@ -0,0 +1,37 @@
1
+ import { getLoginLocale, LOCALE } from "@ax/locales";
2
+
3
+ describe("getLoginLocale", () => {
4
+ it("devuelve el login del idioma fijo de AX (inglés), igual que LOCALE", () => {
5
+ expect(getLoginLocale()).toBe(LOCALE.login);
6
+ expect(getLoginLocale().griddoIdButton).toBe("Sign in with Griddo");
7
+ });
8
+
9
+ it.each(["es-ES", "es", "fr-FR", "en-GB", ""])("no depende del idioma del navegador (%j)", (language) => {
10
+ vi.spyOn(window.navigator, "language", "get").mockReturnValue(language);
11
+
12
+ expect(getLoginLocale().griddoIdButton).toBe("Sign in with Griddo");
13
+ expect(getLoginLocale().emailPasswordToggle).toBe("Login with email and password");
14
+ expect(getLoginLocale().submit).toBe("Login");
15
+ });
16
+
17
+ it("sin idioma del navegador sigue en inglés", () => {
18
+ vi.spyOn(window.navigator, "language", "get").mockReturnValue(undefined as unknown as string);
19
+
20
+ expect(getLoginLocale().welcome).toBe("Welcome");
21
+ });
22
+
23
+ it("textos fijos de acceso denegado", () => {
24
+ expect(getLoginLocale().deniedTitle).toBe("You don't have access to this instance");
25
+ expect(getLoginLocale().switchAccount).toBe("Sign in with another account");
26
+ });
27
+
28
+ it("textos del botón de envío", () => {
29
+ expect(getLoginLocale()).toMatchObject({ submit: "Login", submitting: "Sending" });
30
+ });
31
+
32
+ it("ya no hay separador «o» ni texto de «Acceso de administración»", () => {
33
+ for (const key of ["or", "emailPasswordHint", "adminAccess"]) {
34
+ expect(getLoginLocale()).not.toHaveProperty(key);
35
+ }
36
+ });
37
+ });
@@ -0,0 +1,54 @@
1
+ import { Provider } from "react-redux";
2
+ import { Router } from "react-router-dom";
3
+
4
+ import { cleanup, fireEvent, render, screen } from "@testing-library/react";
5
+ import configureStore from "redux-mock-store";
6
+ import { ThemeProvider } from "styled-components";
7
+ import "@testing-library/jest-dom";
8
+
9
+ import { appInitialState } from "@ax/containers/App/reducer";
10
+ import { parseTheme } from "@ax/helpers";
11
+ import NavMenu from "@ax/modules/App/Routing/NavMenu";
12
+ import history from "@ax/routes/history";
13
+ import globalTheme from "@ax/themes/theme.json";
14
+
15
+ vi.mock("@ax/containers/App", async (importOriginal) => {
16
+ const original = await importOriginal<typeof import("@ax/containers/App")>();
17
+
18
+ return {
19
+ ...original,
20
+ appActions: {
21
+ ...original.appActions,
22
+ logoutAndEndCentralSession: () => ({ type: "test/logoutAndEndCentralSession" }),
23
+ logoutAndNavigate: () => ({ type: "test/logoutAndNavigate" }),
24
+ setHistoryPush: () => ({ type: "test/setHistoryPush" }),
25
+ },
26
+ };
27
+ });
28
+
29
+ afterEach(cleanup);
30
+
31
+ describe("NavMenu: botón «Logout»", () => {
32
+ it("usa el cierre completo (con la sesión central de auth.griddo.io), no el solo local", () => {
33
+ const store = configureStore([])({
34
+ app: { ...appInitialState, lang: { locale: "es-ES", id: 1 }, globalSettings: appInitialState.globalSettings },
35
+ structuredData: { categories: { global: [], site: [] }, structuredData: { global: [], site: [] } },
36
+ sites: { currentSiteInfo: null, currentSiteLanguages: [] },
37
+ users: { currentUser: null },
38
+ });
39
+
40
+ render(
41
+ <Provider store={store}>
42
+ <Router history={history}>
43
+ <ThemeProvider theme={parseTheme(globalTheme)}>
44
+ <NavMenu />
45
+ </ThemeProvider>
46
+ </Router>
47
+ </Provider>,
48
+ );
49
+
50
+ fireEvent.click(screen.getAllByText("Logout")[0]);
51
+
52
+ expect(store.getActions()).toEqual([{ type: "test/logoutAndEndCentralSession" }]);
53
+ });
54
+ });
@@ -0,0 +1,64 @@
1
+ import { MemoryRouter, Route } from "react-router-dom";
2
+
3
+ import { cleanup, render, screen } from "@testing-library/react";
4
+ import { ThemeProvider } from "styled-components";
5
+ import "@testing-library/jest-dom";
6
+
7
+ import { parseTheme } from "@ax/helpers";
8
+ import PrivateRoute from "@ax/modules/App/Routing/PrivateRoute";
9
+ import globalTheme from "@ax/themes/theme.json";
10
+ import type { IUser } from "@ax/types";
11
+
12
+ const usePermission = vi.hoisted(() => vi.fn());
13
+
14
+ vi.mock("@ax/hooks", async (importOriginal) => ({
15
+ ...(await importOriginal<typeof import("@ax/hooks")>()),
16
+ usePermission,
17
+ }));
18
+
19
+ afterEach(cleanup);
20
+
21
+ const Private = () => <p>área privada</p>;
22
+ const currentUser = { id: 1 } as IUser;
23
+
24
+ const renderAt = (token: string, allowed: boolean) => {
25
+ usePermission.mockReturnValue(allowed);
26
+
27
+ render(
28
+ <ThemeProvider theme={parseTheme(globalTheme)}>
29
+ <MemoryRouter initialEntries={["/sites"]}>
30
+ <PrivateRoute
31
+ path="/sites"
32
+ component={Private}
33
+ token={token}
34
+ currentUser={currentUser}
35
+ permission="sites.view"
36
+ exact
37
+ />
38
+ <Route path="/login" render={() => <p>pantalla de login</p>} />
39
+ </MemoryRouter>
40
+ </ThemeProvider>,
41
+ );
42
+ };
43
+
44
+ describe("[UC-AX-sign-in-out] PrivateRoute", () => {
45
+ it("AC4 · ruta privada sin token → redirige a /login", () => {
46
+ renderAt("", true);
47
+
48
+ expect(screen.getByText("pantalla de login")).toBeInTheDocument();
49
+ expect(screen.queryByText("área privada")).toBeNull();
50
+ });
51
+
52
+ it("AC4 · token pero sin permiso → ErrorPage forbidden", () => {
53
+ renderAt("jwt", false);
54
+
55
+ expect(screen.getByText("Access Denied")).toBeInTheDocument();
56
+ expect(screen.queryByText("área privada")).toBeNull();
57
+ });
58
+
59
+ it("AC4 (borde) · token y permiso → renderiza la ruta", () => {
60
+ renderAt("jwt", true);
61
+
62
+ expect(screen.getByText("área privada")).toBeInTheDocument();
63
+ });
64
+ });
@@ -0,0 +1,79 @@
1
+ import { Provider } from "react-redux";
2
+ import { MemoryRouter } from "react-router-dom";
3
+
4
+ import { appInitialState } from "@ax/containers/App/reducer";
5
+ import { parseTheme } from "@ax/helpers";
6
+ import Routing from "@ax/modules/App/Routing";
7
+ import globalTheme from "@ax/themes/theme.json";
8
+
9
+ import { cleanup, render } from "@testing-library/react";
10
+ import configureStore from "redux-mock-store";
11
+ import { ThemeProvider } from "styled-components";
12
+
13
+ const actions = vi.hoisted(() => ({ setHistoryPush: vi.fn(), logout: vi.fn() }));
14
+
15
+ vi.mock("@ax/routes", () => ({ publicRoutes: [], privateRoutes: [], routes: [] }));
16
+ vi.mock("@ax/modules/App/Routing/NavMenu", () => ({ default: () => null }));
17
+ vi.mock("@ax/guards", () => ({ ErrorGuard: () => null }));
18
+ vi.mock("@ax/containers/App", async (importOriginal) => {
19
+ const original = await importOriginal<typeof import("@ax/containers/App")>();
20
+
21
+ return {
22
+ ...original,
23
+ appActions: {
24
+ ...original.appActions,
25
+ setHistoryPush: (...args: unknown[]) => {
26
+ actions.setHistoryPush(...args);
27
+
28
+ return { type: "test/setHistoryPush" };
29
+ },
30
+ logout: () => {
31
+ actions.logout();
32
+
33
+ return { type: "test/logout" };
34
+ },
35
+ },
36
+ };
37
+ });
38
+
39
+ beforeEach(() => localStorage.clear());
40
+ afterEach(() => {
41
+ cleanup();
42
+ vi.clearAllMocks();
43
+ });
44
+
45
+ const renderAt = (path: string) => {
46
+ const store = configureStore([])({
47
+ router: { location: { pathname: path } },
48
+ app: { ...appInitialState, token: "" },
49
+ users: { currentUser: null },
50
+ });
51
+
52
+ render(
53
+ <Provider store={store}>
54
+ <MemoryRouter initialEntries={[path]}>
55
+ <ThemeProvider theme={parseTheme(globalTheme)}>
56
+ <Routing />
57
+ </ThemeProvider>
58
+ </MemoryRouter>
59
+ </Provider>,
60
+ );
61
+ };
62
+
63
+ describe("[UC-AX-sign-in-out] arranque", () => {
64
+ it("AC3 · con localStorage.user guardado, arrancar en /login redirige a /sites", () => {
65
+ localStorage.setItem("user", JSON.stringify({ token: "jwt" }));
66
+
67
+ renderAt("/login");
68
+
69
+ expect(actions.setHistoryPush).toHaveBeenCalledExactlyOnceWith("/sites", false);
70
+ expect(actions.logout).not.toHaveBeenCalled();
71
+ });
72
+
73
+ it("AC3 (borde) · sin localStorage.user, /login limpia la sesión y no redirige", () => {
74
+ renderAt("/login");
75
+
76
+ expect(actions.logout).toHaveBeenCalledTimes(1);
77
+ expect(actions.setHistoryPush).not.toHaveBeenCalled();
78
+ });
79
+ });