Unverified Commit ed59ad52 authored by Wyatt Johnson's avatar Wyatt Johnson Committed by GitHub

Change `NextInstance.fetch` Signature (#44575)

Co-authored-by: 's avatarkodiakhq[bot] <49736102+kodiakhq[bot]@users.noreply.github.com>
parent 5fb56312
...@@ -2,6 +2,7 @@ ...@@ -2,6 +2,7 @@
import { createNextDescribe, FileRef } from 'e2e-utils' import { createNextDescribe, FileRef } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import path from 'path' import path from 'path'
import { withQuery } from 'next-test-utils'
createNextDescribe( createNextDescribe(
'app-dir with middleware', 'app-dir with middleware',
...@@ -31,7 +32,7 @@ createNextDescribe( ...@@ -31,7 +32,7 @@ createNextDescribe(
}, },
])('Mutate request headers for $title', ({ path, toJson }) => { ])('Mutate request headers for $title', ({ path, toJson }) => {
it(`Adds new headers`, async () => { it(`Adds new headers`, async () => {
const res = await next.fetch(path, null, { const res = await next.fetch(path, {
headers: { headers: {
'x-from-client': 'hello-from-client', 'x-from-client': 'hello-from-client',
}, },
...@@ -44,10 +45,9 @@ createNextDescribe( ...@@ -44,10 +45,9 @@ createNextDescribe(
it(`Deletes headers`, async () => { it(`Deletes headers`, async () => {
const res = await next.fetch( const res = await next.fetch(
path, withQuery(path, {
{
'remove-headers': 'x-from-client1,x-from-client2', 'remove-headers': 'x-from-client1,x-from-client2',
}, }),
{ {
headers: { headers: {
'x-from-client1': 'hello-from-client', 'x-from-client1': 'hello-from-client',
...@@ -78,11 +78,10 @@ createNextDescribe( ...@@ -78,11 +78,10 @@ createNextDescribe(
it(`Updates headers`, async () => { it(`Updates headers`, async () => {
const res = await next.fetch( const res = await next.fetch(
path, withQuery(path, {
{
'update-headers': 'update-headers':
'x-from-client1=new-value1,x-from-client2=new-value2', 'x-from-client1=new-value1,x-from-client2=new-value2',
}, }),
{ {
headers: { headers: {
'x-from-client1': 'old-value1', 'x-from-client1': 'old-value1',
......
...@@ -234,7 +234,7 @@ createNextDescribe( ...@@ -234,7 +234,7 @@ createNextDescribe(
}) })
it('should force SSR correctly for headers usage', async () => { it('should force SSR correctly for headers usage', async () => {
const res = await next.fetch('/force-static', undefined, { const res = await next.fetch('/force-static', {
headers: { headers: {
Cookie: 'myCookie=cookieValue', Cookie: 'myCookie=cookieValue',
another: 'header', another: 'header',
...@@ -315,7 +315,7 @@ createNextDescribe( ...@@ -315,7 +315,7 @@ createNextDescribe(
const validParams = ['tim', 'seb', 'styfle'] const validParams = ['tim', 'seb', 'styfle']
for (const param of validParams) { for (const param of validParams) {
const res = await next.fetch(`/blog/${param}`, undefined, { const res = await next.fetch(`/blog/${param}`, {
redirect: 'manual', redirect: 'manual',
}) })
expect(res.status).toBe(200) expect(res.status).toBe(200)
...@@ -330,7 +330,7 @@ createNextDescribe( ...@@ -330,7 +330,7 @@ createNextDescribe(
const invalidParams = ['timm', 'non-existent'] const invalidParams = ['timm', 'non-existent']
for (const param of invalidParams) { for (const param of invalidParams) {
const invalidRes = await next.fetch(`/blog/${param}`, undefined, { const invalidRes = await next.fetch(`/blog/${param}`, {
redirect: 'manual', redirect: 'manual',
}) })
expect(invalidRes.status).toBe(404) expect(invalidRes.status).toBe(404)
...@@ -340,11 +340,9 @@ createNextDescribe( ...@@ -340,11 +340,9 @@ createNextDescribe(
it('should work with forced dynamic path', async () => { it('should work with forced dynamic path', async () => {
for (const slug of ['first', 'second']) { for (const slug of ['first', 'second']) {
const res = await next.fetch( const res = await next.fetch(`/dynamic-no-gen-params-ssr/${slug}`, {
`/dynamic-no-gen-params-ssr/${slug}`, redirect: 'manual',
undefined, })
{ redirect: 'manual' }
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.text()).toContain(`${slug}`) expect(await res.text()).toContain(`${slug}`)
} }
...@@ -352,11 +350,9 @@ createNextDescribe( ...@@ -352,11 +350,9 @@ createNextDescribe(
it('should work with dynamic path no generateStaticParams', async () => { it('should work with dynamic path no generateStaticParams', async () => {
for (const slug of ['first', 'second']) { for (const slug of ['first', 'second']) {
const res = await next.fetch( const res = await next.fetch(`/dynamic-no-gen-params/${slug}`, {
`/dynamic-no-gen-params/${slug}`, redirect: 'manual',
undefined, })
{ redirect: 'manual' }
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(await res.text()).toContain(`${slug}`) expect(await res.text()).toContain(`${slug}`)
} }
...@@ -383,13 +379,9 @@ createNextDescribe( ...@@ -383,13 +379,9 @@ createNextDescribe(
] ]
for (const params of paramsToCheck) { for (const params of paramsToCheck) {
const res = await next.fetch( const res = await next.fetch(`/blog/${params.author}/${params.slug}`, {
`/blog/${params.author}/${params.slug}`, redirect: 'manual',
undefined, })
{
redirect: 'manual',
}
)
expect(res.status).toBe(200) expect(res.status).toBe(200)
const html = await res.text() const html = await res.text()
const $ = cheerio.load(html) const $ = cheerio.load(html)
...@@ -436,7 +428,7 @@ createNextDescribe( ...@@ -436,7 +428,7 @@ createNextDescribe(
it('should ssr dynamically when detected automatically with fetch cache option', async () => { it('should ssr dynamically when detected automatically with fetch cache option', async () => {
const pathname = '/ssr-auto/cache-no-store' const pathname = '/ssr-auto/cache-no-store'
const initialRes = await next.fetch(pathname, undefined, { const initialRes = await next.fetch(pathname, {
redirect: 'manual', redirect: 'manual',
}) })
expect(initialRes.status).toBe(200) expect(initialRes.status).toBe(200)
...@@ -449,7 +441,7 @@ createNextDescribe( ...@@ -449,7 +441,7 @@ createNextDescribe(
expect(initialHtml).toContain('Example Domain') expect(initialHtml).toContain('Example Domain')
const secondRes = await next.fetch(pathname, undefined, { const secondRes = await next.fetch(pathname, {
redirect: 'manual', redirect: 'manual',
}) })
expect(secondRes.status).toBe(200) expect(secondRes.status).toBe(200)
...@@ -465,7 +457,7 @@ createNextDescribe( ...@@ -465,7 +457,7 @@ createNextDescribe(
}) })
it('should render not found pages correctly and fallback to the default one', async () => { it('should render not found pages correctly and fallback to the default one', async () => {
const res = await next.fetch(`/blog/shu/hi`, undefined, { const res = await next.fetch(`/blog/shu/hi`, {
redirect: 'manual', redirect: 'manual',
}) })
expect(res.status).toBe(404) expect(res.status).toBe(404)
...@@ -477,7 +469,7 @@ createNextDescribe( ...@@ -477,7 +469,7 @@ createNextDescribe(
// TODO-APP: support fetch revalidate case for dynamic rendering // TODO-APP: support fetch revalidate case for dynamic rendering
it.skip('should ssr dynamically when detected automatically with fetch revalidate option', async () => { it.skip('should ssr dynamically when detected automatically with fetch revalidate option', async () => {
const pathname = '/ssr-auto/fetch-revalidate-zero' const pathname = '/ssr-auto/fetch-revalidate-zero'
const initialRes = await next.fetch(pathname, undefined, { const initialRes = await next.fetch(pathname, {
redirect: 'manual', redirect: 'manual',
}) })
expect(initialRes.status).toBe(200) expect(initialRes.status).toBe(200)
...@@ -490,7 +482,7 @@ createNextDescribe( ...@@ -490,7 +482,7 @@ createNextDescribe(
expect(initialHtml).toContain('Example Domain') expect(initialHtml).toContain('Example Domain')
const secondRes = await next.fetch(pathname, undefined, { const secondRes = await next.fetch(pathname, {
redirect: 'manual', redirect: 'manual',
}) })
expect(secondRes.status).toBe(200) expect(secondRes.status).toBe(200)
...@@ -506,7 +498,7 @@ createNextDescribe( ...@@ -506,7 +498,7 @@ createNextDescribe(
}) })
it('should ssr dynamically when forced via config', async () => { it('should ssr dynamically when forced via config', async () => {
const initialRes = await next.fetch('/ssr-forced', undefined, { const initialRes = await next.fetch('/ssr-forced', {
redirect: 'manual', redirect: 'manual',
}) })
expect(initialRes.status).toBe(200) expect(initialRes.status).toBe(200)
...@@ -517,7 +509,7 @@ createNextDescribe( ...@@ -517,7 +509,7 @@ createNextDescribe(
expect(initial$('#page').text()).toBe('/ssr-forced') expect(initial$('#page').text()).toBe('/ssr-forced')
const initialDate = initial$('#date').text() const initialDate = initial$('#date').text()
const secondRes = await next.fetch('/ssr-forced', undefined, { const secondRes = await next.fetch('/ssr-forced', {
redirect: 'manual', redirect: 'manual',
}) })
expect(secondRes.status).toBe(200) expect(secondRes.status).toBe(200)
......
...@@ -20,12 +20,12 @@ createNextDescribe( ...@@ -20,12 +20,12 @@ createNextDescribe(
const controller1 = new AbortController() const controller1 = new AbortController()
const controller2 = new AbortController() const controller2 = new AbortController()
next next
.fetch('/slow-page-no-loading', undefined, { .fetch('/slow-page-no-loading', {
signal: controller1.signal, signal: controller1.signal,
}) })
.catch(() => {}) .catch(() => {})
next next
.fetch('/slow-page-no-loading', undefined, { .fetch('/slow-page-no-loading', {
signal: controller2.signal, signal: controller2.signal,
}) })
.catch(() => {}) .catch(() => {})
...@@ -35,7 +35,7 @@ createNextDescribe( ...@@ -35,7 +35,7 @@ createNextDescribe(
const controller3 = new AbortController() const controller3 = new AbortController()
next next
.fetch('/slow-page-no-loading', undefined, { .fetch('/slow-page-no-loading', {
signal: controller3.signal, signal: controller3.signal,
}) })
.catch(() => {}) .catch(() => {})
...@@ -66,28 +66,20 @@ createNextDescribe( ...@@ -66,28 +66,20 @@ createNextDescribe(
} }
it('should use application/octet-stream for flight', async () => { it('should use application/octet-stream for flight', async () => {
const res = await next.fetch( const res = await next.fetch('/dashboard/deployments/123', {
'/dashboard/deployments/123', headers: {
{}, ['RSC'.toString()]: '1',
{ },
headers: { })
['RSC'.toString()]: '1',
},
}
)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream') expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
}) })
it('should use application/octet-stream for flight with edge runtime', async () => { it('should use application/octet-stream for flight with edge runtime', async () => {
const res = await next.fetch( const res = await next.fetch('/dashboard', {
'/dashboard', headers: {
{}, ['RSC'.toString()]: '1',
{ },
headers: { })
['RSC'.toString()]: '1',
},
}
)
expect(res.headers.get('Content-Type')).toBe('application/octet-stream') expect(res.headers.get('Content-Type')).toBe('application/octet-stream')
}) })
...@@ -1895,7 +1887,7 @@ createNextDescribe( ...@@ -1895,7 +1887,7 @@ createNextDescribe(
}) })
;(isDev ? describe.skip : describe)('Subresource Integrity', () => { ;(isDev ? describe.skip : describe)('Subresource Integrity', () => {
function fetchWithPolicy(policy: string | null) { function fetchWithPolicy(policy: string | null) {
return next.fetch('/dashboard', undefined, { return next.fetch('/dashboard', {
headers: policy headers: policy
? { ? {
'Content-Security-Policy': policy, 'Content-Security-Policy': policy,
...@@ -2405,7 +2397,7 @@ createNextDescribe( ...@@ -2405,7 +2397,7 @@ createNextDescribe(
describe('bots', () => { describe('bots', () => {
if (!isNextDeploy) { if (!isNextDeploy) {
it('should block rendering for bots and return 404 status', async () => { it('should block rendering for bots and return 404 status', async () => {
const res = await next.fetch('/not-found/servercomponent', '', { const res = await next.fetch('/not-found/servercomponent', {
headers: { headers: {
'User-Agent': 'Googlebot', 'User-Agent': 'Googlebot',
}, },
......
...@@ -8,13 +8,9 @@ createNextDescribe( ...@@ -8,13 +8,9 @@ createNextDescribe(
}, },
({ next }) => { ({ next }) => {
it('should redirect route when requesting it directly', async () => { it('should redirect route when requesting it directly', async () => {
const res = await next.fetch( const res = await next.fetch('/a/', {
'/a/', redirect: 'manual',
{}, })
{
redirect: 'manual',
}
)
expect(res.status).toBe(308) expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(next.url + '/a') expect(res.headers.get('location')).toBe(next.url + '/a')
}) })
......
...@@ -331,7 +331,7 @@ describe('app dir - rsc basics', () => { ...@@ -331,7 +331,7 @@ describe('app dir - rsc basics', () => {
}) })
it('should render css-in-js suspense boundary correctly', async () => { it('should render css-in-js suspense boundary correctly', async () => {
await next.fetch('/css-in-js/suspense', null, {}).then(async (response) => { await next.fetch('/css-in-js/suspense').then(async (response) => {
const results = [] const results = []
await resolveStreamResponse(response, (chunk: string) => { await resolveStreamResponse(response, (chunk: string) => {
...@@ -393,15 +393,11 @@ describe('app dir - rsc basics', () => { ...@@ -393,15 +393,11 @@ describe('app dir - rsc basics', () => {
it('should support streaming for flight response', async () => { it('should support streaming for flight response', async () => {
await next await next
.fetch( .fetch('/', {
'/', headers: {
{}, ['RSC'.toString()]: '1',
{ },
headers: { })
['RSC'.toString()]: '1',
},
}
)
.then(async (response) => { .then(async (response) => {
const result = await resolveStreamResponse(response) const result = await resolveStreamResponse(response)
expect(result).toContain('component:index.server') expect(result).toContain('component:index.server')
...@@ -409,7 +405,7 @@ describe('app dir - rsc basics', () => { ...@@ -409,7 +405,7 @@ describe('app dir - rsc basics', () => {
}) })
it('should support partial hydration with inlined server data', async () => { it('should support partial hydration with inlined server data', async () => {
await next.fetch('/partial-hydration', null, {}).then(async (response) => { await next.fetch('/partial-hydration').then(async (response) => {
let gotFallback = false let gotFallback = false
let gotData = false let gotData = false
let gotInlinedData = false let gotInlinedData = false
......
...@@ -8,13 +8,9 @@ createNextDescribe( ...@@ -8,13 +8,9 @@ createNextDescribe(
}, },
({ next }) => { ({ next }) => {
it('should redirect route when requesting it directly', async () => { it('should redirect route when requesting it directly', async () => {
const res = await next.fetch( const res = await next.fetch('/a', {
'/a', redirect: 'manual',
{}, })
{
redirect: 'manual',
}
)
expect(res.status).toBe(308) expect(res.status).toBe(308)
expect(res.headers.get('location')).toBe(next.url + '/a/') expect(res.headers.get('location')).toBe(next.url + '/a/')
}) })
......
...@@ -2,7 +2,7 @@ import os from 'os' ...@@ -2,7 +2,7 @@ import os from 'os'
import path from 'path' import path from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import treeKill from 'tree-kill' import treeKill from 'tree-kill'
import { NextConfig } from 'next' import type { NextConfig } from 'next'
import { FileRef } from '../e2e-utils' import { FileRef } from '../e2e-utils'
import { ChildProcess } from 'child_process' import { ChildProcess } from 'child_process'
import { createNextInstall } from '../create-next-install' import { createNextInstall } from '../create-next-install'
...@@ -414,12 +414,17 @@ export class NextInstance { ...@@ -414,12 +414,17 @@ export class NextInstance {
} }
/** /**
* Fetch the HTML for the provided page. * Performs a fetch request to the NextInstance with the options provided.
*
* @param pathname the pathname on the NextInstance to fetch
* @param opts the optional options to pass to the underlying fetch
* @returns the fetch response
*/ */
public async fetch( public async fetch(
...args: Parameters<OmitFirstArgument<typeof fetchViaHTTP>> pathname: string,
opts?: import('node-fetch').RequestInit
) { ) {
return fetchViaHTTP(this.url, ...args) return fetchViaHTTP(this.url, pathname, null, opts)
} }
public on(event: Event, cb: (...args: any[]) => any) { public on(event: Event, cb: (...args: any[]) => any) {
......
...@@ -111,8 +111,30 @@ export function getFullUrl(appPortOrUrl, url, hostname) { ...@@ -111,8 +111,30 @@ export function getFullUrl(appPortOrUrl, url, hostname) {
return fullUrl return fullUrl
} }
/**
* Appends the querystring to the url
*
* @param {string} pathname the pathname
* @param {Record<string,any> | string} query the query object to add to the pathname
* @returns the pathname with the query
*/
export function withQuery(pathname, query) {
const querystring = typeof query === 'string' ? query : qs.stringify(query)
if (querystring.length === 0) {
return pathname
}
// If there's a `?` between the pathname and the querystring already, then
// don't add another one.
if (querystring.startsWith('?') || pathname.endsWith('?')) {
return `${pathname}${querystring}`
}
return `${pathname}?${querystring}`
}
export function renderViaAPI(app, pathname, query) { export function renderViaAPI(app, pathname, query) {
const url = `${pathname}${query ? `?${qs.stringify(query)}` : ''}` const url = query ? withQuery(pathname, query) : pathname
return app.renderToHTML({ url }, {}, pathname, query) return app.renderToHTML({ url }, {}, pathname, query)
} }
...@@ -130,14 +152,12 @@ export function renderViaHTTP(appPort, pathname, query, opts) { ...@@ -130,14 +152,12 @@ export function renderViaHTTP(appPort, pathname, query, opts) {
/** /**
* @param {string | number} appPort * @param {string | number} appPort
* @param {string} pathname * @param {string} pathname
* @param {Record<string, any> | string | undefined} [query] * @param {Record<string, any> | string | null | undefined} [query]
* @param {import('node-fetch').RequestInit} [opts] * @param {import('node-fetch').RequestInit} [opts]
* @returns {Promise<Response & {buffer: any} & {headers: any}>} * @returns {Promise<Response & {buffer: any} & {headers: any}>}
*/ */
export function fetchViaHTTP(appPort, pathname, query, opts) { export function fetchViaHTTP(appPort, pathname, query, opts) {
const url = `${pathname}${ const url = query ? withQuery(pathname, query) : pathname
typeof query === 'string' ? query : query ? `?${qs.stringify(query)}` : ''
}`
return fetch(getFullUrl(appPort, url), { return fetch(getFullUrl(appPort, url), {
// in node.js v17 fetch favors IPv6 but Next.js is // in node.js v17 fetch favors IPv6 but Next.js is
// listening on IPv4 by default so force IPv4 DNS resolving // listening on IPv4 by default so force IPv4 DNS resolving
......
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment