-
Notifications
You must be signed in to change notification settings - Fork 27k
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
NextResponse: add
.json
static method (#31483)
closes: #31196 This new API was suggested in a previous version of this feature: #31024 (comment) Co-authored-by: JJ Kasper <[email protected]>
- Loading branch information
Showing
2 changed files
with
60 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
/* 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: '', | ||
}) | ||
}) |