Skip to content

Commit

Permalink
Add eval test
Browse files Browse the repository at this point in the history
  • Loading branch information
javivelasco committed Nov 4, 2021
1 parent 8ecd85a commit 0f0bebc
Show file tree
Hide file tree
Showing 3 changed files with 94 additions and 0 deletions.
8 changes: 8 additions & 0 deletions test/integration/middleware/with-eval/lib/utils.js
@@ -0,0 +1,8 @@
export async function usingEval() {
// eslint-disable-next-line no-eval
return { value: eval('100') }
}

export async function notUsingEval() {
return { value: 100 }
}
19 changes: 19 additions & 0 deletions test/integration/middleware/with-eval/pages/_middleware.js
@@ -0,0 +1,19 @@
import { notUsingEval, usingEval } from '../lib/utils'

export async function middleware(request) {
if (request.nextUrl.pathname === '/using-eval') {
return new Response(JSON.stringify(await usingEval()), {
headers: {
'Content-Type': 'application/json',
},
})
}

if (request.nextUrl.pathname === '/not-using-eval') {
return new Response(JSON.stringify(await notUsingEval()), {
headers: {
'Content-Type': 'application/json',
},
})
}
}
67 changes: 67 additions & 0 deletions test/integration/middleware/with-eval/test/index.test.js
@@ -0,0 +1,67 @@
/* eslint-env jest */

import { join } from 'path'
import {
fetchViaHTTP,
findPort,
killApp,
launchApp,
nextBuild,
} from 'next-test-utils'

const context = {}
const DYNAMIC_CODE_ERROR = `Dynamic Code Evaluation (e. g. 'eval', 'new Function') not allowed in Middleware`

jest.setTimeout(1000 * 60 * 2)
context.appDir = join(__dirname, '../')

describe('Middleware usage of dynamic code evaluation', () => {
describe('dev mode', () => {
let output = ''

beforeAll(async () => {
context.appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, {
onStdout(msg) {
output += msg
},
onStderr(msg) {
output += msg
},
})
})

beforeEach(() => (output = ''))
afterAll(() => killApp(context.app))

it('shows a warning when running code with eval', async () => {
const res = await fetchViaHTTP(context.appPort, `/using-eval`)
const json = await res.json()
expect(json.value).toEqual(100)
expect(output).toContain(DYNAMIC_CODE_ERROR)
})

it('does not show warning when no code uses eval', async () => {
const res = await fetchViaHTTP(context.appPort, `/not-using-eval`)
const json = await res.json()
expect(json.value).toEqual(100)
expect(output).not.toContain(DYNAMIC_CODE_ERROR)
})
})

describe('production mode', () => {
let buildResult

beforeAll(async () => {
buildResult = await nextBuild(context.appDir, undefined, {
stderr: true,
stdout: true,
})
})

it('should have middleware warning during build', () => {
expect(buildResult.stderr).toContain(`Failed to compile`)
expect(buildResult.stderr).toContain(DYNAMIC_CODE_ERROR)
})
})
})

0 comments on commit 0f0bebc

Please sign in to comment.