@asteby/metacore-runtime-react 53.4.1 → 53.6.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.
- package/CHANGELOG.md +12 -0
- package/README.md +73 -0
- package/dist/index.d.ts +2 -0
- package/dist/index.d.ts.map +1 -1
- package/dist/index.js +4 -0
- package/dist/setup/addon-config-surface.d.ts +119 -0
- package/dist/setup/addon-config-surface.d.ts.map +1 -0
- package/dist/setup/addon-config-surface.js +662 -0
- package/dist/setup/connector-blocks-model.d.ts +79 -0
- package/dist/setup/connector-blocks-model.d.ts.map +1 -0
- package/dist/setup/connector-blocks-model.js +96 -0
- package/dist/setup/connector-blocks.d.ts +48 -0
- package/dist/setup/connector-blocks.d.ts.map +1 -0
- package/dist/setup/connector-blocks.js +132 -0
- package/dist/setup/connector-form-model.d.ts +40 -0
- package/dist/setup/connector-form-model.d.ts.map +1 -0
- package/dist/setup/connector-form-model.js +76 -0
- package/dist/setup/flow-model.d.ts +49 -0
- package/dist/setup/flow-model.d.ts.map +1 -0
- package/dist/setup/flow-model.js +124 -0
- package/dist/setup/health-card.d.ts +25 -0
- package/dist/setup/health-card.d.ts.map +1 -0
- package/dist/setup/health-card.js +21 -0
- package/dist/setup/index.d.ts +13 -0
- package/dist/setup/index.d.ts.map +1 -0
- package/dist/setup/index.js +15 -0
- package/dist/setup/messages.d.ts +15 -0
- package/dist/setup/messages.d.ts.map +1 -0
- package/dist/setup/messages.js +320 -0
- package/dist/setup/records-table.d.ts +24 -0
- package/dist/setup/records-table.d.ts.map +1 -0
- package/dist/setup/records-table.js +80 -0
- package/dist/setup/setup-flow.d.ts +30 -0
- package/dist/setup/setup-flow.d.ts.map +1 -0
- package/dist/setup/setup-flow.js +277 -0
- package/dist/setup/setup-form-step.d.ts +20 -0
- package/dist/setup/setup-form-step.d.ts.map +1 -0
- package/dist/setup/setup-form-step.js +173 -0
- package/dist/setup/step-status-badge.d.ts +12 -0
- package/dist/setup/step-status-badge.d.ts.map +1 -0
- package/dist/setup/step-status-badge.js +21 -0
- package/dist/setup/tone.d.ts +8 -0
- package/dist/setup/tone.d.ts.map +1 -0
- package/dist/setup/tone.js +33 -0
- package/dist/setup/types.d.ts +130 -0
- package/dist/setup/types.d.ts.map +1 -0
- package/dist/setup/types.js +1 -0
- package/package.json +9 -5
- package/src/__tests__/addon-config-surface.test.tsx +260 -0
- package/src/__tests__/connector-blocks.test.tsx +302 -0
- package/src/__tests__/setup-components.test.tsx +147 -0
- package/src/__tests__/setup-flow-model.test.ts +117 -0
- package/src/__tests__/setup-flow.test.tsx +424 -0
- package/src/index.ts +29 -0
- package/src/setup/addon-config-surface.tsx +1426 -0
- package/src/setup/connector-blocks-model.ts +163 -0
- package/src/setup/connector-blocks.tsx +341 -0
- package/src/setup/connector-form-model.ts +115 -0
- package/src/setup/flow-model.ts +156 -0
- package/src/setup/health-card.tsx +131 -0
- package/src/setup/index.ts +35 -0
- package/src/setup/messages.ts +334 -0
- package/src/setup/records-table.tsx +186 -0
- package/src/setup/setup-flow.tsx +562 -0
- package/src/setup/setup-form-step.tsx +342 -0
- package/src/setup/step-status-badge.tsx +47 -0
- package/src/setup/tone.ts +44 -0
- package/src/setup/types.ts +147 -0
|
@@ -0,0 +1,302 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
3
|
+
import { QueryClient, QueryClientProvider } from '@tanstack/react-query'
|
|
4
|
+
import { cleanup, fireEvent, render, screen, waitFor, within } from '@testing-library/react'
|
|
5
|
+
|
|
6
|
+
vi.mock('react-i18next', () => {
|
|
7
|
+
const dict: Record<string, string> = {
|
|
8
|
+
'mp.section.connection': 'Conexión',
|
|
9
|
+
'mp.section.advanced': 'Avanzado',
|
|
10
|
+
'mp.section.advanced_help': 'Webhooks y modo de pruebas.',
|
|
11
|
+
'mp.field.token': 'Access token',
|
|
12
|
+
'mp.field.secret': 'Secreto del webhook',
|
|
13
|
+
'mp.block.webhook.title': 'URL de notificaciones',
|
|
14
|
+
'mp.block.webhook.panel': 'Abrir panel de Mercado Pago',
|
|
15
|
+
'mp.block.order.label': 'Crear orden de prueba',
|
|
16
|
+
'mp.block.order.title': 'Prueba de cobro',
|
|
17
|
+
}
|
|
18
|
+
const t = (k: string, o?: { defaultValue?: string }) => dict[k] ?? o?.defaultValue ?? k
|
|
19
|
+
return { useTranslation: () => ({ t, i18n: { language: 'es', exists: () => true } }) }
|
|
20
|
+
})
|
|
21
|
+
|
|
22
|
+
import { ApiProvider } from '../api-context'
|
|
23
|
+
import { AddonConfigSurface, type ConnectorEntry } from '../setup/addon-config-surface'
|
|
24
|
+
import {
|
|
25
|
+
buildWizardSteps,
|
|
26
|
+
hasExplicitTest,
|
|
27
|
+
normalizeBlockResult,
|
|
28
|
+
safeHttpsUrl,
|
|
29
|
+
stepStatus,
|
|
30
|
+
} from '../setup/connector-blocks-model'
|
|
31
|
+
|
|
32
|
+
afterEach(cleanup)
|
|
33
|
+
|
|
34
|
+
const WEBHOOK = 'https://panel.example.com/api/webhooks/0b6f/mercadopago/notifications'
|
|
35
|
+
|
|
36
|
+
describe('connector-blocks-model', () => {
|
|
37
|
+
it('normalizes envelopes without inventing success', () => {
|
|
38
|
+
expect(normalizeBlockResult({ success: true, data: { ok: true, message: 'Listo' } })).toEqual({
|
|
39
|
+
status: 'ok',
|
|
40
|
+
message: 'Listo',
|
|
41
|
+
details: [],
|
|
42
|
+
})
|
|
43
|
+
expect(normalizeBlockResult({ success: false, error: { message: 'sin token' } }).status).toBe('error')
|
|
44
|
+
expect(normalizeBlockResult({ success: true, data: {} }, 'falló')).toEqual({ status: 'error', message: 'falló', details: [] })
|
|
45
|
+
// explicit ok:false beats a status that claims success
|
|
46
|
+
expect(normalizeBlockResult({ data: { ok: false, status: 'ok' } }).status).toBe('error')
|
|
47
|
+
const r = normalizeBlockResult({
|
|
48
|
+
success: true,
|
|
49
|
+
data: { ok: true, status: 'pending', details: [{ key: 'id', label: 'ID', value: 123, kind: 'id' }, { value: {} }] },
|
|
50
|
+
})
|
|
51
|
+
expect(r.status).toBe('pending')
|
|
52
|
+
expect(r.details).toEqual([{ key: 'id', label: 'ID', value: '123', kind: 'id' }])
|
|
53
|
+
})
|
|
54
|
+
|
|
55
|
+
it('only https URLs become links', () => {
|
|
56
|
+
expect(safeHttpsUrl('https://x.example/a')).toBe('https://x.example/a')
|
|
57
|
+
expect(safeHttpsUrl('http://x.example')).toBeNull()
|
|
58
|
+
expect(safeHttpsUrl('javascript:alert(1)')).toBeNull()
|
|
59
|
+
expect(safeHttpsUrl('https://user:pw@x.example')).toBeNull()
|
|
60
|
+
})
|
|
61
|
+
|
|
62
|
+
it('a section with only blocks is a step; settings append a last step', () => {
|
|
63
|
+
const steps = buildWizardSteps(
|
|
64
|
+
[{ key: 'a' }, { key: 'b', blocks: [{ key: 'w', kind: 'webhook_url' }] }, { key: 'c' }],
|
|
65
|
+
['a'],
|
|
66
|
+
true,
|
|
67
|
+
)
|
|
68
|
+
expect(steps.map((s) => s.key)).toEqual(['a', 'b', '__settings'])
|
|
69
|
+
expect(hasExplicitTest([{ key: 'a', blocks: [{ key: 't', kind: 'action', export: 'ping' }] }], 'ping')).toBe(true)
|
|
70
|
+
expect(hasExplicitTest([{ key: 'a' }], 'ping')).toBe(false)
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
it('step status: errors win, then verification, then visited', () => {
|
|
74
|
+
const base = { index: 0, current: 1, fieldKeys: ['a'], fieldErrors: {}, blockKeys: ['t'], results: {} }
|
|
75
|
+
expect(stepStatus(base)).toBe('ok')
|
|
76
|
+
expect(stepStatus({ ...base, fieldErrors: { a: 'x' } })).toBe('error')
|
|
77
|
+
expect(stepStatus({ ...base, results: { t: { status: 'error', message: '', details: [] } } })).toBe('error')
|
|
78
|
+
expect(stepStatus({ ...base, index: 1, results: { t: { status: 'ok', message: '', details: [] } } })).toBe('ok')
|
|
79
|
+
expect(stepStatus({ ...base, index: 2 })).toBe('pending')
|
|
80
|
+
})
|
|
81
|
+
})
|
|
82
|
+
|
|
83
|
+
function makeApi(routes: Record<string, any> = {}) {
|
|
84
|
+
const calls: { m: string; url: string; body?: any }[] = []
|
|
85
|
+
const handle = (m: string) => async (url: string, body?: any) => {
|
|
86
|
+
calls.push({ m, url, body })
|
|
87
|
+
const r = routes[`${m} ${url}`]
|
|
88
|
+
if (r instanceof Error) throw r
|
|
89
|
+
return { data: typeof r === 'function' ? r(body) : (r ?? { data: {} }) }
|
|
90
|
+
}
|
|
91
|
+
return { client: { get: handle('GET'), post: handle('POST'), put: handle('PUT'), delete: handle('DELETE') }, calls }
|
|
92
|
+
}
|
|
93
|
+
|
|
94
|
+
const addon = { addon_key: 'mercadopago', manifest: { name: 'Mercado Pago', settings_defs: [] as any[] } }
|
|
95
|
+
|
|
96
|
+
const mp: ConnectorEntry = {
|
|
97
|
+
addon_key: 'mercadopago',
|
|
98
|
+
provider: 'mercadopago',
|
|
99
|
+
auth: 'token',
|
|
100
|
+
connected: true,
|
|
101
|
+
test_export: 'handle_connector_test',
|
|
102
|
+
form_layout: {
|
|
103
|
+
mode: 'steps',
|
|
104
|
+
sections: [
|
|
105
|
+
{ key: 'connection', title: 'mp.section.connection' },
|
|
106
|
+
{
|
|
107
|
+
key: 'advanced',
|
|
108
|
+
title: 'mp.section.advanced',
|
|
109
|
+
description: 'mp.section.advanced_help',
|
|
110
|
+
blocks: [
|
|
111
|
+
{
|
|
112
|
+
key: 'webhook_url',
|
|
113
|
+
kind: 'webhook_url',
|
|
114
|
+
webhook: 'notifications',
|
|
115
|
+
title: 'mp.block.webhook.title',
|
|
116
|
+
value: WEBHOOK,
|
|
117
|
+
links: [{ label: 'mp.block.webhook.panel', url: 'https://www.mercadopago.com.mx/developers/panel/app' }],
|
|
118
|
+
},
|
|
119
|
+
{ key: 'test_order', kind: 'action', export: 'handle_setup_test_order', label: 'mp.block.order.label', title: 'mp.block.order.title' },
|
|
120
|
+
],
|
|
121
|
+
},
|
|
122
|
+
],
|
|
123
|
+
},
|
|
124
|
+
credentials: [
|
|
125
|
+
{ key: 'access_token', label: 'mp.field.token', type: 'secret', secret: true, required: true, section: 'connection' },
|
|
126
|
+
{ key: 'webhook_secret', label: 'mp.field.secret', type: 'secret', secret: true, section: 'advanced' },
|
|
127
|
+
],
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function setup(connector: ConnectorEntry | null, routes: Record<string, any> = {}, extra: Record<string, any> = {}) {
|
|
131
|
+
const api = makeApi(routes)
|
|
132
|
+
const notify = { success: vi.fn(), error: vi.fn(), info: vi.fn(), warning: vi.fn() }
|
|
133
|
+
const qc = new QueryClient({ defaultOptions: { mutations: { retry: false }, queries: { retry: false } } })
|
|
134
|
+
const onOpenChange = vi.fn()
|
|
135
|
+
render(
|
|
136
|
+
<QueryClientProvider client={qc}>
|
|
137
|
+
<ApiProvider client={api.client as any} batch={false}>
|
|
138
|
+
<AddonConfigSurface addon={addon} connector={connector} open onOpenChange={onOpenChange} notify={notify} {...extra} />
|
|
139
|
+
</ApiProvider>
|
|
140
|
+
</QueryClientProvider>,
|
|
141
|
+
)
|
|
142
|
+
return { ...api, notify, onOpenChange }
|
|
143
|
+
}
|
|
144
|
+
|
|
145
|
+
const footer = () => document.querySelector('[data-wizard-footer]') as HTMLElement
|
|
146
|
+
|
|
147
|
+
describe('AddonConfigSurface with setup blocks', () => {
|
|
148
|
+
it('step 2 shows the org webhook URL with copy, the panel link and the test-order action', async () => {
|
|
149
|
+
const writeText = vi.fn().mockResolvedValue(undefined)
|
|
150
|
+
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
|
151
|
+
setup(mp)
|
|
152
|
+
await screen.findByText('Access token')
|
|
153
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
154
|
+
expect(await screen.findByText(WEBHOOK)).toBeTruthy()
|
|
155
|
+
const link = screen.getByText('Abrir panel de Mercado Pago').closest('a')!
|
|
156
|
+
expect(link.getAttribute('href')).toBe('https://www.mercadopago.com.mx/developers/panel/app')
|
|
157
|
+
expect(link.getAttribute('rel')).toContain('noopener')
|
|
158
|
+
fireEvent.click(screen.getByRole('button', { name: 'Copiar URL de notificaciones' }))
|
|
159
|
+
await waitFor(() => expect(writeText).toHaveBeenCalledWith(WEBHOOK))
|
|
160
|
+
// The explicit test is the last credentials step's; the implicit one joins it.
|
|
161
|
+
expect(screen.getByText('Crear orden de prueba')).toBeTruthy()
|
|
162
|
+
expect(screen.getByText('Probar conexión')).toBeTruthy()
|
|
163
|
+
// Focus moved to the new step heading.
|
|
164
|
+
expect(document.activeElement?.textContent).toBe('Avanzado')
|
|
165
|
+
// Reading order: URL to paste, then the secret field, then the verifications.
|
|
166
|
+
const url = screen.getByText(WEBHOOK)
|
|
167
|
+
const secret = screen.getByLabelText(/Secreto del webhook/)
|
|
168
|
+
const action = screen.getByText('Crear orden de prueba')
|
|
169
|
+
expect(url.compareDocumentPosition(secret) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
|
170
|
+
expect(secret.compareDocumentPosition(action) & Node.DOCUMENT_POSITION_FOLLOWING).toBeTruthy()
|
|
171
|
+
})
|
|
172
|
+
|
|
173
|
+
it('runs the action block through the host route and shows ID + status live', async () => {
|
|
174
|
+
const { calls } = setup(mp, {
|
|
175
|
+
'POST /integrations/mercadopago/blocks/test_order/run': {
|
|
176
|
+
success: true,
|
|
177
|
+
data: {
|
|
178
|
+
ok: true,
|
|
179
|
+
status: 'ok',
|
|
180
|
+
message: 'Preferencia de prueba creada',
|
|
181
|
+
details: [
|
|
182
|
+
{ key: 'preference_id', label: 'ID de la preferencia', value: '123-abc', kind: 'id' },
|
|
183
|
+
{ key: 'link', label: 'Pagar en sandbox', value: 'https://sandbox.mercadopago.com.mx/checkout/v1/redirect?pref_id=123-abc', kind: 'url' },
|
|
184
|
+
],
|
|
185
|
+
},
|
|
186
|
+
},
|
|
187
|
+
})
|
|
188
|
+
await screen.findByText('Access token')
|
|
189
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
190
|
+
fireEvent.click(await screen.findByText('Crear orden de prueba'))
|
|
191
|
+
const msg = await screen.findByText('Preferencia de prueba creada')
|
|
192
|
+
const live = msg.closest('[aria-live="polite"]') as HTMLElement
|
|
193
|
+
expect(live.getAttribute('role')).toBe('status')
|
|
194
|
+
expect(within(live).getByText('123-abc')).toBeTruthy()
|
|
195
|
+
expect(within(live).getByText('Abrir enlace').closest('a')!.getAttribute('href')).toContain('sandbox.mercadopago.com.mx')
|
|
196
|
+
expect(calls.filter((c) => c.url === '/integrations/mercadopago/blocks/test_order/run')).toHaveLength(1)
|
|
197
|
+
// Stepper marks the verified step.
|
|
198
|
+
expect(document.querySelector('[data-step-status="ok"]')).toBeTruthy()
|
|
199
|
+
// Retry runs it again.
|
|
200
|
+
fireEvent.click(screen.getByText('Reintentar: Crear orden de prueba'))
|
|
201
|
+
await waitFor(() => expect(calls.filter((c) => c.url === '/integrations/mercadopago/blocks/test_order/run')).toHaveLength(2))
|
|
202
|
+
})
|
|
203
|
+
|
|
204
|
+
it('saves typed credentials before running an action (the host tests what is stored)', async () => {
|
|
205
|
+
const { calls } = setup(mp, {
|
|
206
|
+
'POST /integrations/mercadopago/blocks/test_order/run': { success: true, data: { ok: true, message: 'ok' } },
|
|
207
|
+
})
|
|
208
|
+
await screen.findByText('Access token')
|
|
209
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
210
|
+
fireEvent.change(await screen.findByLabelText(/Secreto del webhook/), { target: { value: 'whsec' } })
|
|
211
|
+
expect(screen.getAllByText('Se guardarán tus cambios antes de probar.').length).toBeGreaterThan(0)
|
|
212
|
+
fireEvent.click(screen.getByText('Crear orden de prueba'))
|
|
213
|
+
await screen.findByText('ok')
|
|
214
|
+
const save = calls.findIndex((c) => c.m === 'POST' && c.url === '/integrations/mercadopago')
|
|
215
|
+
const run = calls.findIndex((c) => c.url.endsWith('/blocks/test_order/run'))
|
|
216
|
+
expect(save).toBeGreaterThanOrEqual(0)
|
|
217
|
+
expect(save).toBeLessThan(run)
|
|
218
|
+
expect(calls[save].body).toEqual({ webhook_secret: 'whsec' })
|
|
219
|
+
})
|
|
220
|
+
|
|
221
|
+
it('a failed HTTP call is an error result, never success', async () => {
|
|
222
|
+
const err = Object.assign(new Error('x'), { response: { data: { message: 'Guarda las credenciales antes de probar' } } })
|
|
223
|
+
setup(mp, { 'POST /integrations/mercadopago/blocks/test_order/run': err })
|
|
224
|
+
await screen.findByText('Access token')
|
|
225
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
226
|
+
fireEvent.click(await screen.findByText('Crear orden de prueba'))
|
|
227
|
+
const msg = await screen.findByText('Guarda las credenciales antes de probar')
|
|
228
|
+
expect(msg.closest('[data-result-status]')!.getAttribute('data-result-status')).toBe('error')
|
|
229
|
+
expect(document.querySelector('[data-step-status="error"]')).toBeTruthy()
|
|
230
|
+
})
|
|
231
|
+
|
|
232
|
+
it('Siguiente validates the current step before moving on', async () => {
|
|
233
|
+
setup({ ...mp, connected: false })
|
|
234
|
+
await screen.findByText('Access token')
|
|
235
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
236
|
+
expect((await screen.findByText(/Faltan campos obligatorios: Access token/)).getAttribute('role')).toBe('alert')
|
|
237
|
+
expect(screen.queryByText(WEBHOOK)).toBeNull()
|
|
238
|
+
})
|
|
239
|
+
|
|
240
|
+
it('footer: one primary, full width on phones; Atrás + Cancelar share a row', async () => {
|
|
241
|
+
setup(mp)
|
|
242
|
+
await screen.findByText('Access token')
|
|
243
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
244
|
+
await screen.findByText(WEBHOOK)
|
|
245
|
+
const buttons = within(footer()).getAllByRole('button')
|
|
246
|
+
expect(buttons.map((b) => b.textContent)).toEqual(['Guardar', 'Atrás', 'Cancelar'])
|
|
247
|
+
expect(buttons[0].className).toContain('col-span-2')
|
|
248
|
+
expect(buttons[0].className).toContain('h-11')
|
|
249
|
+
expect(buttons[1].className).not.toContain('col-span-2')
|
|
250
|
+
expect(buttons[2].className).not.toContain('col-span-2')
|
|
251
|
+
expect(within(footer()).queryByText('Probar conexión')).toBeNull()
|
|
252
|
+
expect(footer().className).toContain('grid-cols-2')
|
|
253
|
+
})
|
|
254
|
+
|
|
255
|
+
it('an explicit action bound to test_export replaces the implicit test', async () => {
|
|
256
|
+
const explicit: ConnectorEntry = {
|
|
257
|
+
...mp,
|
|
258
|
+
form_layout: {
|
|
259
|
+
mode: 'steps',
|
|
260
|
+
sections: [
|
|
261
|
+
{ key: 'connection', title: 'mp.section.connection', blocks: [{ key: 'ping', kind: 'action', export: 'handle_connector_test', label: 'Probar ahora' }] },
|
|
262
|
+
{ key: 'advanced', title: 'mp.section.advanced' },
|
|
263
|
+
],
|
|
264
|
+
},
|
|
265
|
+
}
|
|
266
|
+
setup(explicit)
|
|
267
|
+
expect(await screen.findByText('Probar ahora')).toBeTruthy()
|
|
268
|
+
fireEvent.click(within(footer()).getByText('Siguiente'))
|
|
269
|
+
await screen.findByText('Secreto del webhook')
|
|
270
|
+
expect(screen.queryByText('Probar conexión')).toBeNull()
|
|
271
|
+
})
|
|
272
|
+
|
|
273
|
+
it('long help expands instead of being cut', async () => {
|
|
274
|
+
const long = 'Ayuda '.repeat(60).trim()
|
|
275
|
+
setup({ ...mp, form_layout: { mode: 'steps', sections: [{ key: 'connection', title: 'mp.section.connection', description: long }, { key: 'advanced' }] } })
|
|
276
|
+
const p = await screen.findByText(long)
|
|
277
|
+
expect(p.className).toContain('line-clamp-3')
|
|
278
|
+
const more = screen.getByRole('button', { name: 'Ver más' })
|
|
279
|
+
expect(more.getAttribute('aria-expanded')).toBe('false')
|
|
280
|
+
fireEvent.click(more)
|
|
281
|
+
expect(p.className).not.toContain('line-clamp-3')
|
|
282
|
+
expect(screen.getByRole('button', { name: 'Ver menos' }).getAttribute('aria-expanded')).toBe('true')
|
|
283
|
+
})
|
|
284
|
+
|
|
285
|
+
it('OAuth connectors show their state and hand "Conectar cuenta" to the host', async () => {
|
|
286
|
+
const onConnectOAuth = vi.fn()
|
|
287
|
+
const gh: ConnectorEntry = { addon_key: 'mercadopago', provider: 'github', auth: 'oauth2', connected: false }
|
|
288
|
+
setup(gh, {}, { onConnectOAuth })
|
|
289
|
+
expect(await screen.findByText('Sin conectar')).toBeTruthy()
|
|
290
|
+
fireEvent.click(screen.getByText('Conectar cuenta'))
|
|
291
|
+
expect(onConnectOAuth).toHaveBeenCalledWith(gh)
|
|
292
|
+
})
|
|
293
|
+
|
|
294
|
+
it('an addon with nothing to configure shows a useful empty state and a single Cerrar', async () => {
|
|
295
|
+
const { onOpenChange } = setup(null)
|
|
296
|
+
expect(await screen.findByText('Nada que configurar')).toBeTruthy()
|
|
297
|
+
const buttons = within(footer()).getAllByRole('button')
|
|
298
|
+
expect(buttons.map((b) => b.textContent)).toEqual(['Cerrar'])
|
|
299
|
+
fireEvent.click(buttons[0])
|
|
300
|
+
expect(onOpenChange).toHaveBeenCalledWith(false)
|
|
301
|
+
})
|
|
302
|
+
})
|
|
@@ -0,0 +1,147 @@
|
|
|
1
|
+
// @vitest-environment happy-dom
|
|
2
|
+
import { afterEach, describe, expect, it, vi } from 'vitest'
|
|
3
|
+
import { cleanup, fireEvent, render, screen, waitFor } from '@testing-library/react'
|
|
4
|
+
|
|
5
|
+
const lang = { current: 'es' }
|
|
6
|
+
vi.mock('react-i18next', () => {
|
|
7
|
+
const t = (k: string, o?: { defaultValue?: string }) => o?.defaultValue ?? k
|
|
8
|
+
return { useTranslation: () => ({ t, i18n: { language: lang.current, exists: () => true } }) }
|
|
9
|
+
})
|
|
10
|
+
|
|
11
|
+
import { StepStatusBadge } from '../setup/step-status-badge'
|
|
12
|
+
import { RecordsTable, copyText } from '../setup/records-table'
|
|
13
|
+
import { HealthCard } from '../setup/health-card'
|
|
14
|
+
|
|
15
|
+
afterEach(() => {
|
|
16
|
+
cleanup()
|
|
17
|
+
lang.current = 'es'
|
|
18
|
+
vi.restoreAllMocks()
|
|
19
|
+
})
|
|
20
|
+
|
|
21
|
+
describe('StepStatusBadge', () => {
|
|
22
|
+
it.each([
|
|
23
|
+
['pending', 'Pendiente'],
|
|
24
|
+
['running', 'En curso'],
|
|
25
|
+
['ok', 'Listo'],
|
|
26
|
+
['warn', 'Con avisos'],
|
|
27
|
+
['error', 'Con error'],
|
|
28
|
+
['blocked', 'Bloqueado'],
|
|
29
|
+
] as const)('%s renders a text label (not colour alone)', (status, text) => {
|
|
30
|
+
render(<StepStatusBadge status={status} />)
|
|
31
|
+
expect(screen.getByText(text)).toBeTruthy()
|
|
32
|
+
})
|
|
33
|
+
it('speaks English when the language is en', () => {
|
|
34
|
+
lang.current = 'en-US'
|
|
35
|
+
render(<StepStatusBadge status='blocked' />)
|
|
36
|
+
expect(screen.getByText('Blocked')).toBeTruthy()
|
|
37
|
+
})
|
|
38
|
+
it('compact keeps the label for screen readers only', () => {
|
|
39
|
+
render(<StepStatusBadge status='ok' compact />)
|
|
40
|
+
expect(screen.getByText('Listo').className).toContain('sr-only')
|
|
41
|
+
})
|
|
42
|
+
})
|
|
43
|
+
|
|
44
|
+
describe('copyText', () => {
|
|
45
|
+
it('uses the Clipboard API when available', async () => {
|
|
46
|
+
const writeText = vi.fn().mockResolvedValue(undefined)
|
|
47
|
+
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
|
48
|
+
expect(await copyText('abc')).toBe(true)
|
|
49
|
+
expect(writeText).toHaveBeenCalledWith('abc')
|
|
50
|
+
})
|
|
51
|
+
it('falls back to execCommand when the Clipboard API rejects', async () => {
|
|
52
|
+
Object.defineProperty(navigator, 'clipboard', { value: { writeText: vi.fn().mockRejectedValue(new Error('denied')) }, configurable: true })
|
|
53
|
+
const exec = vi.fn().mockReturnValue(true)
|
|
54
|
+
;(document as any).execCommand = exec
|
|
55
|
+
expect(await copyText('abc')).toBe(true)
|
|
56
|
+
expect(exec).toHaveBeenCalledWith('copy')
|
|
57
|
+
expect(document.querySelector('textarea')).toBeNull() // cleaned up
|
|
58
|
+
})
|
|
59
|
+
it('reports failure when nothing works', async () => {
|
|
60
|
+
Object.defineProperty(navigator, 'clipboard', { value: undefined, configurable: true })
|
|
61
|
+
;(document as any).execCommand = vi.fn().mockReturnValue(false)
|
|
62
|
+
expect(await copyText('abc')).toBe(false)
|
|
63
|
+
})
|
|
64
|
+
})
|
|
65
|
+
|
|
66
|
+
describe('RecordsTable', () => {
|
|
67
|
+
const records = [
|
|
68
|
+
{ type: 'TXT', name: '_dmarc.acme.test', value: 'v=DMARC1; p=none', status: 'ok' as const },
|
|
69
|
+
{ type: 'MX', name: 'acme.test', value: 'mx.acme.test', status: 'wrong_value' as const, found: 'old.mx.test', diagnostic: { message: 'El MX apunta a otro servidor', fix: { label: 'Corregir', action: 'apply_dns' } } },
|
|
70
|
+
{ type: 'TXT', name: 'acme.test', value: 'v=spf1 -all', status: 'propagating' as const, diagnostic: 'Puede tardar unos minutos' },
|
|
71
|
+
]
|
|
72
|
+
it('shows type, name, value, status and diagnostics per row', () => {
|
|
73
|
+
render(<RecordsTable records={records} caption='DNS' />)
|
|
74
|
+
expect(screen.getByRole('table')).toBeTruthy()
|
|
75
|
+
expect(screen.getByText('_dmarc.acme.test')).toBeTruthy()
|
|
76
|
+
expect(screen.getByText('Correcto')).toBeTruthy()
|
|
77
|
+
expect(screen.getByText('Valor distinto')).toBeTruthy()
|
|
78
|
+
expect(screen.getByText('Propagando')).toBeTruthy()
|
|
79
|
+
expect(screen.getByText('Encontrado: old.mx.test')).toBeTruthy()
|
|
80
|
+
expect(screen.getByText('El MX apunta a otro servidor')).toBeTruthy()
|
|
81
|
+
expect(screen.getByText('Puede tardar unos minutos')).toBeTruthy()
|
|
82
|
+
})
|
|
83
|
+
it('copies a value and confirms it', async () => {
|
|
84
|
+
const writeText = vi.fn().mockResolvedValue(undefined)
|
|
85
|
+
Object.defineProperty(navigator, 'clipboard', { value: { writeText }, configurable: true })
|
|
86
|
+
render(<RecordsTable records={records} />)
|
|
87
|
+
fireEvent.click(screen.getAllByLabelText('Copiar valor')[0])
|
|
88
|
+
await waitFor(() => expect(screen.getByText('Copiado')).toBeTruthy())
|
|
89
|
+
expect(writeText).toHaveBeenCalledWith('v=DMARC1; p=none')
|
|
90
|
+
})
|
|
91
|
+
it('tells the person when copy fails', async () => {
|
|
92
|
+
Object.defineProperty(navigator, 'clipboard', { value: undefined, configurable: true })
|
|
93
|
+
;(document as any).execCommand = vi.fn().mockReturnValue(false)
|
|
94
|
+
render(<RecordsTable records={records} />)
|
|
95
|
+
fireEvent.click(screen.getAllByLabelText('Copiar nombre')[0])
|
|
96
|
+
await waitFor(() => expect(screen.getByText(/No se pudo copiar/)).toBeTruthy())
|
|
97
|
+
})
|
|
98
|
+
it('row fix calls onFix with the fix and the record', () => {
|
|
99
|
+
const onFix = vi.fn()
|
|
100
|
+
render(<RecordsTable records={records} onFix={onFix} />)
|
|
101
|
+
fireEvent.click(screen.getByText('Corregir'))
|
|
102
|
+
expect(onFix).toHaveBeenCalledWith({ label: 'Corregir', action: 'apply_dns' }, records[1])
|
|
103
|
+
})
|
|
104
|
+
it('empty list shows a message and recheck fires', () => {
|
|
105
|
+
const onRecheck = vi.fn()
|
|
106
|
+
const { rerender } = render(<RecordsTable records={[]} />)
|
|
107
|
+
expect(screen.getByText('No hay registros por mostrar.')).toBeTruthy()
|
|
108
|
+
rerender(<RecordsTable records={records} onRecheck={onRecheck} />)
|
|
109
|
+
fireEvent.click(screen.getByText('Verificar ahora'))
|
|
110
|
+
expect(onRecheck).toHaveBeenCalled()
|
|
111
|
+
})
|
|
112
|
+
})
|
|
113
|
+
|
|
114
|
+
describe('HealthCard', () => {
|
|
115
|
+
it('renders status, metrics with tone and issues with fix', () => {
|
|
116
|
+
const onFix = vi.fn()
|
|
117
|
+
const onContinue = vi.fn()
|
|
118
|
+
render(
|
|
119
|
+
<HealthCard
|
|
120
|
+
title='Correo'
|
|
121
|
+
status='warn'
|
|
122
|
+
summary='Falta un registro'
|
|
123
|
+
progress={{ done: 2, total: 4 }}
|
|
124
|
+
metrics={[
|
|
125
|
+
{ key: 'q', label: 'En cola', value: 12, tone: 'warn' },
|
|
126
|
+
{ key: 's', label: 'Entregados', value: '98', unit: '%', tone: 'good' },
|
|
127
|
+
]}
|
|
128
|
+
issues={[{ severity: 'error', message: 'DKIM no publicado', fix: { label: 'Ver registros', step: 'dns' } }]}
|
|
129
|
+
onFix={onFix}
|
|
130
|
+
onContinue={onContinue}
|
|
131
|
+
/>,
|
|
132
|
+
)
|
|
133
|
+
expect(screen.getByText('Requiere atención')).toBeTruthy()
|
|
134
|
+
expect(screen.getByText('2 de 4 pasos')).toBeTruthy()
|
|
135
|
+
expect(screen.getByRole('progressbar').getAttribute('aria-valuenow')).toBe('50')
|
|
136
|
+
expect(screen.getByText('12').closest('[data-metric-tone]')?.getAttribute('data-metric-tone')).toBe('warn')
|
|
137
|
+
fireEvent.click(screen.getByText('Ver registros'))
|
|
138
|
+
expect(onFix).toHaveBeenCalledWith({ label: 'Ver registros', step: 'dns' }, expect.objectContaining({ message: 'DKIM no publicado' }))
|
|
139
|
+
fireEvent.click(screen.getByText('Continuar configuración'))
|
|
140
|
+
expect(onContinue).toHaveBeenCalled()
|
|
141
|
+
})
|
|
142
|
+
it('says there are no issues when the list is empty and unknown status degrades', () => {
|
|
143
|
+
render(<HealthCard status={'weird' as any} issues={[]} />)
|
|
144
|
+
expect(screen.getByText('Sin datos')).toBeTruthy()
|
|
145
|
+
expect(screen.getByText('Sin avisos.')).toBeTruthy()
|
|
146
|
+
})
|
|
147
|
+
})
|
|
@@ -0,0 +1,117 @@
|
|
|
1
|
+
import { describe, expect, it } from 'vitest'
|
|
2
|
+
import {
|
|
3
|
+
effectiveStatus,
|
|
4
|
+
flowProgress,
|
|
5
|
+
mergeAnswer,
|
|
6
|
+
nextPollDelayMs,
|
|
7
|
+
normalizeState,
|
|
8
|
+
pickActiveStep,
|
|
9
|
+
safeUrl,
|
|
10
|
+
unmetDependencies,
|
|
11
|
+
} from '../setup/flow-model'
|
|
12
|
+
import type { SetupStepDef, SetupStepState } from '../setup/types'
|
|
13
|
+
|
|
14
|
+
const defs: SetupStepDef[] = [
|
|
15
|
+
{ key: 'domain', kind: 'form', title: 'Domain' },
|
|
16
|
+
{ key: 'dns', kind: 'records', title: 'DNS', depends_on: ['domain'] },
|
|
17
|
+
{ key: 'test', kind: 'action', title: 'Test', depends_on: ['dns'] },
|
|
18
|
+
{ key: 'extras', kind: 'action', title: 'Extras', optional: true },
|
|
19
|
+
]
|
|
20
|
+
const st = (key: string, status: SetupStepState['status'], extra: Partial<SetupStepState> = {}): SetupStepState => ({ key, status, ...extra })
|
|
21
|
+
const map = (...s: SetupStepState[]) => Object.fromEntries(s.map((x) => [x.key, x]))
|
|
22
|
+
|
|
23
|
+
describe('normalizeState', () => {
|
|
24
|
+
it('accepts array and by-key map', () => {
|
|
25
|
+
expect(normalizeState({ steps: [st('a', 'ok')] }).a.status).toBe('ok')
|
|
26
|
+
expect(normalizeState({ steps: { a: { status: 'warn' } as SetupStepState } }).a).toMatchObject({ key: 'a', status: 'warn' })
|
|
27
|
+
expect(normalizeState(undefined)).toEqual({})
|
|
28
|
+
})
|
|
29
|
+
})
|
|
30
|
+
|
|
31
|
+
describe('effectiveStatus / depends_on', () => {
|
|
32
|
+
it('blocks a step whose dependency is not satisfied', () => {
|
|
33
|
+
const s = map(st('domain', 'pending'))
|
|
34
|
+
expect(effectiveStatus(defs[1], s)).toBe('blocked')
|
|
35
|
+
expect(unmetDependencies(defs[1], s)).toEqual(['domain'])
|
|
36
|
+
})
|
|
37
|
+
it('unblocks when the dependency is ok, warn or skipped', () => {
|
|
38
|
+
expect(effectiveStatus(defs[1], map(st('domain', 'ok')))).toBe('pending')
|
|
39
|
+
expect(effectiveStatus(defs[1], map(st('domain', 'warn')))).toBe('pending')
|
|
40
|
+
expect(effectiveStatus(defs[1], map(st('domain', 'pending', { skipped: true })))).toBe('pending')
|
|
41
|
+
})
|
|
42
|
+
it('an error dependency keeps dependants blocked', () => {
|
|
43
|
+
expect(effectiveStatus(defs[1], map(st('domain', 'error')))).toBe('blocked')
|
|
44
|
+
})
|
|
45
|
+
it('keeps running/ok from the server and reads skipped as ok', () => {
|
|
46
|
+
expect(effectiveStatus(defs[1], map(st('dns', 'running')))).toBe('running')
|
|
47
|
+
expect(effectiveStatus(defs[3], map(st('extras', 'pending', { skipped: true })))).toBe('ok')
|
|
48
|
+
})
|
|
49
|
+
})
|
|
50
|
+
|
|
51
|
+
describe('pickActiveStep / flowProgress', () => {
|
|
52
|
+
it('resumes at the first step that is not satisfied and not blocked', () => {
|
|
53
|
+
expect(pickActiveStep(defs, map(st('domain', 'ok'), st('dns', 'error')))).toBe('dns')
|
|
54
|
+
expect(pickActiveStep(defs, map())).toBe('domain')
|
|
55
|
+
})
|
|
56
|
+
it('falls to the last step when everything is satisfied', () => {
|
|
57
|
+
expect(pickActiveStep(defs, map(st('domain', 'ok'), st('dns', 'ok'), st('test', 'ok'), st('extras', 'ok')))).toBe('extras')
|
|
58
|
+
})
|
|
59
|
+
it('optional steps do not hold completion back', () => {
|
|
60
|
+
const p = flowProgress(defs, map(st('domain', 'ok'), st('dns', 'ok'), st('test', 'ok')))
|
|
61
|
+
expect(p).toEqual({ done: 3, total: 3, percent: 100, complete: true })
|
|
62
|
+
})
|
|
63
|
+
it('an error step is not progress', () => {
|
|
64
|
+
const p = flowProgress(defs, map(st('domain', 'ok'), st('dns', 'error')))
|
|
65
|
+
expect(p.complete).toBe(false)
|
|
66
|
+
expect(p.done).toBe(1)
|
|
67
|
+
})
|
|
68
|
+
it('honours the server verdict', () => {
|
|
69
|
+
expect(flowProgress(defs, {}, true)).toMatchObject({ complete: true, percent: 100 })
|
|
70
|
+
})
|
|
71
|
+
})
|
|
72
|
+
|
|
73
|
+
describe('nextPollDelayMs', () => {
|
|
74
|
+
it('backs off exponentially up to the cap', () => {
|
|
75
|
+
expect(nextPollDelayMs(0)).toBe(2000)
|
|
76
|
+
expect(nextPollDelayMs(1)).toBe(3200)
|
|
77
|
+
expect(nextPollDelayMs(2)).toBe(5120)
|
|
78
|
+
expect(nextPollDelayMs(50)).toBe(30000)
|
|
79
|
+
})
|
|
80
|
+
it('retry_after_s wins, clamped to 1s..5min', () => {
|
|
81
|
+
expect(nextPollDelayMs(5, 45)).toBe(45000)
|
|
82
|
+
expect(nextPollDelayMs(0, 0.1)).toBe(1000) // floor 1s
|
|
83
|
+
expect(nextPollDelayMs(0, -3)).toBe(2000) // unusable hint → backoff
|
|
84
|
+
expect(nextPollDelayMs(0, 1)).toBe(1000)
|
|
85
|
+
expect(nextPollDelayMs(0, 99999)).toBe(300000)
|
|
86
|
+
})
|
|
87
|
+
})
|
|
88
|
+
|
|
89
|
+
describe('safeUrl', () => {
|
|
90
|
+
it('allows http(s) and app-relative, refuses the rest', () => {
|
|
91
|
+
expect(safeUrl('/settings')).toBe('/settings')
|
|
92
|
+
expect(safeUrl('https://x.test/a')).toBe('https://x.test/a')
|
|
93
|
+
expect(safeUrl('javascript:alert(1)')).toBeNull()
|
|
94
|
+
expect(safeUrl('//evil.test')).toBeNull()
|
|
95
|
+
expect(safeUrl('data:text/html,hi')).toBeNull()
|
|
96
|
+
})
|
|
97
|
+
it('refuses relative paths that browsers resolve to another host', () => {
|
|
98
|
+
expect(safeUrl('/\\evil.com/x')).toBeNull()
|
|
99
|
+
expect(safeUrl('/\t/evil.com')).toBeNull()
|
|
100
|
+
expect(safeUrl('/\n/evil.com')).toBeNull()
|
|
101
|
+
expect(safeUrl('\\\\evil.com')).toBeNull()
|
|
102
|
+
expect(safeUrl(' //evil.com ')).toBeNull()
|
|
103
|
+
expect(safeUrl(' javascript:alert(1)')).toBeNull()
|
|
104
|
+
expect(safeUrl('/ok/path?x=1#h')).toBe('/ok/path?x=1#h')
|
|
105
|
+
expect(safeUrl(' /padded ')).toBe('/padded')
|
|
106
|
+
expect(safeUrl('')).toBeNull()
|
|
107
|
+
})
|
|
108
|
+
})
|
|
109
|
+
|
|
110
|
+
describe('mergeAnswer', () => {
|
|
111
|
+
it('merges a step answer, replaces on a flow answer, refetches on void', () => {
|
|
112
|
+
const cur = map(st('a', 'pending'))
|
|
113
|
+
expect(mergeAnswer(cur, 'a', st('a', 'ok')).next.a.status).toBe('ok')
|
|
114
|
+
expect(mergeAnswer(cur, 'a', { steps: [st('b', 'ok')] }).next).toEqual({ b: st('b', 'ok') })
|
|
115
|
+
expect(mergeAnswer(cur, 'a', undefined).needsRefetch).toBe(true)
|
|
116
|
+
})
|
|
117
|
+
})
|