Skip to content

Commit

Permalink
chore: fixes existing production tests
Browse files Browse the repository at this point in the history
  • Loading branch information
feugy committed May 11, 2022
1 parent bb88b3c commit d3931cd
Show file tree
Hide file tree
Showing 8 changed files with 44 additions and 73 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import { fetchViaHTTP } from 'next-test-utils'
import { readJson } from 'fs-extra'
import path from 'path'

Expand Down Expand Up @@ -29,13 +29,13 @@ describe('dependencies can use env vars in middlewares', () => {
'pages/api/_middleware.js': `
import customPackage from 'my-custom-package';
export default function middleware(_req) {
return new Response(JSON.stringify({
string: "a constant string",
hello: process.env.ENV_VAR_USED_IN_MIDDLEWARE,
customPackage: customPackage(),
}), {
headers: {
'Content-Type': 'application/json'
return new Response(null, {
headers: {
data: JSON.stringify({
string: "a constant string",
hello: process.env.ENV_VAR_USED_IN_MIDDLEWARE,
customPackage: customPackage(),
})
}
})
}
Expand Down Expand Up @@ -67,13 +67,11 @@ describe('dependencies can use env vars in middlewares', () => {
})

it('uses the environment variables', async () => {
const html = await renderViaHTTP(next.url, '/api')
expect(html).toContain(
JSON.stringify({
string: 'a constant string',
hello: 'env-var-used-in-middleware',
customPackage: 'my-custom-package-env-var',
})
)
const response = await fetchViaHTTP(next.url, '/api')
expect(JSON.parse(response.headers.get('data'))).toEqual({
string: 'a constant string',
hello: 'env-var-used-in-middleware',
customPackage: 'my-custom-package-env-var',
})
})
})
6 changes: 4 additions & 2 deletions test/production/generate-middleware-source-maps/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,8 +15,9 @@ describe('experimental.middlewareSourceMaps: true', () => {
},
files: {
'pages/_middleware.js': `
import { NextResponse } from "next/server";
export default function middleware() {
return new Response("Hello, world!");
return NextResponse.next();
}
`,
},
Expand All @@ -42,8 +43,9 @@ describe('experimental.middlewareSourceMaps: false', () => {
next = await createNext({
files: {
'pages/_middleware.js': `
import { NextResponse } from "next/server";
export default function middleware() {
return new Response("Hello, world!");
return NextResponse.next();
}
`,
},
Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { createNext } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import { fetchViaHTTP } from 'next-test-utils'

describe('middleware environment variables in node server reflect the usage inference', () => {
let next: NextInstance
Expand All @@ -16,12 +16,12 @@ describe('middleware environment variables in node server reflect the usage infe
files: {
'pages/_middleware.js': `
export default function middleware() {
return new Response(JSON.stringify({
canBeInferred: process.env.CAN_BE_INFERRED,
rest: process.env
}), {
return new Response(null, {
headers: {
'Content-Type': 'application/json',
data: JSON.stringify({
canBeInferred: process.env.CAN_BE_INFERRED,
rest: process.env
}),
'X-Custom-Header': process.env.X_CUSTOM_HEADER,
}
})
Expand All @@ -34,12 +34,8 @@ describe('middleware environment variables in node server reflect the usage infe
afterAll(() => next.destroy())

it('limits process.env to only contain env vars that are inferred from usage', async () => {
const html = await renderViaHTTP(next.url, '/test')
let parsed: any
expect(() => {
parsed = JSON.parse(html)
}).not.toThrow()
expect(parsed).toEqual({
const response = await fetchViaHTTP(next.url, '/test')
expect(JSON.parse(response.headers.get('data'))).toEqual({
canBeInferred: 'can-be-inferred',
rest: {
CAN_BE_INFERRED: 'can-be-inferred',
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,9 @@ export const middleware: NextMiddleware = function (request) {
console.log(request.ua?.isBot)
console.log(request.ua?.ua)

return new Response('hello from middleware', {
return new Response(null, {
headers: {
data: 'hello from middleware',
'req-url-basepath': request.nextUrl.basePath,
'req-url-pathname': request.nextUrl.pathname,
'req-url-params': JSON.stringify(request.page.params),
Expand Down
Original file line number Diff line number Diff line change
@@ -1,42 +1,20 @@
import { NextMiddleware, NextResponse } from 'next/server'

export const middleware: NextMiddleware = async function (request, ev) {
// eslint-disable-next-line no-undef
const { readable, writable } = new TransformStream()
export const middleware: NextMiddleware = async function (request) {
const url = request.nextUrl
const writer = writable.getWriter()
const encoder = new TextEncoder()
const next = NextResponse.next()

// Header based on query param
if (url.searchParams.get('set-header') === 'true') {
next.headers.set('x-set-header', 'valid')
}

// Streams a basic response
if (url.pathname === '/responses/stream-a-response') {
ev.waitUntil(
(async () => {
writer.write(encoder.encode('this is a streamed '))
writer.write(encoder.encode('response'))
writer.close()
})()
)

return new Response(readable)
}

if (url.pathname === '/responses/bad-status') {
return new Response('Auth required', {
return new Response(null, {
headers: { 'WWW-Authenticate': 'Basic realm="Secure Area"' },
status: 401,
})
}

// Sends response
if (url.pathname === '/responses/send-response') {
return new NextResponse(JSON.stringify({ message: 'hi!' }))
}

return next
}
6 changes: 3 additions & 3 deletions test/production/middleware-typescript/test/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'test/lib/next-modes/base'
import { renderViaHTTP } from 'next-test-utils'
import { fetchViaHTTP } from 'next-test-utils'

const appDir = join(__dirname, '../app')

Expand All @@ -28,7 +28,7 @@ describe('should set-up next', () => {
afterAll(() => next.destroy())

it('should have built and started', async () => {
const html = await renderViaHTTP(next.url, '/interface/static')
expect(html).toContain('hello from middleware')
const response = await fetchViaHTTP(next.url, '/interface/static')
expect(response.headers.get('data')).toEqual('hello from middleware')
})
})
24 changes: 10 additions & 14 deletions test/production/reading-request-body-in-middleware/index.test.ts
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ describe('reading request body in middleware', () => {
export default async function middleware(request) {
if (!request.body) {
return new Response('No body', { status: 400 });
return new Response(null, { status: 400 });
}
let json;
Expand All @@ -28,13 +28,10 @@ describe('reading request body in middleware', () => {
return res;
}
return new Response(JSON.stringify({
root: true,
...json,
}), {
return new Response(null, {
status: 200,
headers: {
'content-type': 'application/json',
data: JSON.stringify({ root: true, ...json }),
},
})
}
Expand All @@ -45,18 +42,15 @@ describe('reading request body in middleware', () => {
export default async function middleware(request) {
if (!request.body) {
return new Response('No body', { status: 400 });
return new Response(null, { status: 400 });
}
const json = await request.json();
return new Response(JSON.stringify({
root: false,
...json,
}), {
return new Response(null, {
status: 200,
headers: {
'content-type': 'application/json',
data: JSON.stringify({ root: false, ...json }),
},
})
}
Expand Down Expand Up @@ -94,7 +88,7 @@ describe('reading request body in middleware', () => {
}
)
expect(response.status).toEqual(200)
expect(await response.json()).toEqual({
expect(JSON.parse(response.headers.get('data'))).toEqual({
foo: 'bar',
root: true,
})
Expand All @@ -115,7 +109,7 @@ describe('reading request body in middleware', () => {
}
)
expect(response.status).toEqual(200)
expect(await response.json()).toEqual({
expect(JSON.parse(response.headers.get('data'))).toEqual({
foo: 'bar',
root: false,
})
Expand Down Expand Up @@ -144,6 +138,7 @@ describe('reading request body in middleware', () => {
api: true,
})
expect(response.headers.get('x-from-root-middleware')).toEqual('1')
expect(response.headers.has('data')).toBe(false)
})

it('passes the body to the api endpoint when no body is consumed on middleware', async () => {
Expand All @@ -170,5 +165,6 @@ describe('reading request body in middleware', () => {
api: true,
})
expect(response.headers.get('x-from-root-middleware')).toEqual('1')
expect(response.headers.has('data')).toBe(false)
})
})
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
export async function middleware(req) {
return new Response('hello from middleware')
return new Response(null, { headers: { data: 'hello from middleware' } })
}

0 comments on commit d3931cd

Please sign in to comment.