forked from sheyman546/Grainlify-Frontend
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathi18n.test.tsx
More file actions
186 lines (161 loc) · 6.13 KB
/
Copy pathi18n.test.tsx
File metadata and controls
186 lines (161 loc) · 6.13 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
import type { ReactNode } from 'react'
import { describe, it, expect, vi } from 'vitest'
import { render, renderHook, screen, waitFor } from '@testing-library/react'
import { FormattedMessage, FormattedNumber, ReactIntlErrorCode } from 'react-intl'
import {
I18nProvider,
handleIntlError,
useTranslation,
resolveMessages,
en,
type Locale,
type Messages,
type MessageId,
} from './index'
// `useLandingStats` reaches the network through the API client; stub it so the
// hook's locale-aware number formatting can be asserted in isolation.
vi.mock('../api/client', () => ({ getLandingStats: vi.fn() }))
import { getLandingStats } from '../api/client'
import { useLandingStats } from '../hooks/useLandingStats'
const mockGetLandingStats = getLandingStats as unknown as ReturnType<typeof vi.fn>
/** Wraps a hook/component under test in the real {@link I18nProvider}. */
function wrapper({ children }: { children: ReactNode }) {
return <I18nProvider>{children}</I18nProvider>
}
describe('i18n catalog & fallback', () => {
it('exposes the full English base for the default locale', () => {
const msgs = resolveMessages('en')
expect(msgs).toEqual(en)
;(Object.keys(en) as MessageId[]).forEach((key) => {
expect(msgs[key]).toBe(en[key])
})
})
it('layers a partial locale over English, falling back per missing key', () => {
const partial: Partial<Messages> = { 'dashboardNav.discover': 'Descubrir' }
const msgs = resolveMessages('es' as Locale, { es: partial })
// Provided key uses the locale value…
expect(msgs['dashboardNav.discover']).toBe('Descubrir')
// …every other key falls back to its English value.
expect(msgs['dashboardNav.browse']).toBe('Browse')
expect(msgs['landingNav.features']).toBe('Features')
})
it('falls back entirely to English for an unknown locale', () => {
expect(resolveMessages('zz' as Locale)).toEqual(en)
})
})
describe('handleIntlError policy', () => {
it('swallows non-fatal missing-translation / missing-data errors', () => {
expect(() =>
handleIntlError({ code: ReactIntlErrorCode.MISSING_TRANSLATION } as never)
).not.toThrow()
expect(() => handleIntlError({ code: ReactIntlErrorCode.MISSING_DATA } as never)).not.toThrow()
})
it('re-throws unexpected error codes to surface real bugs', () => {
expect(() =>
handleIntlError({
code: ReactIntlErrorCode.FORMAT_ERROR,
message: 'bad pattern',
} as never)
).toThrow()
})
})
describe('useTranslation', () => {
it('resolves typed keys to their English strings and exposes the locale', () => {
const { result } = renderHook(() => useTranslation(), { wrapper })
expect(result.current.t('dashboardNav.discover')).toBe('Discover')
expect(result.current.t('landingNav.getStarted')).toBe('Get Started')
expect(result.current.locale).toBe('en')
})
})
describe('missing key rendering', () => {
it('renders the English defaultMessage for an unknown id without throwing', () => {
render(
<I18nProvider>
<FormattedMessage
id={'totally.missing.key' as MessageId}
defaultMessage="English fallback"
/>
</I18nProvider>
)
expect(screen.getByText('English fallback')).toBeInTheDocument()
})
})
describe('number formatting', () => {
it('formats currency for the active locale via <FormattedNumber>', () => {
render(
<I18nProvider>
<FormattedNumber
value={1234567.89}
style="currency"
currency="USD"
maximumFractionDigits={0}
/>
</I18nProvider>
)
expect(screen.getByText('$1,234,568')).toBeInTheDocument()
})
it('wires the provider locale into useLandingStats number formatting', async () => {
mockGetLandingStats.mockResolvedValue({
active_projects: 1234,
contributors: 56789,
grants_distributed_usd: 9876543,
})
const { result } = renderHook(() => useLandingStats(), { wrapper })
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(result.current.display.activeProjects).toBe('1,234')
expect(result.current.display.contributors).toBe('56,789')
expect(result.current.display.grantsDistributed).toBe('$9,876,543')
})
it('shows placeholders and surfaces an error when stats fail to load', async () => {
mockGetLandingStats.mockRejectedValue(new Error('boom'))
const { result } = renderHook(() => useLandingStats(), { wrapper })
await waitFor(() => expect(result.current.isLoading).toBe(false))
expect(result.current.display.activeProjects).toBe('—')
expect(result.current.display.grantsDistributed).toBe('—')
expect(result.current.error).toBe('boom')
})
})
describe('plural formatting', () => {
it('selects the correct ICU plural branch', () => {
const message = '{count, plural, one {# project} other {# projects}}'
const { rerender } = render(
<I18nProvider>
<FormattedMessage
id={'plural.demo' as MessageId}
defaultMessage={message}
values={{ count: 1 }}
/>
</I18nProvider>
)
expect(screen.getByText('1 project')).toBeInTheDocument()
rerender(
<I18nProvider>
<FormattedMessage
id={'plural.demo' as MessageId}
defaultMessage={message}
values={{ count: 5 }}
/>
</I18nProvider>
)
expect(screen.getByText('5 projects')).toBeInTheDocument()
})
})
describe('security — interpolation is text-only', () => {
it('renders interpolated untrusted markup as inert text, never as DOM', () => {
const evil = '<img src=x onerror="window.__pwned = true">'
const { container } = render(
<I18nProvider>
<FormattedMessage
id={'greeting.demo' as MessageId}
defaultMessage="Hello, {name}!"
values={{ name: evil }}
/>
</I18nProvider>
)
// No element was injected — the payload never became part of the DOM tree.
expect(container.querySelector('img')).toBeNull()
expect((window as unknown as Record<string, unknown>).__pwned).toBeUndefined()
// The raw markup is present verbatim, as a text node.
expect(container.textContent).toBe(`Hello, ${evil}!`)
})
})