rsnext/test/unit/web-runtime/next-response.test.ts
Dominik Ferber feabd54f6b
avoid mutating response.cookie options (#31679)
Previously `response.cookie(name, value, options)` would mutate the passed in `options` which lead to unexpected behaviour as described in #31666.

This PR clones the `options` argument before mutating it.

## Bug

- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Errors have helpful link attached, see `contributing.md`

## Feature

- [ ] Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR.
- [x] Related issues linked using `fixes #number`
- [ ] Integration tests added
- [ ] Documentation added
- [ ] Telemetry added. In case of a feature if it's used or not.
- [ ] Errors have helpful link attached, see `contributing.md`

## Documentation / Examples

- [x] Make sure the linting passes by running `yarn lint`
2021-11-22 11:20:01 +00:00

65 lines
1.9 KiB
TypeScript

/* eslint-env jest */
import { Blob, File, FormData } from 'next/dist/compiled/formdata-node'
import { Crypto } from 'next/dist/server/web/sandbox/polyfills'
import { Response } from 'next/dist/server/web/spec-compliant/response'
import { Headers } from 'next/dist/server/web/spec-compliant/headers'
import * as streams from 'web-streams-polyfill/ponyfill'
beforeAll(() => {
global['Blob'] = Blob
global['crypto'] = new Crypto()
global['File'] = File
global['FormData'] = FormData
global['Headers'] = Headers
global['ReadableStream'] = streams.ReadableStream
global['TransformStream'] = streams.TransformStream
global['Response'] = Response
})
afterAll(() => {
delete global['Blob']
delete global['crypto']
delete global['File']
delete global['Headers']
delete global['FormData']
delete global['ReadableStream']
delete global['TransformStream']
})
const toJSON = async (response) => ({
body: await response.json(),
contentType: response.headers.get('content-type'),
})
it('automatically parses and formats JSON', async () => {
const { NextResponse } = await import(
'next/dist/server/web/spec-extension/response'
)
expect(await toJSON(NextResponse.json({ message: 'hello!' }))).toMatchObject({
contentType: 'application/json',
body: { message: 'hello!' },
})
expect(await toJSON(NextResponse.json(null))).toMatchObject({
contentType: 'application/json',
body: null,
})
expect(await toJSON(NextResponse.json(''))).toMatchObject({
contentType: 'application/json',
body: '',
})
})
it('response.cookie does not modify options', async () => {
const { NextResponse } = await import(
'next/dist/server/web/spec-extension/response'
)
const options = { maxAge: 10000 }
const response = NextResponse.json(null)
response.cookie('cookieName', 'cookieValue', options)
expect(options).toEqual({ maxAge: 10000 })
})