Initialise le front-end Vue
- Vue 3, Vite, TypeScript, Vue Router, vue-i18n, MapLibre GL JS, Bootstrap 5 (CSS seul), Bootstrap Icons, police Roboto. - Pages : connexion, évaluation (adresse, carte avec couches WalOnMap, une carte par facteur avec badge, valeurs mesurées, onglets et références, état « indisponible » avec Réessayer), erreurs 403/404. - Design repris des maquettes Penpot (charte ssmg.be), bureau et mobile. - Garde de navigation, client API avec jeton CSRF ; l'adresse du patient ne quitte pas la mémoire du composant. - 51 tests Vitest ; README et CLAUDE.md mis à jour. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
This commit is contained in:
1 parent
7d441b11c2
commit
7f29cec2a2
52 files changed
+9347
-4
No files matched your search
@@ -0,0 +1,57 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import FactorCard from '@/components/FactorCard.vue'
|
||||
|
||||
import { factor, mountWithPlugins } from './helpers'
|
||||
|
||||
describe('FactorCard', () => {
|
||||
it('affiche le niveau, le résumé, le détail et les références', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor() } })
|
||||
expect(wrapper.find('h2').text()).toBe('Pollution sonore')
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Impact faible')
|
||||
expect(wrapper.find('.color-badge').classes()).toContain('level-1')
|
||||
expect(wrapper.find('.summary').text()).toBe('moins de 55 dB (Lden)')
|
||||
expect(wrapper.find('dl').text()).toContain('Route')
|
||||
expect(wrapper.find('.references a').attributes('href')).toBe('https://eea.europa.eu')
|
||||
})
|
||||
|
||||
it.each([
|
||||
[2, 'Impact modéré'],
|
||||
[3, 'Impact élevé'],
|
||||
[4, 'Impact très élevé'],
|
||||
])('niveau %i → « %s »', (level, text) => {
|
||||
const wrapper = mountWithPlugins(FactorCard, { props: { factor: factor({ level }) } })
|
||||
expect(wrapper.find('.color-badge').text()).toBe(text)
|
||||
expect(wrapper.find('.factor-dot').classes()).toContain(`level-${level}`)
|
||||
})
|
||||
|
||||
it('affiche « Niveau non défini » sans classe de seuil', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ level: null, color: null }) },
|
||||
})
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Niveau non défini')
|
||||
expect(wrapper.find('.factor-dot').classes()).toContain('level-none')
|
||||
})
|
||||
|
||||
it('source indisponible : message, contour pointillé et bouton Réessayer', async () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ code: 'radon', label: 'Radon', status: 'unavailable' }) },
|
||||
})
|
||||
expect(wrapper.classes()).toContain('unavailable')
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Donnée indisponible')
|
||||
expect(wrapper.text()).toContain('Le service de données « radon » ne répond pas')
|
||||
expect(wrapper.find('dl').exists()).toBe(false)
|
||||
|
||||
await wrapper.find('button').trigger('click')
|
||||
expect(wrapper.emitted('retry')).toHaveLength(1)
|
||||
})
|
||||
|
||||
it('donnée absente : message sans bouton Réessayer', () => {
|
||||
const wrapper = mountWithPlugins(FactorCard, {
|
||||
props: { factor: factor({ status: 'no_data' }) },
|
||||
})
|
||||
expect(wrapper.find('.color-badge').text()).toBe('Donnée absente')
|
||||
expect(wrapper.text()).toContain('Aucune donnée')
|
||||
expect(wrapper.find('button').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,59 @@
|
||||
import { describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import ResultMap from '@/components/ResultMap.vue'
|
||||
|
||||
import { mountWithPlugins } from './helpers'
|
||||
|
||||
// MapLibre a besoin de WebGL, absent de jsdom : on vérifie les appels.
|
||||
type Fn = (...args: unknown[]) => unknown
|
||||
|
||||
const mapInstance = {
|
||||
addControl: vi.fn<Fn>(),
|
||||
resize: vi.fn<Fn>(),
|
||||
jumpTo: vi.fn<Fn>(),
|
||||
setLayoutProperty: vi.fn<Fn>(),
|
||||
remove: vi.fn<Fn>(),
|
||||
}
|
||||
const marker = {
|
||||
setLngLat: vi.fn<Fn>().mockReturnThis(),
|
||||
addTo: vi.fn<Fn>().mockReturnThis(),
|
||||
remove: vi.fn<Fn>(),
|
||||
}
|
||||
|
||||
vi.mock('maplibre-gl', () => ({
|
||||
Map: vi.fn<() => typeof mapInstance>(function () {
|
||||
return mapInstance
|
||||
}),
|
||||
Marker: vi.fn<() => typeof marker>(function () {
|
||||
return marker
|
||||
}),
|
||||
NavigationControl: vi.fn<Fn>(),
|
||||
ScaleControl: vi.fn<Fn>(),
|
||||
}))
|
||||
|
||||
describe('ResultMap', () => {
|
||||
it("centre la carte et place le marqueur sur l'adresse", async () => {
|
||||
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||
expect(marker.setLngLat).not.toHaveBeenCalled()
|
||||
|
||||
await wrapper.setProps({ location: { lat: 50.668, lon: 4.617, region: 'WAL' } })
|
||||
|
||||
expect(marker.setLngLat).toHaveBeenCalledWith([4.617, 50.668])
|
||||
expect(mapInstance.jumpTo).toHaveBeenCalledWith(
|
||||
expect.objectContaining({ center: [4.617, 50.668], zoom: 15 }),
|
||||
)
|
||||
})
|
||||
|
||||
it('affiche ou masque une couche WMS', async () => {
|
||||
const wrapper = mountWithPlugins(ResultMap, { props: { location: null } })
|
||||
await wrapper.find('#layer-noise').setValue(true)
|
||||
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('noise', 'visibility', 'visible')
|
||||
await wrapper.find('#layer-flood').trigger('change')
|
||||
expect(mapInstance.setLayoutProperty).toHaveBeenCalledWith('flood', 'visibility', 'none')
|
||||
})
|
||||
|
||||
it('libère la carte au démontage', () => {
|
||||
mountWithPlugins(ResultMap, { props: { location: null } }).unmount()
|
||||
expect(mapInstance.remove).toHaveBeenCalled()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,70 @@
|
||||
import { afterEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { api, ApiError, csrfToken } from '@/api/client'
|
||||
|
||||
import { ASSESSMENT, jsonResponse, mockFetch } from './helpers'
|
||||
|
||||
afterEach(() => {
|
||||
vi.unstubAllGlobals()
|
||||
document.cookie = 'csrftoken=; expires=Thu, 01 Jan 1970 00:00:00 GMT'
|
||||
})
|
||||
|
||||
describe('csrfToken', () => {
|
||||
it('lit le cookie csrftoken', () => {
|
||||
document.cookie = 'autre=1'
|
||||
document.cookie = 'csrftoken=abc123'
|
||||
expect(csrfToken()).toBe('abc123')
|
||||
})
|
||||
|
||||
it('renvoie une chaîne vide sans cookie', () => {
|
||||
expect(csrfToken()).toBe('')
|
||||
})
|
||||
})
|
||||
|
||||
describe('api', () => {
|
||||
it('envoie le jeton CSRF et le corps JSON sur un POST', async () => {
|
||||
document.cookie = 'csrftoken=jeton'
|
||||
const fetch = mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
|
||||
const result = await api.assess('Place de l’Université 1')
|
||||
|
||||
expect(result).toEqual(ASSESSMENT)
|
||||
const [url, init] = fetch.mock.calls[0]!
|
||||
expect(url).toBe('/api/v1/assessments/')
|
||||
expect(init?.method).toBe('POST')
|
||||
expect(init?.credentials).toBe('same-origin')
|
||||
expect(init?.headers).toMatchObject({
|
||||
'X-CSRFToken': 'jeton',
|
||||
'Content-Type': 'application/json',
|
||||
})
|
||||
expect(JSON.parse(init?.body as string)).toEqual({ address: 'Place de l’Université 1' })
|
||||
})
|
||||
|
||||
it("n'envoie pas de jeton CSRF sur un GET", async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, {}))
|
||||
await api.me()
|
||||
expect(fetch.mock.calls[0]![1]?.headers).not.toHaveProperty('X-CSRFToken')
|
||||
})
|
||||
|
||||
it('accepte une réponse 204 sans corps', async () => {
|
||||
mockFetch(new Response(null, { status: 204 }))
|
||||
await expect(api.logout()).resolves.toBeUndefined()
|
||||
})
|
||||
|
||||
it('lève une ApiError avec le statut, le message et le code', async () => {
|
||||
mockFetch(jsonResponse(404, { code: 'address_not_found', detail: 'Adresse introuvable.' }))
|
||||
const error = await api.assess('nulle part').catch((e) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect(error.status).toBe(404)
|
||||
expect(error.code).toBe('address_not_found')
|
||||
expect(error.message).toBe('Adresse introuvable.')
|
||||
})
|
||||
|
||||
it('gère une erreur sans corps JSON', async () => {
|
||||
mockFetch(new Response('<html>403</html>', { status: 403 }))
|
||||
const error = await api.me().catch((e) => e)
|
||||
expect(error).toBeInstanceOf(ApiError)
|
||||
expect(error.message).toBe('HTTP 403')
|
||||
expect(error.code).toBeUndefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,108 @@
|
||||
import { describe, expect, it } from 'vitest'
|
||||
|
||||
import AddressForm from '@/components/AddressForm.vue'
|
||||
import DetailList from '@/components/DetailList.vue'
|
||||
import InfoTabs from '@/components/InfoTabs.vue'
|
||||
import ReferenceList from '@/components/ReferenceList.vue'
|
||||
|
||||
import { factor, mountWithPlugins } from './helpers'
|
||||
|
||||
describe('DetailList', () => {
|
||||
it('affiche une pastille rouge pour un dépassement et verte sinon', () => {
|
||||
const wrapper = mountWithPlugins(DetailList, {
|
||||
props: {
|
||||
details: [
|
||||
{ label: 'PM2,5', value: '7,1 µg/m³ (seuil 5)', status: 'exceeded' },
|
||||
{ label: 'PM10', value: '12,0 µg/m³ (seuil 15)', status: 'ok' },
|
||||
{ label: 'O₃', value: '50,1 µg/m³' },
|
||||
],
|
||||
},
|
||||
})
|
||||
const rows = wrapper.findAll('.detail-row')
|
||||
expect(rows).toHaveLength(3)
|
||||
expect(rows[0]!.find('.dot').classes()).toContain('level-4')
|
||||
expect(rows[0]!.text()).toContain('(dépassé)')
|
||||
expect(rows[1]!.find('.dot').classes()).toContain('level-1')
|
||||
expect(rows[2]!.find('.dot').exists()).toBe(false)
|
||||
})
|
||||
|
||||
it("n'affiche rien sans détail", () => {
|
||||
expect(
|
||||
mountWithPlugins(DetailList, { props: { details: [] } })
|
||||
.find('dl')
|
||||
.exists(),
|
||||
).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('InfoTabs', () => {
|
||||
it('affiche les effets sur la santé par défaut, une ligne par puce', () => {
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||
expect(wrapper.find('[aria-selected="true"]').text()).toBe('Effets sur la santé')
|
||||
expect(wrapper.findAll('.bullets li').map((li) => li.text())).toEqual([
|
||||
'Gêne, perturbation du sommeil',
|
||||
'Effets cardiovasculaires',
|
||||
])
|
||||
})
|
||||
|
||||
it('change d’onglet', async () => {
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs: factor().tabs } })
|
||||
const [, actions, legend] = wrapper.findAll('[role="tab"]')
|
||||
|
||||
await actions!.trigger('click')
|
||||
expect(actions!.attributes('aria-selected')).toBe('true')
|
||||
expect(wrapper.find('.bullets').text()).toBe('Isolation acoustique')
|
||||
|
||||
await legend!.trigger('click')
|
||||
expect(wrapper.find('.scale').text()).toBe('< 55 dB')
|
||||
expect(wrapper.find('.source').text()).toBe('Source : WalOnMap')
|
||||
})
|
||||
|
||||
it('indique un contenu en attente de validation', () => {
|
||||
const tabs = { ...factor().tabs, health_effects: '' }
|
||||
const wrapper = mountWithPlugins(InfoTabs, { props: { tabs } })
|
||||
expect(wrapper.find('.empty').text()).toContain('en cours de validation')
|
||||
})
|
||||
})
|
||||
|
||||
describe('ReferenceList', () => {
|
||||
it('numérote les références et ouvre les liens dans un nouvel onglet', () => {
|
||||
const wrapper = mountWithPlugins(ReferenceList, {
|
||||
props: {
|
||||
references: [
|
||||
{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' },
|
||||
{ n: 2, title: 'Canopea 2021', url: '' },
|
||||
],
|
||||
},
|
||||
})
|
||||
expect(wrapper.text()).toContain('1. EEA 2020')
|
||||
expect(wrapper.text()).toContain('2. Canopea 2021')
|
||||
const link = wrapper.find('a')
|
||||
expect(link.attributes('target')).toBe('_blank')
|
||||
expect(link.attributes('rel')).toContain('noopener')
|
||||
})
|
||||
|
||||
it("n'affiche rien sans référence", () => {
|
||||
const wrapper = mountWithPlugins(ReferenceList, { props: { references: [] } })
|
||||
expect(wrapper.find('.references').exists()).toBe(false)
|
||||
})
|
||||
})
|
||||
|
||||
describe('AddressForm', () => {
|
||||
it("émet l'adresse sans espaces superflus", async () => {
|
||||
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||
await wrapper.find('input').setValue(' Rue de la Loi 16, 1000 Bruxelles ')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
expect(wrapper.emitted('submit')).toEqual([['Rue de la Loi 16, 1000 Bruxelles']])
|
||||
})
|
||||
|
||||
it('désactive le bouton sans adresse ou pendant le chargement', async () => {
|
||||
const wrapper = mountWithPlugins(AddressForm, { props: { loading: false } })
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||
await wrapper.find('input').setValue('Rue')
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeUndefined()
|
||||
await wrapper.setProps({ loading: true })
|
||||
expect(wrapper.find('button').text()).toBe('Analyse…')
|
||||
expect(wrapper.find('button').attributes('disabled')).toBeDefined()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,77 @@
|
||||
import { mount, type ComponentMountingOptions } from '@vue/test-utils'
|
||||
import { vi } from 'vitest'
|
||||
import type { Component } from 'vue'
|
||||
import { createMemoryHistory, createRouter } from 'vue-router'
|
||||
|
||||
import type { Assessment, FactorResult, User } from '@/api/types'
|
||||
import i18n from '@/i18n'
|
||||
import { routes } from '@/router'
|
||||
|
||||
export const USER: User = {
|
||||
email: 'medecin@exemple.be',
|
||||
first_name: 'Jean',
|
||||
last_name: 'Dupont',
|
||||
roles: ['Médecin'],
|
||||
is_staff: false,
|
||||
}
|
||||
|
||||
export function factor(overrides: Partial<FactorResult> = {}): FactorResult {
|
||||
return {
|
||||
code: 'noise',
|
||||
label: 'Pollution sonore',
|
||||
status: 'ok',
|
||||
level: 1,
|
||||
color: 'green',
|
||||
summary: 'moins de 55 dB (Lden)',
|
||||
details: [{ label: 'Route', value: 'moins de 55 dB' }],
|
||||
tabs: {
|
||||
health_effects: 'Gêne, perturbation du sommeil\nEffets cardiovasculaires',
|
||||
actions: 'Isolation acoustique',
|
||||
legend: {
|
||||
source: 'WalOnMap',
|
||||
text: '',
|
||||
scale: [{ level: 1, color: 'green', label: '< 55 dB' }],
|
||||
},
|
||||
},
|
||||
references: [{ n: 1, title: 'EEA 2020', url: 'https://eea.europa.eu' }],
|
||||
...overrides,
|
||||
}
|
||||
}
|
||||
|
||||
export const ASSESSMENT: Assessment = {
|
||||
location: { lat: 50.668, lon: 4.617, region: 'WAL' },
|
||||
factors: [
|
||||
factor(),
|
||||
factor({ code: 'radon', label: 'Radon', status: 'unavailable', level: null, color: null }),
|
||||
],
|
||||
}
|
||||
|
||||
/** Réponse JSON simulée pour `fetch`. */
|
||||
export function jsonResponse(status: number, body?: unknown): Response {
|
||||
return new Response(body === undefined ? null : JSON.stringify(body), {
|
||||
status,
|
||||
headers: { 'Content-Type': 'application/json' },
|
||||
})
|
||||
}
|
||||
|
||||
export function mockFetch(...responses: Response[]) {
|
||||
const fn = vi.fn<typeof fetch>()
|
||||
for (const response of responses) fn.mockResolvedValueOnce(response)
|
||||
vi.stubGlobal('fetch', fn)
|
||||
return fn
|
||||
}
|
||||
|
||||
export function makeRouter() {
|
||||
return createRouter({ history: createMemoryHistory(), routes })
|
||||
}
|
||||
|
||||
export function mountWithPlugins<C extends Component>(
|
||||
component: C,
|
||||
options: ComponentMountingOptions<C> & { router?: ReturnType<typeof makeRouter> } = {},
|
||||
) {
|
||||
const { router = makeRouter(), ...rest } = options
|
||||
return mount(component, {
|
||||
...rest,
|
||||
global: { plugins: [i18n, router], ...rest.global },
|
||||
} as ComponentMountingOptions<C>)
|
||||
}
|
||||
@@ -0,0 +1,43 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { resetAuth } from '@/composables/useAuth'
|
||||
import { createAppRouter } from '@/router'
|
||||
|
||||
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
async function navigate(path: string) {
|
||||
const router = createAppRouter()
|
||||
await router.push(path)
|
||||
return router.currentRoute.value
|
||||
}
|
||||
|
||||
describe('garde de navigation', () => {
|
||||
it("redirige un visiteur vers /login depuis l'évaluation", async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
expect((await navigate('/')).name).toBe('login')
|
||||
})
|
||||
|
||||
it('laisse un utilisateur connecté accéder à l’évaluation', async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
expect((await navigate('/')).name).toBe('assessment')
|
||||
})
|
||||
|
||||
it('renvoie un utilisateur connecté de /login vers l’évaluation', async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
expect((await navigate('/login')).name).toBe('assessment')
|
||||
})
|
||||
|
||||
it('affiche la page 404 pour une route inconnue', async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
const route = await navigate('/nimporte/quoi')
|
||||
expect(route.name).toBe('not-found')
|
||||
})
|
||||
|
||||
it('laisse la page 403 publique', async () => {
|
||||
mockFetch(jsonResponse(403, {}))
|
||||
expect((await navigate('/403')).name).toBe('forbidden')
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,61 @@
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { ApiError } from '@/api/client'
|
||||
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||
|
||||
import { jsonResponse, mockFetch, USER } from './helpers'
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
describe('useAuth', () => {
|
||||
it("charge l'utilisateur connecté", async () => {
|
||||
mockFetch(jsonResponse(200, USER))
|
||||
const { load, user, isAuthenticated } = useAuth()
|
||||
await load()
|
||||
expect(user.value).toEqual(USER)
|
||||
expect(isAuthenticated.value).toBe(true)
|
||||
})
|
||||
|
||||
it('considère un 403 comme « non connecté »', async () => {
|
||||
mockFetch(jsonResponse(403, { detail: 'Non authentifié.' }))
|
||||
const { load, isAuthenticated } = useAuth()
|
||||
await expect(load()).resolves.toBeNull()
|
||||
expect(isAuthenticated.value).toBe(false)
|
||||
})
|
||||
|
||||
it('propage les autres erreurs', async () => {
|
||||
mockFetch(jsonResponse(500, {}))
|
||||
await expect(useAuth().load()).rejects.toBeInstanceOf(ApiError)
|
||||
})
|
||||
|
||||
it("n'interroge l'API qu'une fois", async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, USER))
|
||||
const { load } = useAuth()
|
||||
await load()
|
||||
await load()
|
||||
expect(fetch).toHaveBeenCalledTimes(1)
|
||||
})
|
||||
|
||||
it("connecte puis recharge l'utilisateur (nouveau jeton CSRF)", async () => {
|
||||
const fetch = mockFetch(
|
||||
jsonResponse(200, { mfa_required: false, user: USER }),
|
||||
jsonResponse(200, USER),
|
||||
)
|
||||
const { login, user } = useAuth()
|
||||
await login('medecin@exemple.be', 'secret')
|
||||
expect(user.value).toEqual(USER)
|
||||
expect(fetch.mock.calls.map(([url]) => url)).toEqual([
|
||||
'/api/v1/auth/login/',
|
||||
'/api/v1/auth/me/',
|
||||
])
|
||||
})
|
||||
|
||||
it('déconnecte même si la requête échoue', async () => {
|
||||
mockFetch(jsonResponse(200, USER), jsonResponse(500, {}), jsonResponse(403, {}))
|
||||
const { load, logout, user } = useAuth()
|
||||
await load()
|
||||
await logout().catch(() => {})
|
||||
expect(user.value).toBeNull()
|
||||
})
|
||||
})
|
||||
@@ -0,0 +1,151 @@
|
||||
import { flushPromises } from '@vue/test-utils'
|
||||
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
|
||||
|
||||
import { resetAuth, useAuth } from '@/composables/useAuth'
|
||||
import AssessmentView from '@/views/AssessmentView.vue'
|
||||
import ErrorView from '@/views/ErrorView.vue'
|
||||
import LoginView from '@/views/LoginView.vue'
|
||||
|
||||
import { ASSESSMENT, jsonResponse, makeRouter, mockFetch, mountWithPlugins, USER } from './helpers'
|
||||
|
||||
const stubs = { ResultMap: { template: '<div class="map-stub" />', props: ['location'] } }
|
||||
|
||||
beforeEach(resetAuth)
|
||||
afterEach(() => vi.unstubAllGlobals())
|
||||
|
||||
async function analyse(
|
||||
wrapper: ReturnType<typeof mountWithPlugins>,
|
||||
address = 'Place de l’Université 1',
|
||||
) {
|
||||
await wrapper.find('#address').setValue(address)
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
}
|
||||
|
||||
describe('AssessmentView', () => {
|
||||
it('affiche l’adresse reconnue et une carte par facteur', async () => {
|
||||
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(wrapper.find('[role="status"]').text()).toBe(
|
||||
'Adresse reconnue : Place de l’Université 1 — Région wallonne',
|
||||
)
|
||||
expect(wrapper.findAll('.factor-card')).toHaveLength(2)
|
||||
})
|
||||
|
||||
it.each([
|
||||
[404, { code: 'address_not_found' }, 'Adresse introuvable'],
|
||||
[422, { code: 'out_of_coverage' }, 'hors couverture'],
|
||||
[503, { code: 'geocoding_unavailable' }, 'géocodage est indisponible'],
|
||||
[429, { detail: 'Throttled' }, "Trop d'analyses"],
|
||||
[500, {}, "L'analyse a échoué"],
|
||||
])('erreur %i → message adapté', async (status, body, message) => {
|
||||
mockFetch(jsonResponse(status, body))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(wrapper.find('[role="alert"]').text()).toContain(message)
|
||||
expect(wrapper.findAll('.factor-card')).toHaveLength(0)
|
||||
})
|
||||
|
||||
it('« Réessayer » relance l’analyse de la même adresse', async () => {
|
||||
const fetch = mockFetch(jsonResponse(200, ASSESSMENT), jsonResponse(200, ASSESSMENT))
|
||||
const wrapper = mountWithPlugins(AssessmentView, { global: { stubs } })
|
||||
await analyse(wrapper, 'Rue de la Loi 16, 1000 Bruxelles')
|
||||
|
||||
await wrapper.find('.factor-card.unavailable button').trigger('click')
|
||||
await flushPromises()
|
||||
|
||||
expect(fetch).toHaveBeenCalledTimes(2)
|
||||
expect(JSON.parse(fetch.mock.calls[1]![1]!.body as string)).toEqual({
|
||||
address: 'Rue de la Loi 16, 1000 Bruxelles',
|
||||
})
|
||||
})
|
||||
|
||||
it('session expirée : retour à la connexion', async () => {
|
||||
mockFetch(jsonResponse(403, {}), jsonResponse(204), jsonResponse(403, {}))
|
||||
const router = makeRouter()
|
||||
const push = vi.spyOn(router, 'push')
|
||||
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||
|
||||
await analyse(wrapper)
|
||||
|
||||
expect(push).toHaveBeenCalledWith({ name: 'login' })
|
||||
})
|
||||
|
||||
it("ne place pas l'adresse dans l'URL ni dans le stockage du navigateur", async () => {
|
||||
mockFetch(jsonResponse(200, ASSESSMENT))
|
||||
const router = makeRouter()
|
||||
const wrapper = mountWithPlugins(AssessmentView, { router, global: { stubs } })
|
||||
|
||||
await analyse(wrapper, 'Rue Secrète 1, 1348 Louvain-la-Neuve')
|
||||
|
||||
expect(router.currentRoute.value.fullPath).not.toContain('Secr')
|
||||
expect(JSON.stringify({ ...localStorage, ...sessionStorage })).not.toContain('Secr')
|
||||
})
|
||||
})
|
||||
|
||||
describe('LoginView', () => {
|
||||
it("affiche le message d'erreur du serveur", async () => {
|
||||
mockFetch(jsonResponse(400, { detail: 'E-mail ou mot de passe incorrect.' }))
|
||||
const wrapper = mountWithPlugins(LoginView)
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('mauvais')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(wrapper.find('[role="alert"]').text()).toBe('E-mail ou mot de passe incorrect.')
|
||||
})
|
||||
|
||||
it('redirige vers l’évaluation après connexion', async () => {
|
||||
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||
const router = makeRouter()
|
||||
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||
const wrapper = mountWithPlugins(LoginView, { router })
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('un-mot-de-passe-solide')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(useAuth().user.value).toEqual(USER)
|
||||
expect(push).toHaveBeenCalledWith({ name: 'assessment' })
|
||||
})
|
||||
|
||||
it('suit le paramètre next interne et ignore une URL externe', async () => {
|
||||
for (const [next, expected] of [
|
||||
['/403', '/403'],
|
||||
['https://evil.example', { name: 'assessment' }],
|
||||
] as const) {
|
||||
resetAuth()
|
||||
mockFetch(jsonResponse(200, { mfa_required: false, user: USER }), jsonResponse(200, USER))
|
||||
const router = makeRouter()
|
||||
await router.push({ name: 'login', query: { next } }).catch(() => {})
|
||||
const push = vi.spyOn(router, 'push').mockResolvedValue(undefined)
|
||||
const wrapper = mountWithPlugins(LoginView, { router })
|
||||
|
||||
await wrapper.find('#email').setValue('medecin@exemple.be')
|
||||
await wrapper.find('#password').setValue('x')
|
||||
await wrapper.find('form').trigger('submit')
|
||||
await flushPromises()
|
||||
|
||||
expect(push).toHaveBeenCalledWith(expected)
|
||||
}
|
||||
})
|
||||
})
|
||||
|
||||
describe('ErrorView', () => {
|
||||
it.each([
|
||||
[404, 'Page introuvable'],
|
||||
[403, 'Accès refusé'],
|
||||
] as const)('%i', (code, title) => {
|
||||
const wrapper = mountWithPlugins(ErrorView, { props: { code } })
|
||||
expect(wrapper.find('.error-code').text()).toBe(String(code))
|
||||
expect(wrapper.find('h1').text()).toBe(title)
|
||||
expect(wrapper.find('a').attributes('href')).toBe('/')
|
||||
})
|
||||
})
|
||||
Reference in new issue
Block a user