Unverified Commit 2c56a693 authored by Sebastian "Sebbie" Silbermann's avatar Sebastian "Sebbie" Silbermann Committed by GitHub

[test] Move all files to .ts (4/6) (#85639)

parent 8bfa443b
...@@ -40,11 +40,10 @@ describe('Link Component with Encoding', () => { ...@@ -40,11 +40,10 @@ describe('Link Component with Encoding', () => {
{ pathname: encodeURI('/single/hello world ') } { pathname: encodeURI('/single/hello world ') }
)` )`
) )
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`)
} finally { } finally {
...@@ -57,11 +56,10 @@ describe('Link Component with Encoding', () => { ...@@ -57,11 +56,10 @@ describe('Link Component with Encoding', () => {
try { try {
await waitFor(2000) await waitFor(2000)
await browser.elementByCss('#single-spaces').click() await browser.elementByCss('#single-spaces').click()
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello world "}"`)
} finally { } finally {
...@@ -91,11 +89,10 @@ describe('Link Component with Encoding', () => { ...@@ -91,11 +89,10 @@ describe('Link Component with Encoding', () => {
{ pathname: encodeURI('/single/hello%world') } { pathname: encodeURI('/single/hello%world') }
)` )`
) )
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello%world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello%world"}"`)
} finally { } finally {
...@@ -108,11 +105,10 @@ describe('Link Component with Encoding', () => { ...@@ -108,11 +105,10 @@ describe('Link Component with Encoding', () => {
try { try {
await waitFor(2000) await waitFor(2000)
await browser.elementByCss('#single-percent').click() await browser.elementByCss('#single-percent').click()
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello%world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello%world"}"`)
} finally { } finally {
...@@ -145,11 +141,10 @@ describe('Link Component with Encoding', () => { ...@@ -145,11 +141,10 @@ describe('Link Component with Encoding', () => {
{ pathname: '/single/hello${encodeURIComponent('/')}world' } { pathname: '/single/hello${encodeURIComponent('/')}world' }
)` )`
) )
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello/world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello/world"}"`)
} finally { } finally {
...@@ -162,11 +157,10 @@ describe('Link Component with Encoding', () => { ...@@ -162,11 +157,10 @@ describe('Link Component with Encoding', () => {
try { try {
await waitFor(2000) await waitFor(2000)
await browser.elementByCss('#single-slash').click() await browser.elementByCss('#single-slash').click()
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello/world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello/world"}"`)
} finally { } finally {
...@@ -203,11 +197,10 @@ describe('Link Component with Encoding', () => { ...@@ -203,11 +197,10 @@ describe('Link Component with Encoding', () => {
{ pathname: '/single/hello${encodeURIComponent('"')}world' } { pathname: '/single/hello${encodeURIComponent('"')}world' }
)` )`
) )
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(JSON.parse(text)).toMatchInlineSnapshot(` expect(JSON.parse(text)).toMatchInlineSnapshot(`
{ {
...@@ -224,11 +217,10 @@ describe('Link Component with Encoding', () => { ...@@ -224,11 +217,10 @@ describe('Link Component with Encoding', () => {
try { try {
await waitFor(2000) await waitFor(2000)
await browser.elementByCss('#single-double-quote').click() await browser.elementByCss('#single-double-quote').click()
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(JSON.parse(text)).toMatchInlineSnapshot(` expect(JSON.parse(text)).toMatchInlineSnapshot(`
{ {
...@@ -265,11 +257,10 @@ describe('Link Component with Encoding', () => { ...@@ -265,11 +257,10 @@ describe('Link Component with Encoding', () => {
{ pathname: '/single/hello${encodeURIComponent(':')}world' } { pathname: '/single/hello${encodeURIComponent(':')}world' }
)` )`
) )
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello:world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello:world"}"`)
} finally { } finally {
...@@ -282,11 +273,10 @@ describe('Link Component with Encoding', () => { ...@@ -282,11 +273,10 @@ describe('Link Component with Encoding', () => {
try { try {
await waitFor(2000) await waitFor(2000)
await browser.elementByCss('#single-colon').click() await browser.elementByCss('#single-colon').click()
await check(() => browser.hasElementByCssSelector('#query-content'), { await check(
test(val) { () => browser.hasElementByCssSelector('#query-content'),
return Boolean(val) true
}, )
})
const text = await browser.elementByCss('#query-content').text() const text = await browser.elementByCss('#query-content').text()
expect(text).toMatchInlineSnapshot(`"{"slug":"hello:world"}"`) expect(text).toMatchInlineSnapshot(`"{"slug":"hello:world"}"`)
} finally { } finally {
......
...@@ -10,6 +10,8 @@ import { ...@@ -10,6 +10,8 @@ import {
import { join } from 'path' import { join } from 'path'
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
let app
let appPort
const context = { const context = {
appDir: join(__dirname, '../'), appDir: join(__dirname, '../'),
logs: { output: '', stdout: '', stderr: '' }, logs: { output: '', stdout: '', stderr: '' },
...@@ -19,8 +21,8 @@ const context = { ...@@ -19,8 +21,8 @@ const context = {
describe('Middleware development errors', () => { describe('Middleware development errors', () => {
beforeEach(async () => { beforeEach(async () => {
context.logs = { output: '', stdout: '', stderr: '' } context.logs = { output: '', stdout: '', stderr: '' }
context.appPort = await findPort() appPort = await findPort()
context.app = await launchApp(context.appDir, context.appPort, { app = await launchApp(context.appDir, appPort, {
onStdout(msg) { onStdout(msg) {
context.logs.output += msg context.logs.output += msg
context.logs.stdout += msg context.logs.stdout += msg
...@@ -34,14 +36,14 @@ describe('Middleware development errors', () => { ...@@ -34,14 +36,14 @@ describe('Middleware development errors', () => {
afterEach(async () => { afterEach(async () => {
context.middleware.restore() context.middleware.restore()
if (context.app) { if (app) {
await killApp(context.app) await killApp(app)
} }
}) })
async function assertMiddlewareFetch(hasMiddleware, path = '/') { async function assertMiddlewareFetch(hasMiddleware, path = '/') {
await check(async () => { await check(async () => {
const res = await fetchViaHTTP(context.appPort, path) const res = await fetchViaHTTP(appPort, path)
expect(res.status).toBe(200) expect(res.status).toBe(200)
expect(res.headers.get('x-from-middleware')).toBe( expect(res.headers.get('x-from-middleware')).toBe(
hasMiddleware ? 'true' : null hasMiddleware ? 'true' : null
...@@ -51,7 +53,7 @@ describe('Middleware development errors', () => { ...@@ -51,7 +53,7 @@ describe('Middleware development errors', () => {
} }
async function assertMiddlewareRender(hasMiddleware, path = '/') { async function assertMiddlewareRender(hasMiddleware, path = '/') {
const browser = await webdriver(context.appPort, path) const browser = await webdriver(appPort, path)
const fromMiddleware = await browser.elementById('from-middleware').text() const fromMiddleware = await browser.elementById('from-middleware').text()
expect(fromMiddleware).toBe(hasMiddleware ? 'true' : 'null') expect(fromMiddleware).toBe(hasMiddleware ? 'true' : 'null')
} }
......
...@@ -14,6 +14,8 @@ import { ...@@ -14,6 +14,8 @@ import {
jest.setTimeout(1000 * 60 * 2) jest.setTimeout(1000 * 60 * 2)
let appPort
let app
const context = { const context = {
appDir: join(__dirname, '../'), appDir: join(__dirname, '../'),
buildLogs: { output: '', stdout: '', stderr: '' }, buildLogs: { output: '', stdout: '', stderr: '' },
...@@ -24,27 +26,23 @@ describe('Middleware Production Prefetch', () => { ...@@ -24,27 +26,23 @@ describe('Middleware Production Prefetch', () => {
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
'production mode', 'production mode',
() => { () => {
afterAll(() => killApp(context.app)) afterAll(() => killApp(app))
beforeAll(async () => { beforeAll(async () => {
const build = await nextBuild(context.appDir, undefined, { const build = await nextBuild(context.appDir, undefined, {
stderr: true, stderr: true,
stdout: true, stdout: true,
}) })
context.buildId = await fs.readFile( await fs.readFile(join(context.appDir, '.next/BUILD_ID'), 'utf8')
join(context.appDir, '.next/BUILD_ID'),
'utf8'
)
context.buildLogs = { context.buildLogs = {
output: build.stdout + build.stderr, output: build.stdout + build.stderr,
stderr: build.stderr, stderr: build.stderr,
stdout: build.stdout, stdout: build.stdout,
} }
context.dev = false
context.appPort = await findPort() appPort = await findPort()
context.app = await nextStart(context.appDir, context.appPort, { app = await nextStart(context.appDir, appPort, {
env: { env: {
MIDDLEWARE_TEST: 'asdf', MIDDLEWARE_TEST: 'asdf',
}, },
...@@ -60,7 +58,7 @@ describe('Middleware Production Prefetch', () => { ...@@ -60,7 +58,7 @@ describe('Middleware Production Prefetch', () => {
}) })
it(`prefetch correctly for unexistent routes`, async () => { it(`prefetch correctly for unexistent routes`, async () => {
const browser = await webdriver(context.appPort, `/`) const browser = await webdriver(appPort, `/`)
await browser.elementByCss('#made-up-link').moveTo() await browser.elementByCss('#made-up-link').moveTo()
await check(async () => { await check(async () => {
const scripts = await browser.elementsByCss('script') const scripts = await browser.elementsByCss('script')
...@@ -76,7 +74,7 @@ describe('Middleware Production Prefetch', () => { ...@@ -76,7 +74,7 @@ describe('Middleware Production Prefetch', () => {
}) })
it(`does not prefetch provided path if it will be rewritten`, async () => { it(`does not prefetch provided path if it will be rewritten`, async () => {
const browser = await webdriver(context.appPort, `/`) const browser = await webdriver(appPort, `/`)
await browser.elementByCss('#ssg-page-2').moveTo() await browser.elementByCss('#ssg-page-2').moveTo()
await check(async () => { await check(async () => {
const scripts = await browser.elementsByCss('script') const scripts = await browser.elementsByCss('script')
......
/* eslint-env jest */
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { import {
...@@ -40,6 +38,7 @@ function runDoubleMiddlewareTests() { ...@@ -40,6 +38,7 @@ function runDoubleMiddlewareTests() {
async function writeRootMiddleware() { async function writeRootMiddleware() {
await fs.copy(join(appDir, 'src/pages'), join(appDir, 'pages'), { await fs.copy(join(appDir, 'src/pages'), join(appDir, 'pages'), {
// @ts-expect-error
force: true, force: true,
recursive: true, recursive: true,
}) })
...@@ -68,9 +67,19 @@ return response ...@@ -68,9 +67,19 @@ return response
} }
async function removeRootMiddleware() { async function removeRootMiddleware() {
await fs.remove(rootMiddlewareJSFile, { force: true }) await fs.remove(rootMiddlewareJSFile, {
await fs.remove(rootMiddlewareTSFile, { force: true }) // @ts-expect-error
await fs.remove(join(appDir, 'pages'), { force: true, recursive: true }) force: true,
})
await fs.remove(rootMiddlewareTSFile, {
// @ts-expect-error
force: true,
})
await fs.remove(join(appDir, 'pages'), {
// @ts-expect-error
force: true,
recursive: true,
})
} }
describe.each([ describe.each([
......
/* eslint-env jest */
import fs from 'fs-extra' import fs from 'fs-extra'
import { join } from 'path' import { join } from 'path'
import { import {
...@@ -40,6 +38,7 @@ function runDoubleMiddlewareTests() { ...@@ -40,6 +38,7 @@ function runDoubleMiddlewareTests() {
async function writeRootMiddleware() { async function writeRootMiddleware() {
await fs.copy(join(appDir, 'src/pages'), join(appDir, 'pages'), { await fs.copy(join(appDir, 'src/pages'), join(appDir, 'pages'), {
// @ts-expect-error
force: true, force: true,
recursive: true, recursive: true,
}) })
...@@ -68,9 +67,19 @@ return response ...@@ -68,9 +67,19 @@ return response
} }
async function removeRootMiddleware() { async function removeRootMiddleware() {
await fs.remove(rootMiddlewareJSFile, { force: true }) await fs.remove(rootMiddlewareJSFile, {
await fs.remove(rootMiddlewareTSFile, { force: true }) // @ts-expect-error
await fs.remove(join(appDir, 'pages'), { force: true, recursive: true }) force: true,
})
await fs.remove(rootMiddlewareTSFile, {
// @ts-expect-error
force: true,
})
await fs.remove(join(appDir, 'pages'), {
// @ts-expect-error
force: true,
recursive: true,
})
} }
describe.each([ describe.each([
......
...@@ -103,9 +103,9 @@ describe('minified module ids', () => { ...@@ -103,9 +103,9 @@ describe('minified module ids', () => {
staticBundles += output staticBundles += output
} }
}) })
afterAll(() => { afterAll(async () => {
global.isNextDev = originalIsNextDev global.isNextDev = originalIsNextDev
killApp(app) await killApp(app)
}) })
it('should have long module ids for basic modules', async () => { it('should have long module ids for basic modules', async () => {
......
...@@ -58,7 +58,7 @@ describe('next/dynamic with assetPrefix', () => { ...@@ -58,7 +58,7 @@ describe('next/dynamic with assetPrefix', () => {
cdnPort = await findPort() cdnPort = await findPort()
// lightweight http proxy // lightweight http proxy
cdn = createServer((clientReq, clientRes) => { cdn = createServer((clientReq, clientRes) => {
const proxyPath = clientReq.url.slice('/path-prefix'.length) const proxyPath = clientReq.url!.slice('/path-prefix'.length)
const proxyReq = request( const proxyReq = request(
{ {
hostname: 'localhost', hostname: 'localhost',
...@@ -71,7 +71,7 @@ describe('next/dynamic with assetPrefix', () => { ...@@ -71,7 +71,7 @@ describe('next/dynamic with assetPrefix', () => {
// cdn must be configured to allow requests from this origin // cdn must be configured to allow requests from this origin
proxyRes.headers['Access-Control-Allow-Origin'] = proxyRes.headers['Access-Control-Allow-Origin'] =
`http://localhost:${appPort}` `http://localhost:${appPort}`
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers) clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers)
// [NOTE] if socket doesn't have a handler to error event and if error // [NOTE] if socket doesn't have a handler to error event and if error
// event leaks, node.js ends its process with errored exit code. // event leaks, node.js ends its process with errored exit code.
// However, there can be failing socket event while running test // However, there can be failing socket event while running test
...@@ -105,7 +105,7 @@ describe('next/dynamic with assetPrefix', () => { ...@@ -105,7 +105,7 @@ describe('next/dynamic with assetPrefix', () => {
afterAll(() => cdn.close()) afterAll(() => cdn.close())
afterAll(() => nextConfig.restore()) afterAll(() => nextConfig.restore())
runTests(true) runTests()
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
...@@ -115,7 +115,7 @@ describe('next/dynamic with assetPrefix', () => { ...@@ -115,7 +115,7 @@ describe('next/dynamic with assetPrefix', () => {
cdnPort = await findPort() cdnPort = await findPort()
// lightweight http proxy // lightweight http proxy
cdn = createServer((clientReq, clientRes) => { cdn = createServer((clientReq, clientRes) => {
const proxyPath = clientReq.url.slice('/path-prefix'.length) const proxyPath = clientReq.url!.slice('/path-prefix'.length)
const proxyReq = request( const proxyReq = request(
{ {
hostname: 'localhost', hostname: 'localhost',
...@@ -128,7 +128,7 @@ describe('next/dynamic with assetPrefix', () => { ...@@ -128,7 +128,7 @@ describe('next/dynamic with assetPrefix', () => {
// cdn must be configured to allow requests from this origin // cdn must be configured to allow requests from this origin
proxyRes.headers['Access-Control-Allow-Origin'] = proxyRes.headers['Access-Control-Allow-Origin'] =
`http://localhost:${appPort}` `http://localhost:${appPort}`
clientRes.writeHead(proxyRes.statusCode, proxyRes.headers) clientRes.writeHead(proxyRes.statusCode!, proxyRes.headers)
// [NOTE] if socket doesn't have a handler to error event and if error // [NOTE] if socket doesn't have a handler to error event and if error
// event leaks, node.js ends its process with errored exit code. // event leaks, node.js ends its process with errored exit code.
// However, there can be failing socket event while running test // However, there can be failing socket event while running test
......
...@@ -21,5 +21,5 @@ ...@@ -21,5 +21,5 @@
"strictNullChecks": true "strictNullChecks": true
}, },
"include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"], "include": ["next-env.d.ts", ".next/types/**/*.ts", "**/*.ts", "**/*.tsx"],
"exclude": ["node_modules"] "exclude": ["node_modules", "**/*.test.ts", "**/*.test.tsx"]
} }
...@@ -54,7 +54,7 @@ describe('next/dynamic', () => { ...@@ -54,7 +54,7 @@ describe('next/dynamic', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests(true) runTests()
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
......
...@@ -59,7 +59,7 @@ function runTests() { ...@@ -59,7 +59,7 @@ function runTests() {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests(true) runTests()
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
......
...@@ -52,7 +52,7 @@ describe('next/dynamic', () => { ...@@ -52,7 +52,7 @@ describe('next/dynamic', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests(true) runTests()
} }
) )
;(process.env.TURBOPACK_DEV ? describe.skip : describe)( ;(process.env.TURBOPACK_DEV ? describe.skip : describe)(
......
...@@ -82,8 +82,10 @@ const runTests = (isDev) => { ...@@ -82,8 +82,10 @@ const runTests = (isDev) => {
linkPreload = { index, attribs } linkPreload = { index, attribs }
} }
}) })
expect(metaViewport.attribs.content).toContain('width=device-width') expect((metaViewport.attribs as any).content).toContain(
expect(linkPreload.attribs.imagesrcset).toMatch( 'width=device-width'
)
expect((linkPreload.attribs as any).imagesrcset).toMatch(
/%2F_next%2Fstatic%2Fmedia%2Ftest-rect\.(.*)\.jpg/g /%2F_next%2Fstatic%2Fmedia%2Ftest-rect\.(.*)\.jpg/g
) )
expect(metaViewport.index).toBeLessThan(linkPreload.index) expect(metaViewport.index).toBeLessThan(linkPreload.index)
......
...@@ -13,19 +13,16 @@ import { ...@@ -13,19 +13,16 @@ import {
initNextServerScript, initNextServerScript,
} from 'next-test-utils' } from 'next-test-utils'
let app
let appPort
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const context = {}
const startServer = async (optEnv = {}, opts) => { const startServer = async (optEnv = {}, opts?: any) => {
const scriptPath = join(appDir, 'server.js') const scriptPath = join(appDir, 'server.js')
context.appPort = await getPort() appPort = await getPort()
const env = Object.assign( const env = Object.assign({ ...process.env }, { PORT: `${appPort}` }, optEnv)
{ ...process.env },
{ PORT: `${context.appPort}` },
optEnv
)
context.server = await initNextServerScript(scriptPath, /ready on/i, env) app = await initNextServerScript(scriptPath, /ready on/i, env)
} }
// Tests are skipped in Turbopack because they are not relevant to Turbopack. // Tests are skipped in Turbopack because they are not relevant to Turbopack.
...@@ -42,33 +39,30 @@ const startServer = async (optEnv = {}, opts) => { ...@@ -42,33 +39,30 @@ const startServer = async (optEnv = {}, opts) => {
}) })
afterAll(async () => { afterAll(async () => {
global.isNextDev = originalIsNextDev global.isNextDev = originalIsNextDev
await killApp(context.server) await killApp(app)
}) })
it('should compile pages for SSR', async () => { it('should compile pages for SSR', async () => {
// The buffer of built page uses the on-demand-entries-ping to know which pages should be // The buffer of built page uses the on-demand-entries-ping to know which pages should be
// buffered. Therefore, we need to double each render call with a ping. // buffered. Therefore, we need to double each render call with a ping.
const pageContent = await renderViaHTTP(context.appPort, '/') const pageContent = await renderViaHTTP(appPort, '/')
expect(pageContent.includes('Index Page')).toBeTrue() expect(pageContent.includes('Index Page')).toBeTrue()
}) })
it('should compile pages for JSON page requests', async () => { it('should compile pages for JSON page requests', async () => {
await renderViaHTTP(context.appPort, '/about') await renderViaHTTP(appPort, '/about')
const pageFile = getPageFileFromBuildManifest(appDir, '/about') const pageFile = getPageFileFromBuildManifest(appDir, '/about')
const pageContent = await renderViaHTTP( const pageContent = await renderViaHTTP(appPort, join('/_next', pageFile))
context.appPort,
join('/_next', pageFile)
)
expect(pageContent.includes('About Page')).toBeTrue() expect(pageContent.includes('About Page')).toBeTrue()
}) })
it('should dispose inactive pages', async () => { it('should dispose inactive pages', async () => {
await renderViaHTTP(context.appPort, '/') await renderViaHTTP(appPort, '/')
// Render two pages after the index, since the server keeps at least two pages // Render two pages after the index, since the server keeps at least two pages
await renderViaHTTP(context.appPort, '/about') await renderViaHTTP(appPort, '/about')
await renderViaHTTP(context.appPort, '/third') await renderViaHTTP(appPort, '/third')
// Wait maximum of jest.setTimeout checking // Wait maximum of jest.setTimeout checking
// for disposing /about // for disposing /about
...@@ -90,7 +84,7 @@ const startServer = async (optEnv = {}, opts) => { ...@@ -90,7 +84,7 @@ const startServer = async (optEnv = {}, opts) => {
it('should navigate to pages with dynamic imports', async () => { it('should navigate to pages with dynamic imports', async () => {
let browser let browser
try { try {
browser = await webdriver(context.appPort, '/nav') browser = await webdriver(appPort, '/nav')
await browser.eval('document.getElementById("to-dynamic").click()') await browser.eval('document.getElementById("to-dynamic").click()')
......
...@@ -9,30 +9,29 @@ import { ...@@ -9,30 +9,29 @@ import {
File, File,
} from 'next-test-utils' } from 'next-test-utils'
let appPort
let app
const appDir = join(__dirname, '..') const appDir = join(__dirname, '..')
const context = {}
describe('MDX-rs Configuration', () => { describe('MDX-rs Configuration', () => {
describe('MDX-rs Plugin support', () => { describe('MDX-rs Plugin support', () => {
beforeAll(async () => { beforeAll(async () => {
context.appPort = await findPort() appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort) app = await launchApp(join(__dirname, '../'), appPort)
}) })
afterAll(async () => { afterAll(async () => {
await killApp(context.server) await killApp(app)
}) })
it('should render an MDX page correctly', async () => { it('should render an MDX page correctly', async () => {
expect(await renderViaHTTP(context.appPort, '/')).toMatch(/Hello MDX/) expect(await renderViaHTTP(appPort, '/')).toMatch(/Hello MDX/)
}) })
it('should render an MDX page with component correctly', async () => { it('should render an MDX page with component correctly', async () => {
expect(await renderViaHTTP(context.appPort, '/button')).toMatch( expect(await renderViaHTTP(appPort, '/button')).toMatch(/Look, a button!/)
/Look, a button!/
)
}) })
it('should render an MDX page with globally provided components (from `mdx-components.js`) correctly', async () => { it('should render an MDX page with globally provided components (from `mdx-components.js`) correctly', async () => {
expect(await renderViaHTTP(context.appPort, '/provider')).toMatch( expect(await renderViaHTTP(appPort, '/provider')).toMatch(
/Marker was rendered!/ /Marker was rendered!/
) )
}) })
...@@ -57,16 +56,16 @@ describe('MDX-rs Configuration', () => { ...@@ -57,16 +56,16 @@ describe('MDX-rs Configuration', () => {
}) })
`) `)
context.appPort = await findPort() appPort = await findPort()
context.server = await launchApp(join(__dirname, '../'), context.appPort) app = await launchApp(join(__dirname, '../'), appPort)
}) })
afterAll(async () => { afterAll(async () => {
await killApp(context.server) await killApp(app)
nextConfig.restore() nextConfig.restore()
}) })
it('should render an MDX page correctly', async () => { it('should render an MDX page correctly', async () => {
expect(await renderViaHTTP(context.appPort, '/gfm')).toMatch( expect(await renderViaHTTP(appPort, '/gfm')).toMatch(
/<table>\n<thead>\n<tr>\n<th>foo/ /<table>\n<thead>\n<tr>\n<th>foo/
) )
}) })
......
...@@ -52,7 +52,7 @@ describe('Prefetching Links in viewport', () => { ...@@ -52,7 +52,7 @@ describe('Prefetching Links in viewport', () => {
console.warn('Failed to proxy', err) console.warn('Failed to proxy', err)
}) })
await new Promise((resolve) => { await new Promise<void>((resolve) => {
proxyServer.listen(appPort, () => resolve()) proxyServer.listen(appPort, () => resolve())
}) })
}) })
...@@ -65,9 +65,9 @@ describe('Prefetching Links in viewport', () => { ...@@ -65,9 +65,9 @@ describe('Prefetching Links in viewport', () => {
nextDataRequests = [] nextDataRequests = []
const browser = await webdriver(appPort, '/') const browser = await webdriver(appPort, '/')
await browser.eval(function navigate() { await browser.eval(function navigate() {
window.next.router.push('/ssg/slow') ;(window as any).next.router.push('/ssg/slow')
window.next.router.push('/ssg/slow') ;(window as any).next.router.push('/ssg/slow')
window.next.router.push('/ssg/slow') ;(window as any).next.router.push('/ssg/slow')
}) })
await browser.waitForElementByCss('#content') await browser.waitForElementByCss('#content')
expect( expect(
...@@ -550,7 +550,7 @@ describe('Prefetching Links in viewport', () => { ...@@ -550,7 +550,7 @@ describe('Prefetching Links in viewport', () => {
'utf8' 'utf8'
) )
let self = {} let self: Record<string, any> = {}
// eslint-disable-next-line no-eval // eslint-disable-next-line no-eval
eval(content) eval(content)
expect([...self.__SSG_MANIFEST].sort()).toMatchInlineSnapshot(` expect([...self.__SSG_MANIFEST].sort()).toMatchInlineSnapshot(`
......
...@@ -54,18 +54,14 @@ const urlPaths = [ ...@@ -54,18 +54,14 @@ const urlPaths = [
const modePaths = ['fallback-blocking', 'fallback-false', 'fallback-true'] const modePaths = ['fallback-blocking', 'fallback-false', 'fallback-true']
const pagesDir = join(appDir, '.next/server/pages') const pagesDir = join(appDir, '.next/server/pages')
function runTests(isDev) { function runTests(isDev: boolean) {
if (!isDev) { if (!isDev) {
it('should output paths correctly', async () => { it('should output paths correctly', async () => {
for (const path of prerenderedPaths) { for (const path of prerenderedPaths) {
for (const mode of modePaths) { for (const mode of modePaths) {
console.log('checking output', { path, mode }) console.log('checking output', { path, mode })
expect(await fs.exists(join(pagesDir, mode, path + '.html'))).toBe( expect(fs.existsSync(join(pagesDir, mode, path + '.html'))).toBe(true)
true expect(fs.existsSync(join(pagesDir, mode, path + '.json'))).toBe(true)
)
expect(await fs.exists(join(pagesDir, mode, path + '.json'))).toBe(
true
)
} }
} }
}) })
...@@ -112,18 +108,12 @@ function runTests(isDev) { ...@@ -112,18 +108,12 @@ function runTests(isDev) {
// we don't block on writing incremental data to the // we don't block on writing incremental data to the
// disk so use check // disk so use check
await check( await check(
() => () => fs.existsSync(join(pagesDir, mode, path + '.html')),
fs true
.exists(join(pagesDir, mode, path + '.html'))
.then((res) => (res ? 'yes' : 'no')),
'yes'
) )
await check( await check(
() => () => fs.existsSync(join(pagesDir, mode, path + '.json')),
fs true
.exists(join(pagesDir, mode, path + '.json'))
.then((res) => (res ? 'yes' : 'no')),
'yes'
) )
} }
...@@ -352,7 +342,7 @@ describe('Fallback path encoding', () => { ...@@ -352,7 +342,7 @@ describe('Fallback path encoding', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests(false)
} }
) )
}) })
...@@ -80,7 +80,7 @@ function runTests(startServer = nextStart) { ...@@ -80,7 +80,7 @@ function runTests(startServer = nextStart) {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map((cookieRaw) => cookie.parse(cookieRaw))
expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true) expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true)
...@@ -106,7 +106,7 @@ function runTests(startServer = nextStart) { ...@@ -106,7 +106,7 @@ function runTests(startServer = nextStart) {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map((cookieRaw) => cookie.parse(cookieRaw))
expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true) expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true)
...@@ -126,7 +126,7 @@ function runTests(startServer = nextStart) { ...@@ -126,7 +126,7 @@ function runTests(startServer = nextStart) {
expect(res.status).toBe(200) expect(res.status).toBe(200)
const originalCookies = res.headers.get('set-cookie').split(',') const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse) const cookies = originalCookies.map((cookieRaw) => cookie.parse(cookieRaw))
expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true) expect(originalCookies.every((c) => c.includes('; Secure;'))).toBe(true)
...@@ -189,7 +189,7 @@ function runTests(startServer = nextStart) { ...@@ -189,7 +189,7 @@ function runTests(startServer = nextStart) {
.get('set-cookie') .get('set-cookie')
.replace(/(=(?!Lax)\w{3}),/g, '$1') .replace(/(=(?!Lax)\w{3}),/g, '$1')
.split(',') .split(',')
.map(cookie.parse) .map((cookieRaw) => cookie.parse(cookieRaw))
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
expect(cookies[0]).toMatchObject({ expect(cookies[0]).toMatchObject({
...@@ -221,7 +221,7 @@ function runTests(startServer = nextStart) { ...@@ -221,7 +221,7 @@ function runTests(startServer = nextStart) {
.get('set-cookie') .get('set-cookie')
.replace(/(=(?!Lax)\w{3}),/g, '$1') .replace(/(=(?!Lax)\w{3}),/g, '$1')
.split(',') .split(',')
.map(cookie.parse) .map((cookieRaw) => cookie.parse(cookieRaw))
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
expect(cookies[0]).toMatchObject({ expect(cookies[0]).toMatchObject({
...@@ -286,7 +286,7 @@ describe('Prerender Preview Mode', () => { ...@@ -286,7 +286,7 @@ describe('Prerender Preview Mode', () => {
const cookies = res.headers const cookies = res.headers
.get('set-cookie') .get('set-cookie')
.split(',') .split(',')
.map(cookie.parse) .map((cookieRaw) => cookie.parse(cookieRaw))
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
previewCookieString = previewCookieString =
...@@ -324,7 +324,7 @@ describe('Prerender Preview Mode', () => { ...@@ -324,7 +324,7 @@ describe('Prerender Preview Mode', () => {
.get('set-cookie') .get('set-cookie')
.replace(/(=(?!Lax)\w{3}),/g, '$1') .replace(/(=(?!Lax)\w{3}),/g, '$1')
.split(',') .split(',')
.map(cookie.parse) .map((cookieRaw) => cookie.parse(cookieRaw))
expect(cookies.length).toBe(2) expect(cookies.length).toBe(2)
}) })
......
...@@ -109,7 +109,7 @@ describe('SSG Prerender Revalidate', () => { ...@@ -109,7 +109,7 @@ describe('SSG Prerender Revalidate', () => {
app = await nextStart(appDir, appPort, { app = await nextStart(appDir, appPort, {
// The lowest size of the LRU cache that can be set is "1" // The lowest size of the LRU cache that can be set is "1"
// this will cause the cache size to always be exceeded // this will cause the cache size to always be exceeded
env: { __NEXT_TEST_MAX_ISR_CACHE: 1 }, env: { __NEXT_TEST_MAX_ISR_CACHE: '1' },
}) })
buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8') buildId = await fs.readFile(join(appDir, '.next/BUILD_ID'), 'utf8')
}) })
......
...@@ -26,7 +26,7 @@ const getCacheFile = (path = '') => { ...@@ -26,7 +26,7 @@ const getCacheFile = (path = '') => {
return join(appDir, '.next', 'server', 'pages', path) return join(appDir, '.next', 'server', 'pages', path)
} }
function runTests(isDev) { function runTests(isDev: boolean) {
it('should get preview cookie correctly', async () => { it('should get preview cookie correctly', async () => {
const res = await fetchViaHTTP(appPort, '/api/enable') const res = await fetchViaHTTP(appPort, '/api/enable')
previewCookie = '' previewCookie = ''
...@@ -39,15 +39,15 @@ function runTests(isDev) { ...@@ -39,15 +39,15 @@ function runTests(isDev) {
.get('set-cookie') .get('set-cookie')
.split(',') .split(',')
.forEach((c) => { .forEach((c) => {
c = cookie.parse(c) const cookies = cookie.parse(c)
const isBypass = c.__prerender_bypass const isBypass = cookies.__prerender_bypass
if (isBypass || c.__next_preview_data) { if (isBypass || cookies.__next_preview_data) {
if (previewCookie) previewCookie += '; ' if (previewCookie) previewCookie += '; '
previewCookie += `${ previewCookie += `${
isBypass ? '__prerender_bypass' : '__next_preview_data' isBypass ? '__prerender_bypass' : '__next_preview_data'
}=${c[isBypass ? '__prerender_bypass' : '__next_preview_data']}` }=${cookies[isBypass ? '__prerender_bypass' : '__next_preview_data']}`
} }
}) })
}) })
...@@ -155,9 +155,7 @@ function runTests(isDev) { ...@@ -155,9 +155,7 @@ function runTests(isDev) {
}) })
if (!isDev) { if (!isDev) {
expect(await fs.exists(getCacheFile('no-fallback/second.html'))).toBe( expect(fs.existsSync(getCacheFile('no-fallback/second.html'))).toBe(false)
false
)
} }
const res2 = await fetchViaHTTP(appPort, '/no-fallback/second') const res2 = await fetchViaHTTP(appPort, '/no-fallback/second')
...@@ -290,7 +288,7 @@ describe('Preview mode with fallback pages', () => { ...@@ -290,7 +288,7 @@ describe('Preview mode with fallback pages', () => {
}) })
afterAll(() => killApp(app)) afterAll(() => killApp(app))
runTests() runTests(false)
} }
) )
}) })
...@@ -41,7 +41,7 @@ describe('Production Config Usage', () => { ...@@ -41,7 +41,7 @@ describe('Production Config Usage', () => {
describe('env', () => { describe('env', () => {
it('should fail with leading __ in env key', async () => { it('should fail with leading __ in env key', async () => {
const result = await runNextCommand(['build', appDir], { const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_FAIL_UNDERSCORE: true }, env: { ENABLE_ENV_FAIL_UNDERSCORE: 'true' },
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
...@@ -51,7 +51,7 @@ describe('Production Config Usage', () => { ...@@ -51,7 +51,7 @@ describe('Production Config Usage', () => {
it('should fail with NODE_ in env key', async () => { it('should fail with NODE_ in env key', async () => {
const result = await runNextCommand(['build', appDir], { const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_FAIL_NODE: true }, env: { ENABLE_ENV_FAIL_NODE: 'true' },
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
...@@ -61,7 +61,7 @@ describe('Production Config Usage', () => { ...@@ -61,7 +61,7 @@ describe('Production Config Usage', () => {
it('should fail with NEXT_RUNTIME in env key', async () => { it('should fail with NEXT_RUNTIME in env key', async () => {
const result = await runNextCommand(['build', appDir], { const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_NEXT_PRESERVED: true }, env: { ENABLE_ENV_NEXT_PRESERVED: 'true' },
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
...@@ -71,7 +71,7 @@ describe('Production Config Usage', () => { ...@@ -71,7 +71,7 @@ describe('Production Config Usage', () => {
it('should allow __ within env key', async () => { it('should allow __ within env key', async () => {
const result = await runNextCommand(['build', appDir], { const result = await runNextCommand(['build', appDir], {
env: { ENABLE_ENV_WITH_UNDERSCORES: true }, env: { ENABLE_ENV_WITH_UNDERSCORES: 'true' },
stdout: true, stdout: true,
stderr: true, stderr: true,
}) })
......
...@@ -17665,7 +17665,7 @@ ...@@ -17665,7 +17665,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/module-ids/test/index.test.js": { "test/integration/module-ids/test/index.test.ts": {
"passed": [], "passed": [],
"failed": [], "failed": [],
"pending": [ "pending": [
...@@ -18872,7 +18872,7 @@ ...@@ -18872,7 +18872,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/preload-viewport/test/index.test.js": { "test/integration/preload-viewport/test/index.test.ts": {
"passed": [ "passed": [
"Prefetching Links in viewport production mode should correctly omit pre-generated dynamic pages from SSG manifest", "Prefetching Links in viewport production mode should correctly omit pre-generated dynamic pages from SSG manifest",
"Prefetching Links in viewport production mode should de-dupe inflight SSG requests", "Prefetching Links in viewport production mode should de-dupe inflight SSG requests",
...@@ -19634,7 +19634,7 @@ ...@@ -19634,7 +19634,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/module-ids/test/index.test.js": { "test/integration/module-ids/test/index.test.ts": {
"passed": [], "passed": [],
"failed": [], "failed": [],
"pending": [ "pending": [
...@@ -20843,7 +20843,7 @@ ...@@ -20843,7 +20843,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/preload-viewport/test/index.test.js": { "test/integration/preload-viewport/test/index.test.ts": {
"passed": [], "passed": [],
"failed": [], "failed": [],
"pending": [ "pending": [
...@@ -15564,7 +15564,7 @@ ...@@ -15564,7 +15564,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/module-ids/test/index.test.js": { "test/integration/module-ids/test/index.test.ts": {
"passed": [ "passed": [
"minified module ids production mode should have no long module id for the next client runtime module", "minified module ids production mode should have no long module id for the next client runtime module",
"minified module ids production mode should have no long module ids for async loader modules", "minified module ids production mode should have no long module ids for async loader modules",
...@@ -16761,7 +16761,7 @@ ...@@ -16761,7 +16761,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/preload-viewport/test/index.test.js": { "test/integration/preload-viewport/test/index.test.ts": {
"passed": [ "passed": [
"Prefetching Links in viewport production mode should correctly omit pre-generated dynamic pages from SSG manifest", "Prefetching Links in viewport production mode should correctly omit pre-generated dynamic pages from SSG manifest",
"Prefetching Links in viewport production mode should de-dupe inflight SSG requests", "Prefetching Links in viewport production mode should de-dupe inflight SSG requests",
...@@ -19086,7 +19086,7 @@ ...@@ -19086,7 +19086,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/module-ids/test/index.test.js": { "test/integration/module-ids/test/index.test.ts": {
"passed": [ "passed": [
"minified module ids development mode should have long module id for the next client runtime module", "minified module ids development mode should have long module id for the next client runtime module",
"minified module ids development mode should have long module ids for async loader modules", "minified module ids development mode should have long module ids for async loader modules",
...@@ -20288,7 +20288,7 @@ ...@@ -20288,7 +20288,7 @@
"flakey": [], "flakey": [],
"runtimeError": false "runtimeError": false
}, },
"test/integration/preload-viewport/test/index.test.js": { "test/integration/preload-viewport/test/index.test.ts": {
"passed": [], "passed": [],
"failed": [], "failed": [],
"pending": [ "pending": [
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