Skip to content
This repository was archived by the owner on Jul 6, 2025. It is now read-only.

Commit 740336f

Browse files
Craig Doremusije
authored andcommitted
test: redirect.ts tests
1 parent c90875c commit 740336f

File tree

1 file changed

+85
-0
lines changed

1 file changed

+85
-0
lines changed

framework/core/redirect_test.ts

Lines changed: 85 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,85 @@
1+
/**
2+
* NOTE: This test needs the --location cli flag set
3+
* see https://github.com/denoland/deno/blob/main/docs/runtime/location_api.md
4+
* and explanation below.
5+
*/
6+
import { assertEquals } from 'std/testing/asserts.ts'
7+
import { redirect } from './redirect.ts'
8+
9+
// mock history functions used in redirect()
10+
interface MockWindow extends Window {
11+
history: {
12+
replaceState: (state: object | null, title: string | '', url?: string) => void,
13+
pushState: (state: object | null, title: string | '', url?: string) => void
14+
}
15+
}
16+
declare let window: MockWindow
17+
18+
// track calls to history functions
19+
const calls = {
20+
pushCalls: 0, // tracks calls to pushState()
21+
replaceCalls: 0 // tracks calls to replaceState()
22+
}
23+
// create mock history impl
24+
window.history = {
25+
replaceState: (url) => { calls.replaceCalls++; return null },
26+
pushState: (url) => { calls.pushCalls++; return null }
27+
}
28+
29+
const resetCallCount = () => {
30+
calls.pushCalls = 0
31+
calls.replaceCalls = 0
32+
}
33+
34+
Deno.test('redirect: replace=false should call history.pushState', () => {
35+
const url = '/foo/bar.ts'
36+
37+
redirect(url)
38+
assertEquals(calls.pushCalls, 1)
39+
redirect(url)
40+
assertEquals(calls.pushCalls, 2)
41+
redirect(url)
42+
assertEquals(calls.pushCalls, 3)
43+
44+
resetCallCount()
45+
})
46+
47+
Deno.test('redirect: replace=true should call history.replaceState', () => {
48+
const url = '/foo/bar2.ts'
49+
50+
redirect(url, true)
51+
assertEquals(calls.replaceCalls, 1)
52+
redirect(url, true)
53+
54+
assertEquals(calls.replaceCalls, 2)
55+
56+
resetCallCount()
57+
})
58+
59+
Deno.test('redirect: empty string url should not call history methods', () => {
60+
const url = ''
61+
62+
redirect(url)
63+
64+
assertEquals(calls.pushCalls, 0)
65+
assertEquals(calls.replaceCalls, 0)
66+
67+
})
68+
69+
/**
70+
* This fails because setting location.href is not allowed in a
71+
* non-browser environment. see
72+
* https://github.com/denoland/deno/blob/main/docs/runtime/location_api.md
73+
* This errors out on line 12 of redirect().
74+
*/
75+
// Deno.test('redirect: file url should set location.href', () => {
76+
// const url = 'file://foo/file.ts'
77+
78+
// redirect(url)
79+
80+
// assertEquals(window.location.href, url)
81+
// assertEquals(calls.pushCalls, 0)
82+
// assertEquals(calls.replaceCalls, 0)
83+
84+
// resetCallCount()
85+
// })

0 commit comments

Comments
 (0)