testsAndMisc-archive/TS/battery-status/src/useBeforeUnload.test.ts
Krzysztof kuhy Rudnicki 01091c09ce Add tests and fix pre-commit issues across all projects
- C/lichess_random_engine, vocabulary_curve, misc/split,
  1dvelocitysimulator, opening_learner: test suites added
- CPP/miscelanious: tests added
- TS/battery-status, champions_leauge_scores, two-inputs: tests added
- python_pkg/fm24_searcher, wake_alarm: new packages added
- Fix ruff/cppcheck/eslint/clang-format failures
- Update .gitignore for C/C++ build artifacts
2026-04-12 20:45:24 +02:00

58 lines
2.1 KiB
TypeScript

import { describe, it, expect } from 'vitest'
import { useBeforeUnload } from './useBeforeUnload'
import { renderHook, cleanup } from '@testing-library/react'
describe('useBeforeUnload', () => {
afterEach(() => {
cleanup()
})
it('registers beforeunload handler when enabled', () => {
const addSpy = vi.spyOn(window, 'addEventListener')
renderHook(() => useBeforeUnload(true, 'Leave?'))
expect(addSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function))
addSpy.mockRestore()
})
it('does not register handler when disabled', () => {
const addSpy = vi.spyOn(window, 'addEventListener')
renderHook(() => useBeforeUnload(false, 'Leave?'))
expect(addSpy).not.toHaveBeenCalledWith('beforeunload', expect.any(Function))
addSpy.mockRestore()
})
it('removes handler on unmount', () => {
const removeSpy = vi.spyOn(window, 'removeEventListener')
const { unmount } = renderHook(() => useBeforeUnload(true, 'Leave?'))
unmount()
expect(removeSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function))
removeSpy.mockRestore()
})
it('handler sets returnValue and prevents default', () => {
let captured: ((e: BeforeUnloadEvent) => void) | undefined
const addSpy = vi.spyOn(window, 'addEventListener').mockImplementation((type, handler) => {
if (type === 'beforeunload') captured = handler as (e: BeforeUnloadEvent) => void
})
renderHook(() => useBeforeUnload(true, 'Stay here'))
expect(captured).toBeDefined()
const event = new Event('beforeunload') as BeforeUnloadEvent
const preventSpy = vi.spyOn(event, 'preventDefault')
captured!(event)
expect(preventSpy).toHaveBeenCalled()
// jsdom may coerce returnValue to boolean; just verify it was set
expect(event.returnValue).toBeDefined()
addSpy.mockRestore()
})
it('uses default values when called with no arguments', () => {
const addSpy = vi.spyOn(window, 'addEventListener')
renderHook(() => useBeforeUnload())
expect(addSpy).toHaveBeenCalledWith('beforeunload', expect.any(Function))
addSpy.mockRestore()
})
})