d3ro-voice/packages/i18n/__tests__/i18n-provider.test.tsx

426 lines
13 KiB
TypeScript

import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest'
interface HookStateSlot {
kind: 'state'
value: unknown
setter: (next: unknown) => void
}
interface HookRefSlot {
kind: 'ref'
ref: { current: unknown }
}
interface HookMemoSlot {
kind: 'memo'
deps: readonly unknown[] | undefined
value: unknown
}
interface HookEffectSlot {
kind: 'effect'
deps: readonly unknown[] | undefined
create: () => void | (() => void)
cleanup: (() => void) | undefined
}
type HookSlot = HookStateSlot | HookRefSlot | HookMemoSlot | HookEffectSlot
interface HarnessContext<T> {
defaultValue: T
currentValue: T
Provider: string
}
interface HarnessState {
mounted: boolean
unmountedSetStateCalls: number
cursor: number
slots: HookSlot[]
pendingEffects: number[]
renderFn: (() => unknown) | null
lastContextValue: unknown
}
const reactHarness = vi.hoisted(() => {
const state: HarnessState = {
mounted: false,
unmountedSetStateCalls: 0,
cursor: 0,
slots: [],
pendingEffects: [],
renderFn: null,
lastContextValue: undefined,
}
function depsChanged(
prev: readonly unknown[] | undefined,
next: readonly unknown[] | undefined,
): boolean {
if (prev === undefined || next === undefined) return true
if (prev.length !== next.length) return true
for (let i = 0; i < next.length; i += 1) {
if (!Object.is(prev[i], next[i])) return true
}
return false
}
function flushEffects(): void {
const indices = state.pendingEffects.splice(0)
for (const idx of indices) {
const slot = state.slots[idx]
if (!slot || slot.kind !== 'effect') continue
if (slot.cleanup) {
slot.cleanup()
slot.cleanup = undefined
}
const cleanup = slot.create()
slot.cleanup = typeof cleanup === 'function' ? cleanup : undefined
}
}
function renderCycle(): void {
if (!state.mounted || !state.renderFn) return
state.cursor = 0
const element = state.renderFn() as { props?: { value?: unknown } } | undefined
if (element?.props && 'value' in element.props) {
state.lastContextValue = element.props.value
}
flushEffects()
}
function reset(): void {
for (const slot of state.slots) {
if (slot.kind === 'effect' && slot.cleanup) {
slot.cleanup()
}
}
state.mounted = false
state.unmountedSetStateCalls = 0
state.cursor = 0
state.slots = []
state.pendingEffects = []
state.renderFn = null
state.lastContextValue = undefined
}
function mount(renderFn: () => unknown): void {
reset()
state.mounted = true
state.renderFn = renderFn
renderCycle()
}
function rerender(renderFn?: () => unknown): void {
if (renderFn) state.renderFn = renderFn
renderCycle()
}
function unmount(): void {
state.mounted = false
for (const slot of state.slots) {
if (slot.kind === 'effect' && slot.cleanup) {
slot.cleanup()
slot.cleanup = undefined
}
}
}
const reactMock = {
createContext<T>(defaultValue: T): HarnessContext<T> {
return {
defaultValue,
currentValue: defaultValue,
Provider: 'HarnessContextProvider',
}
},
useContext<T>(ctx: HarnessContext<T>): T {
return (state.lastContextValue as T | undefined) ?? ctx.defaultValue
},
useState<T>(initial: T | (() => T)): [T, (next: T | ((prev: T) => T)) => void] {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'state') {
return [existing.value as T, existing.setter as (next: T | ((prev: T) => T)) => void]
}
const initialVal = typeof initial === 'function' ? (initial as () => T)() : initial
const slot: HookStateSlot = {
kind: 'state',
value: initialVal,
setter: (next: unknown) => {
if (!state.mounted) {
state.unmountedSetStateCalls += 1
return
}
const prev = slot.value as T
const resolved =
typeof next === 'function' ? (next as (p: T) => T)(prev) : (next as T)
if (Object.is(prev, resolved)) return
slot.value = resolved
renderCycle()
},
}
state.slots[idx] = slot
return [slot.value as T, slot.setter as (next: T | ((prev: T) => T)) => void]
},
useRef<T>(initial: T): { current: T } {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'ref') {
return existing.ref as { current: T }
}
const slot: HookRefSlot = { kind: 'ref', ref: { current: initial } }
state.slots[idx] = slot
return slot.ref as { current: T }
},
useMemo<T>(factory: () => T, deps?: readonly unknown[]): T {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'memo' && !depsChanged(existing.deps, deps)) {
return existing.value as T
}
const value = factory()
state.slots[idx] = { kind: 'memo', deps, value }
return value
},
useCallback<T extends (...args: never[]) => unknown>(fn: T, deps: readonly unknown[]): T {
const idx = state.cursor++
const existing = state.slots[idx]
if (existing && existing.kind === 'memo' && !depsChanged(existing.deps, deps)) {
return existing.value as T
}
state.slots[idx] = { kind: 'memo', deps, value: fn }
return fn
},
useEffect(create: () => void | (() => void), deps?: readonly unknown[]): void {
const idx = state.cursor++
const existing = state.slots[idx]
if (!existing || existing.kind !== 'effect') {
state.slots[idx] = { kind: 'effect', deps, create, cleanup: undefined }
state.pendingEffects.push(idx)
return
}
if (depsChanged(existing.deps, deps)) {
existing.deps = deps
existing.create = create
state.pendingEffects.push(idx)
}
},
}
return { state, mount, rerender, unmount, reset, reactMock }
})
vi.mock('react', () => ({
...reactHarness.reactMock,
default: reactHarness.reactMock,
}))
vi.mock('react/jsx-runtime', () => ({
Fragment: 'Fragment',
jsx: (type: unknown, props: unknown) => ({ type, props }),
jsxs: (type: unknown, props: unknown) => ({ type, props }),
}))
vi.mock('react/jsx-dev-runtime', () => ({
Fragment: 'Fragment',
jsxDEV: (type: unknown, props: unknown) => ({ type, props }),
}))
import {
I18nProvider as WebI18nProvider,
loadLocaleCatalog,
type I18nContextValue,
type I18nStorage,
} from '../src/index'
import { I18nProvider as NativeI18nProvider } from '../src/index.native'
interface Deferred<T> {
promise: Promise<T>
resolve: (value: T) => void
reject: (reason: unknown) => void
}
function createDeferred<T>(): Deferred<T> {
let resolve!: (value: T) => void
let reject!: (reason: unknown) => void
const promise = new Promise<T>((res, rej) => {
resolve = res
reject = rej
})
return { promise, resolve, reject }
}
async function flushAsyncTurns(): Promise<void> {
await Promise.resolve()
await Promise.resolve()
await new Promise<void>((resolve) => {
setImmediate(resolve)
})
}
const PROVIDERS = [
{ name: 'web(index.tsx)', Provider: WebI18nProvider },
{ name: 'native(index.native.tsx)', Provider: NativeI18nProvider },
] as const
describe.each(PROVIDERS)('I18nProvider 비동기 안전성 ($name)', ({ Provider }) => {
const unhandledReasons: unknown[] = []
const onUnhandled = (reason: unknown): void => {
unhandledReasons.push(reason)
}
beforeEach(() => {
unhandledReasons.length = 0
process.on('unhandledRejection', onUnhandled)
})
afterEach(() => {
reactHarness.reset()
process.off('unhandledRejection', onUnhandled)
})
it('storage_load_언마운트이후완료되면_setState를호출하지않는다', async () => {
const deferred = createDeferred<string | null>()
const storage: I18nStorage = {
load: () => deferred.promise,
save: () => {},
}
reactHarness.mount(() => Provider({ initialLocale: 'ko', storage, children: null }))
reactHarness.unmount()
deferred.resolve('en')
await flushAsyncTurns()
expect(reactHarness.state.unmountedSetStateCalls).toBe(0)
expect(unhandledReasons).toEqual([])
})
it('setLocale_저장소로드완료전사용자변경시_지연된로드가덮어쓰지않는다', async () => {
const deferred = createDeferred<string | null>()
const saved: string[] = []
const storage: I18nStorage = {
load: () => deferred.promise,
save: (next) => {
saved.push(next)
},
}
reactHarness.mount(() => Provider({ initialLocale: 'ko', storage, children: null }))
const ctxBefore = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxBefore.locale).toBe('ko')
ctxBefore.setLocale('ja')
const ctxAfterSet = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxAfterSet.locale).toBe('ja')
// 사용자가 언어를 바꾼 뒤 늦게 도착한 저장소 값은 무시되어야 한다
deferred.resolve('en')
await flushAsyncTurns()
const ctxAfterLoad = reactHarness.state.lastContextValue as I18nContextValue
expect(ctxAfterLoad.locale).toBe('ja')
expect(saved).toEqual(['ja'])
})
it('setLocale_인라인storage객체재렌더후로드가재실행되어도_사용자선택을유지한다', async () => {
const firstLoad = createDeferred<string | null>()
const secondLoad = createDeferred<string | null>()
let loadCount = 0
reactHarness.mount(() =>
Provider({
initialLocale: 'ko',
storage: {
load: () => {
loadCount += 1
return loadCount === 1 ? firstLoad.promise : secondLoad.promise
},
save: () => {},
},
children: null,
}),
)
const ctx = reactHarness.state.lastContextValue as I18nContextValue
ctx.setLocale('fr')
// 부모가 인라인 storage 객체로 재렌더링하더라도 사용자 선택('fr')이 유지되어야 한다
reactHarness.rerender(() =>
Provider({
initialLocale: 'ko',
storage: {
load: () => secondLoad.promise,
save: () => {},
},
children: null,
}),
)
firstLoad.resolve('en')
secondLoad.resolve('de')
await flushAsyncTurns()
const finalCtx = reactHarness.state.lastContextValue as I18nContextValue
expect(finalCtx.locale).toBe('fr')
})
it('storage_load와save가동기또는비동기로실패해도_unhandledRejection을발생시키지않는다', async () => {
const failingAsyncStorage: I18nStorage = {
load: () => Promise.reject(new Error('storage load failed')),
save: () => Promise.reject(new Error('storage save failed')),
}
reactHarness.mount(() =>
Provider({ initialLocale: 'ko', storage: failingAsyncStorage, children: null }),
)
const ctx = reactHarness.state.lastContextValue as I18nContextValue
ctx.setLocale('en')
await flushAsyncTurns()
expect((reactHarness.state.lastContextValue as I18nContextValue).locale).toBe('en')
expect(unhandledReasons).toEqual([])
const throwingSyncStorage: I18nStorage = {
load: () => {
throw new Error('sync load failure')
},
save: () => {
throw new Error('sync save failure')
},
}
reactHarness.mount(() =>
Provider({ initialLocale: 'en', storage: throwingSyncStorage, children: null }),
)
const syncCtx = reactHarness.state.lastContextValue as I18nContextValue
syncCtx.setLocale('de')
await flushAsyncTurns()
expect((reactHarness.state.lastContextValue as I18nContextValue).locale).toBe('de')
expect(unhandledReasons).toEqual([])
})
})
describe('loadLocaleCatalog 및 날짜 포맷 방어 (packages/i18n)', () => {
it('loadLocaleCatalog_동시호출시_중복로드를방지하고정상카탈로그를반환한다', async () => {
const [first, second] = await Promise.all([
loadLocaleCatalog('ja'),
loadLocaleCatalog('ja'),
])
expect(first['login.subtitle']).toBe('AI音声アシスタント')
expect(second).toBe(first)
})
it('I18nProvider_유효하지않은타임스탬프와날짜를전달해도_예외없이빈문자열을반환한다', () => {
reactHarness.mount(() => WebI18nProvider({ initialLocale: 'en', children: null }))
const ctx = reactHarness.state.lastContextValue as I18nContextValue
expect(ctx.formatDate(Number.NaN)).toBe('')
expect(ctx.formatTime(Number.POSITIVE_INFINITY)).toBe('')
expect(ctx.formatRelativeDate(Number.NaN)).toBe('')
expect(ctx.formatDate(new Date('invalid-date'))).toBe('')
expect(ctx.formatDate(1_700_000_000_000, { year: 'numeric' })).toBe('2023')
})
})