|
1 | | -import { describe, expect, test } from 'vitest' |
| 1 | +import { describe, expect, test, vi } from 'vitest' |
2 | 2 | import { createMemoryHistory } from '../src' |
3 | 3 |
|
4 | 4 | describe('createMemoryHistory', () => { |
@@ -76,4 +76,59 @@ describe('createMemoryHistory', () => { |
76 | 76 | history.push('/c', { i: 3 }) |
77 | 77 | expect((history.location.state as any).i).toBe(3) |
78 | 78 | }) |
| 79 | + |
| 80 | + test('block prevents navigation', async () => { |
| 81 | + const history = createMemoryHistory({ initialEntries: ['/'] }) |
| 82 | + const blockerFn = vi.fn(() => true) // Always block |
| 83 | + |
| 84 | + const unblock = history.block({ |
| 85 | + blockerFn, |
| 86 | + enableBeforeUnload: false, |
| 87 | + }) |
| 88 | + |
| 89 | + await history.push('/a') |
| 90 | + |
| 91 | + // Navigation should be blocked |
| 92 | + expect(history.location.pathname).toBe('/') |
| 93 | + expect(blockerFn).toHaveBeenCalled() |
| 94 | + |
| 95 | + unblock() |
| 96 | + }) |
| 97 | + |
| 98 | + test('block allows navigation when blockerFn returns false', async () => { |
| 99 | + const history = createMemoryHistory({ initialEntries: ['/'] }) |
| 100 | + const blockerFn = vi.fn(() => false) // Never block |
| 101 | + |
| 102 | + const unblock = history.block({ |
| 103 | + blockerFn, |
| 104 | + enableBeforeUnload: false, |
| 105 | + }) |
| 106 | + |
| 107 | + await history.push('/a') |
| 108 | + |
| 109 | + // Navigation should proceed |
| 110 | + expect(history.location.pathname).toBe('/a') |
| 111 | + expect(blockerFn).toHaveBeenCalled() |
| 112 | + |
| 113 | + unblock() |
| 114 | + }) |
| 115 | + |
| 116 | + test('unblock removes blocker', async () => { |
| 117 | + const history = createMemoryHistory({ initialEntries: ['/'] }) |
| 118 | + const blockerFn = vi.fn(() => true) // Always block |
| 119 | + |
| 120 | + const unblock = history.block({ |
| 121 | + blockerFn, |
| 122 | + enableBeforeUnload: false, |
| 123 | + }) |
| 124 | + |
| 125 | + // Unblock immediately |
| 126 | + unblock() |
| 127 | + |
| 128 | + await history.push('/a') |
| 129 | + |
| 130 | + // Navigation should proceed since blocker was removed |
| 131 | + expect(history.location.pathname).toBe('/a') |
| 132 | + expect(blockerFn).not.toHaveBeenCalled() |
| 133 | + }) |
79 | 134 | }) |
0 commit comments