Skip to content

Commit 04aa07d

Browse files
committed
test: unit test for wrapWithMutableAccessCheck and phase checks
1 parent 9766484 commit 04aa07d

File tree

1 file changed

+53
-1
lines changed

1 file changed

+53
-1
lines changed

packages/next/src/server/web/spec-extension/adapters/request-cookies.test.ts

Lines changed: 53 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,8 +1,13 @@
1-
import { RequestCookies } from '../cookies'
1+
import {
2+
workUnitAsyncStorage,
3+
type RequestStore,
4+
} from '../../../app-render/work-unit-async-storage.external'
5+
import { RequestCookies, ResponseCookies } from '../cookies'
26
import {
37
ReadonlyRequestCookiesError,
48
RequestCookiesAdapter,
59
MutableRequestCookiesAdapter,
10+
wrapWithMutableAccessCheck,
611
} from './request-cookies'
712

813
describe('RequestCookiesAdapter', () => {
@@ -100,3 +105,50 @@ describe('MutableRequestCookiesAdapter', () => {
100105
])
101106
})
102107
})
108+
109+
describe('wrapWithMutableAccessCheck', () => {
110+
const createMockRequestStore = (phase: RequestStore['phase']) =>
111+
({ type: 'request', phase }) as RequestStore
112+
113+
it('prevents setting cookies in the render phase', () => {
114+
const requestStore = createMockRequestStore('action')
115+
workUnitAsyncStorage.run(requestStore, () => {
116+
const headers = new Headers({})
117+
const underlyingCookies = new ResponseCookies(headers)
118+
const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies)
119+
120+
// simulate changing phases
121+
requestStore.phase = 'render'
122+
123+
const EXPECTED_ERROR =
124+
/Cookies can only be modified in a Server Action or Route Handler\./
125+
126+
expect(() => {
127+
wrappedCookies.set('foo', '1')
128+
}).toThrow(EXPECTED_ERROR)
129+
130+
expect(wrappedCookies.get('foo')).toBe(undefined)
131+
})
132+
})
133+
134+
it('prevents deleting cookies in the render phase', () => {
135+
const requestStore = createMockRequestStore('action')
136+
workUnitAsyncStorage.run(requestStore, () => {
137+
const headers = new Headers({})
138+
const underlyingCookies = new ResponseCookies(headers)
139+
const wrappedCookies = wrapWithMutableAccessCheck(underlyingCookies)
140+
wrappedCookies.set('foo', '1')
141+
142+
// simulate changing phases
143+
requestStore.phase = 'render'
144+
145+
const EXPECTED_ERROR =
146+
/Cookies can only be modified in a Server Action or Route Handler\./
147+
148+
expect(() => {
149+
wrappedCookies.delete('foo')
150+
}).toThrow(EXPECTED_ERROR)
151+
expect(wrappedCookies.get('foo')?.value).toEqual('1')
152+
})
153+
})
154+
})

0 commit comments

Comments
 (0)