Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions packages/history/src/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -593,6 +593,11 @@ export function createMemoryHistory(

const getLocation = () => parseHref(entries[index]!, states[index])

let blockers: Array<NavigationBlocker> = []
const _getBlockers = () => blockers
const _setBlockers = (newBlockers: Array<NavigationBlocker>) =>
(blockers = newBlockers)

return createHistory({
getLocation,
getLength: () => entries.length,
Expand Down Expand Up @@ -620,6 +625,8 @@ export function createMemoryHistory(
index = Math.min(Math.max(index + n, 0), entries.length - 1)
},
createHref: (path) => path,
getBlockers: _getBlockers,
setBlockers: _setBlockers,
})
}

Expand Down
57 changes: 56 additions & 1 deletion packages/history/tests/createMemoryHistory.test.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { describe, expect, test } from 'vitest'
import { describe, expect, test, vi } from 'vitest'
import { createMemoryHistory } from '../src'

describe('createMemoryHistory', () => {
Expand Down Expand Up @@ -76,4 +76,59 @@ describe('createMemoryHistory', () => {
history.push('/c', { i: 3 })
expect((history.location.state as any).i).toBe(3)
})

test('block prevents navigation', async () => {
const history = createMemoryHistory({ initialEntries: ['/'] })
const blockerFn = vi.fn(() => true) // Always block

const unblock = history.block({
blockerFn,
enableBeforeUnload: false,
})

await history.push('/a')

// Navigation should be blocked
expect(history.location.pathname).toBe('/')
expect(blockerFn).toHaveBeenCalled()

unblock()
})

test('block allows navigation when blockerFn returns false', async () => {
const history = createMemoryHistory({ initialEntries: ['/'] })
const blockerFn = vi.fn(() => false) // Never block

const unblock = history.block({
blockerFn,
enableBeforeUnload: false,
})

await history.push('/a')

// Navigation should proceed
expect(history.location.pathname).toBe('/a')
expect(blockerFn).toHaveBeenCalled()

unblock()
})

test('unblock removes blocker', async () => {
const history = createMemoryHistory({ initialEntries: ['/'] })
const blockerFn = vi.fn(() => true) // Always block

const unblock = history.block({
blockerFn,
enableBeforeUnload: false,
})

// Unblock immediately
unblock()

await history.push('/a')

// Navigation should proceed since blocker was removed
expect(history.location.pathname).toBe('/a')
expect(blockerFn).not.toHaveBeenCalled()
})
})
Loading