Unverified Commit 5d54eaaf authored by Leah's avatar Leah Committed by GitHub

type check tests (and convert next-test-utils.js to ts) (#51071)

Enables type checking for tests in CI and fixes a bunch of things related to that
parent d457e989
......@@ -26,6 +26,7 @@
"genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js",
"git-reset": "git reset --hard HEAD",
"git-clean": "git clean -d -x -e node_modules -e packages -f",
"typescript": "tsc --noEmit",
"lint-typescript": "turbo run typescript",
"lint-eslint": "eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.json --no-eslintrc",
"lint-no-typescript": "run-p prettier-check lint-eslint lint-language",
......@@ -84,7 +85,10 @@
"@swc/helpers": "0.5.1",
"@testing-library/react": "13.0.0",
"@types/cheerio": "0.22.16",
"@types/cookie": "0.3.3",
"@types/cross-spawn": "6.0.0",
"@types/fs-extra": "8.1.0",
"@types/glob": "7.1.1",
"@types/html-validator": "5.0.3",
"@types/http-proxy": "1.17.3",
"@types/jest": "24.0.13",
......@@ -171,6 +175,7 @@
"open": "9.0.0",
"outdent": "0.8.0",
"pixrem": "5.0.0",
"playwright-core": "1.28.1",
"playwright-chromium": "1.28.1",
"plop": "3.0.5",
"postcss": "8.4.14",
......
......@@ -77,11 +77,11 @@ function checkRedirect(route: Redirect): {
const invalidParts: string[] = []
let hadInvalidStatus: boolean = false
if (route.statusCode && !allowedStatusCodes.has(route.statusCode)) {
if (route.statusCode && !allowedStatusCodes.has(route['statusCode'])) {
hadInvalidStatus = true
invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`)
}
if (typeof route.permanent !== 'boolean' && !route.statusCode) {
if (typeof route.permanent !== 'boolean' && !route['statusCode']) {
invalidParts.push(`\`permanent\` is not set to \`true\` or \`false\``)
}
......
......@@ -57,7 +57,7 @@ export async function patchIncorrectLockfile(dir: string) {
const lockfileParsed = JSON.parse(content)
const lockfileVersion = parseInt(lockfileParsed?.lockfileVersion, 10)
const expectedSwcPkgs = Object.keys(nextPkgJson.optionalDependencies || {})
const expectedSwcPkgs = Object.keys(nextPkgJson['optionalDependencies'] || {})
const patchDependency = (
pkg: string,
......
......@@ -43,7 +43,10 @@ importers:
'@swc/helpers': 0.5.1
'@testing-library/react': 13.0.0
'@types/cheerio': 0.22.16
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/fs-extra': 8.1.0
'@types/glob': 7.1.1
'@types/html-validator': 5.0.3
'@types/http-proxy': 1.17.3
'@types/jest': 24.0.13
......@@ -131,6 +134,7 @@ importers:
outdent: 0.8.0
pixrem: 5.0.0
playwright-chromium: 1.28.1
playwright-core: 1.28.1
plop: 3.0.5
postcss: 8.4.14
postcss-nested: 4.2.1
......@@ -211,7 +215,10 @@ importers:
'@swc/helpers': 0.5.1
'@testing-library/react': 13.0.0_biqbaboplfbrettd7655fr4n2y
'@types/cheerio': 0.22.16
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/fs-extra': 8.1.0
'@types/glob': 7.1.1
'@types/html-validator': 5.0.3
'@types/http-proxy': 1.17.3
'@types/jest': 24.0.13
......@@ -299,6 +306,7 @@ importers:
outdent: 0.8.0
pixrem: 5.0.0
playwright-chromium: 1.28.1
playwright-core: 1.28.1
plop: 3.0.5
postcss: 8.4.14
postcss-nested: 4.2.1
......
......@@ -100,7 +100,7 @@ createNextDescribe(
it('should support setting cookies in route handlers with the correct overrides', async () => {
const res = await next.fetch('/handler')
const setCookieHeader = res.headers.get('set-cookie') as any as string[]
const setCookieHeader = res.headers.get('set-cookie')
expect(setCookieHeader).toContain('bar=bar2; Path=/')
expect(setCookieHeader).toContain('baz=baz2; Path=/')
expect(setCookieHeader).toContain('foo=foo1; Path=/')
......
......@@ -3,6 +3,7 @@ import path from 'path'
import cheerio from 'cheerio'
import { check, withQuery } from 'next-test-utils'
import { createNextDescribe, FileRef } from 'e2e-utils'
import type { Response } from 'node-fetch'
createNextDescribe(
'app-dir with middleware',
......
import type { Request } from 'playwright-core'
import { createNextDescribe } from 'e2e-utils'
import type { BrowserInterface } from '../../../lib/browsers/base'
const getPathname = (url: string) => {
const urlObj = new URL(url)
......
......@@ -58,7 +58,12 @@ type Cookies = {
* @returns any injected metadata on the request
*/
export function getRequestMeta(
headersOrCookies: Headers | Cookies | ReadonlyHeaders | ReadonlyRequestCookies
headersOrCookies:
| Headers
| import('node-fetch').Headers
| Cookies
| ReadonlyHeaders
| ReadonlyRequestCookies
): Record<string, any> {
const headerOrCookie = headersOrCookies.get(KEY)
if (!headerOrCookie) return {}
......
......@@ -70,7 +70,7 @@ if (!(globalThis as any).isNextStart) {
/Listening on/,
{
...process.env,
PORT: appPort,
PORT: appPort.toString(),
},
undefined,
{
......
import { createNextDescribe } from 'e2e-utils'
import type { Response } from 'node-fetch'
import cookies, { nextConfigHeaders } from './cookies.mjs'
function getSetCookieHeaders(res: globalThis.Response): ReadonlyArray<string> {
function getSetCookieHeaders(res: Response): ReadonlyArray<string> {
return (
(res.headers as any).getSetCookie?.() ??
(res.headers as any).raw()['set-cookie']
......
......@@ -3,6 +3,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import FormData from 'form-data'
import path from 'path'
import type { Response } from 'node-fetch'
async function serialize(response: Response) {
return {
......
......@@ -5,6 +5,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import cheerio from 'cheerio'
import type { Response } from 'node-fetch'
describe('Middleware Request Headers Overrides', () => {
let next: NextInstance
......
import { FileRef, createNext, NextInstance } from 'e2e-utils'
import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path'
import { spawn } from 'cross-spawn'
import spawn from 'cross-spawn'
describe('next/font/google with proxy', () => {
let next: NextInstance
......@@ -22,8 +22,8 @@ describe('next/font/google with proxy', () => {
stdio: 'inherit',
env: {
...process.env,
PROXY_PORT,
SERVER_PORT,
PROXY_PORT: PROXY_PORT.toString(),
SERVER_PORT: SERVER_PORT.toString(),
},
})
......
......@@ -1850,8 +1850,8 @@ describe('Prerender', () => {
previewRes.headers
.get('set-cookie')
.split(',')
.forEach((c) => {
c = cookie.parse(c)
.forEach((s) => {
const c = cookie.parse(s)
const isBypass = c.__prerender_bypass
if (isBypass || c.__next_preview_data) {
......
......@@ -11,6 +11,7 @@ import {
import webdriver from 'next-webdriver'
import { join } from 'path'
import fs from 'fs'
import type { Response } from 'node-fetch'
const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js'))
......
......@@ -43,7 +43,10 @@ describe('Test Draft Mode', () => {
const res = await fetchViaHTTP(appPort, '/api/enable')
expect(res.status).toBe(200)
const cookies = res.headers.get('set-cookie').split(',').map(cookie.parse)
const cookies = res.headers
.get('set-cookie')
.split(',')
.map((c) => cookie.parse(c))
expect(cookies[0]).toBeTruthy()
expect(cookies[0].__prerender_bypass).toBeTruthy()
......@@ -76,7 +79,7 @@ describe('Test Draft Mode', () => {
.get('set-cookie')
.replace(/(=(?!Lax)\w{3}),/g, '$1')
.split(',')
.map(cookie.parse)
.map((c) => cookie.parse(c))
expect(cookies[0]).toBeTruthy()
})
......@@ -154,7 +157,7 @@ describe('Test Draft Mode', () => {
expect(res.status).toBe(200)
const originalCookies = res.headers.get('set-cookie').split(',')
const cookies = originalCookies.map(cookie.parse)
const cookies = originalCookies.map((c) => cookie.parse(c))
expect(cookies.length).toBe(1)
expect(cookies[0]).toBeTruthy()
......@@ -212,7 +215,7 @@ describe('Test Draft Mode', () => {
.get('set-cookie')
.replace(/(=(?!Lax)\w{3}),/g, '$1')
.split(',')
.map(cookie.parse)
.map((c) => cookie.parse(c))
expect(cookies[0]).toBeTruthy()
expect(cookies[0]).toMatchObject({
......
......@@ -12,8 +12,20 @@
"moduleResolution": "node",
"resolveJsonModule": true,
"isolatedModules": true,
"jsx": "preserve"
"jsx": "preserve",
"baseUrl": "../../..",
"paths": {
"development-sandbox": ["test/lib/development-sandbox"],
"next-test-utils": ["test/lib/next-test-utils"],
"amp-test-utils": ["test/lib/amp-test-utils"],
"next-webdriver": ["test/lib/next-webdriver"],
"e2e-utils": ["test/lib/e2e-utils"]
}
},
"include": ["next-env.d.ts", "**/*.ts", "**/*.tsx"],
"include": [
"test/integration/draft-mode/next-env.d.ts",
"test/integration/draft-mode/**/*.ts",
"test/integration/draft-mode/**/*.tsx"
],
"exclude": ["node_modules"]
}
......@@ -54,7 +54,7 @@ describe('dev mode', () => {
context.appPort = await findPort()
context.app = await launchApp(appDir, context.appPort, {
...context.handler,
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
})
})
......
......@@ -69,7 +69,7 @@ describe.each([
output = ''
appPort = await findPort()
app = await launchApp(appDir, appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 },
env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
onStdout(msg) {
output += msg
},
......
......@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => {
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const app = await launchApp(appDir, await findPort(), [])
const app = await launchApp(appDir, await findPort())
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
......@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => {
nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages')
)
const app = await launchApp(appDir, await findPort(), [])
const app = await launchApp(appDir, await findPort())
await killApp(app)
await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
// @ts-ignore
import * as matchers from 'jest-extended'
expect.extend(matchers)
......
import 'jest-extended'
/// <reference types="jest" />
/// <reference types="jest-extended" />
declare namespace jest {
// https://github.com/jestjs/jest/blob/6460335f88cee3dcb9d29c49d55ab02b9d83f994/packages/expect/src/types.ts#L58-L72
interface MatcherState {
assertionCalls: number
currentTestName?: string
error?: Error
expand?: boolean
expectedAssertionsNumber: number | null
expectedAssertionsNumberError?: Error
isExpectingAssertions: boolean
isExpectingAssertionsError?: Error
isNot?: boolean
numPassingAsserts: number
promise?: string
suppressedErrors: Array<Error>
testPath?: string
}
interface Expect {
// https://github.com/jestjs/jest/blob/6460335f88cee3dcb9d29c49d55ab02b9d83f994/packages/expect/src/index.ts#L461
// https://github.com/jestjs/jest/blob/6460335f88cee3dcb9d29c49d55ab02b9d83f994/packages/expect/src/jestMatchersObject.ts#L44-L45
getState(): MatcherState
}
}
......@@ -6,22 +6,29 @@ export type Event = 'request'
* methods we aim to support across tests
*
* They will always await last executed command.
* The interface is mutable - it doesn't have to be in sequece.
* The interface is mutable - it doesn't have to be in sequence.
*
* You can manually await this interface to wait for completion of the last scheduled command.
*/
export class BrowserInterface implements PromiseLike<any> {
private promise: any
then: PromiseLike<any>['then']
private catch: any
export abstract class BrowserInterface implements PromiseLike<any> {
private promise?: Promise<any>
then: Promise<any>['then']
catch: Promise<any>['catch']
finally: Promise<any>['finally'];
protected chain(nextCall: any): BrowserInterface {
// necessary for the type of the function below
readonly [Symbol.toStringTag]: string = 'BrowserInterface'
protected chain<T>(
nextCall: (current: any) => T | PromiseLike<T>
): BrowserInterface & Promise<T> {
if (!this.promise) {
this.promise = Promise.resolve(this)
}
this.promise = this.promise.then(nextCall)
this.then = (...args) => this.promise.then(...args)
this.catch = (...args) => this.promise.catch(...args)
this.finally = (...args) => this.promise.finally(...args)
return this
}
......
......@@ -28,6 +28,11 @@ export async function quit() {
browser = undefined
}
interface ElementHandleExt extends ElementHandle {
getComputedCss(prop: string): Promise<string>
text(): Promise<string>
}
export class Playwright extends BrowserInterface {
private activeTrace?: string
private eventCallbacks: Record<Event, Set<(...args: any[]) => void>> = {
......@@ -95,7 +100,7 @@ export class Playwright extends BrowserInterface {
}
async get(url: string): Promise<void> {
return page.goto(url) as any
await page.goto(url)
}
async loadPage(
......@@ -192,18 +197,18 @@ export class Playwright extends BrowserInterface {
}
back(): BrowserInterface {
return this.chain(() => {
return page.goBack()
return this.chain(async () => {
await page.goBack()
})
}
forward(): BrowserInterface {
return this.chain(() => {
return page.goForward()
return this.chain(async () => {
await page.goForward()
})
}
refresh(): BrowserInterface {
return this.chain(() => {
return page.reload()
return this.chain(async () => {
await page.reload()
})
}
setDimensions({
......@@ -234,29 +239,22 @@ export class Playwright extends BrowserInterface {
return this.chain(() => page.bringToFront())
}
private wrapElement(el: ElementHandle, selector: string) {
;(el as any).selector = selector
;(el as any).text = () => el.innerText()
;(el as any).getComputedCss = (prop) =>
page.evaluate(
private wrapElement(el: ElementHandle, selector: string): ElementHandleExt {
function getComputedCss(prop: string) {
return page.evaluate(
function (args) {
return (
getComputedStyle(document.querySelector(args.selector))[
args.prop
] || null
)
const style = getComputedStyle(document.querySelector(args.selector))
return style[args.prop] || null
},
{ selector, prop }
)
;(el as any).getCssValue = (el as any).getComputedCss
;(el as any).getValue = () =>
page.evaluate(
function (args) {
return (document.querySelector(args.selector) as any).value
},
{ selector }
)
return el
}
return Object.assign(el, {
selector,
getComputedCss,
text: () => el.innerText(),
})
}
elementByCss(selector: string) {
......@@ -268,38 +266,31 @@ export class Playwright extends BrowserInterface {
}
getValue() {
return this.chain((el) =>
page.evaluate(
function (args) {
return document.querySelector(args.selector).value
},
{ selector: el.selector }
)
) as any
return this.chain((el: ElementHandleExt) => el.inputValue())
}
text() {
return this.chain((el) => el.text()) as any
return this.chain((el: ElementHandleExt) => el.innerText())
}
type(text) {
return this.chain((el) => el.type(text))
return this.chain((el: ElementHandleExt) => el.type(text))
}
moveTo() {
return this.chain((el) => {
return page.hover(el.selector).then(() => el)
return this.chain((el: ElementHandleExt) => {
return el.hover().then(() => el)
})
}
async getComputedCss(prop: string) {
return this.chain((el) => {
return el.getCssValue(prop)
return this.chain((el: ElementHandleExt) => {
return el.getComputedCss(prop)
}) as any
}
async getAttribute<T = any>(attr) {
return this.chain((el) => el.getAttribute(attr)) as T
return this.chain((el: ElementHandleExt) => el.getAttribute(attr)) as T
}
hasElementByCssSelector(selector: string) {
......@@ -307,25 +298,25 @@ export class Playwright extends BrowserInterface {
}
keydown(key: string): BrowserInterface {
return this.chain((el) => {
return this.chain((el: ElementHandleExt) => {
return page.keyboard.down(key).then(() => el)
})
}
keyup(key: string): BrowserInterface {
return this.chain((el) => {
return this.chain((el: ElementHandleExt) => {
return page.keyboard.up(key).then(() => el)
})
}
click() {
return this.chain((el) => {
return this.chain((el: ElementHandleExt) => {
return el.click().then(() => el)
})
}
touchStart() {
return this.chain((el: ElementHandle) => {
return this.chain((el: ElementHandleExt) => {
return el.dispatchEvent('touchstart').then(() => el)
})
}
......
......@@ -41,7 +41,6 @@ export async function sandbox(
await next.start()
const browser = await webdriver(next.url, initialUrl, webDriverOptions)
// await waitForHydration(browser)
return {
browser,
session: {
......
import { spawn } from 'cross-spawn'
import spawn from 'cross-spawn'
import { Span } from 'next/src/trace'
import { NextInstance } from './base'
......
import path from 'path'
import fs from 'fs-extra'
import { NextInstance } from './base'
import { spawn, SpawnOptions } from 'cross-spawn'
import spawn from 'cross-spawn'
import { Span } from 'next/src/trace'
export class NextStartInstance extends NextInstance {
private _buildId: string
private _cliOutput: string = ''
private spawnOpts: SpawnOptions
private spawnOpts: import('child_process').SpawnOptions
public get buildId() {
return this._buildId
......
import spawn from 'cross-spawn'
import express from 'express'
import {
existsSync,
......@@ -7,27 +6,45 @@ import {
writeFileSync,
createReadStream,
} from 'fs'
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import { promisify } from 'util'
import http from 'http'
import https from 'https'
import server from 'next/dist/server/next'
import _pkg from 'next/package.json'
import fetch from 'node-fetch'
import path from 'path'
import spawn from 'cross-spawn'
import { writeFile } from 'fs-extra'
import getPort from 'get-port'
import fetch from 'node-fetch'
import qs from 'querystring'
import treeKill from 'tree-kill'
import server from 'next/dist/server/next'
import _pkg from 'next/package.json'
import type { SpawnOptions, ChildProcess } from 'child_process'
import type { RequestInit, Response } from 'node-fetch'
import type { NextServer } from 'next/dist/server/next'
import type { BrowserInterface } from './browsers/base'
import { shouldRunTurboDevTest } from './turbo'
export { shouldRunTurboDevTest }
export const nextServer = server
export const pkg = _pkg
export function initNextServerScript(
scriptPath,
successRegexp,
env,
failRegexp,
opts
) {
scriptPath: string,
successRegexp: RegExp,
env: NodeJS.ProcessEnv,
failRegexp?: RegExp,
opts?: {
cwd?: string
nodeArgs?: string[]
onStdout?: (data: any) => void
onStderr?: (data: any) => void
}
): Promise<ChildProcess> {
return new Promise((resolve, reject) => {
const instance = spawn(
'node',
......@@ -83,13 +100,11 @@ export function initNextServerScript(
})
}
/**
* @param {string | number} appPortOrUrl
* @param {string} [url]
* @param {string} [hostname]
* @returns
*/
export function getFullUrl(appPortOrUrl, url, hostname) {
export function getFullUrl(
appPortOrUrl: string | number,
url?: string,
hostname?: string
) {
let fullUrl =
typeof appPortOrUrl === 'string' && appPortOrUrl.startsWith('http')
? appPortOrUrl
......@@ -114,11 +129,14 @@ export function getFullUrl(appPortOrUrl, url, hostname) {
/**
* 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
* @param pathname the pathname
* @param query the query object to add to the pathname
* @returns the pathname with the query
*/
export function withQuery(pathname, query) {
export function withQuery(
pathname: string,
query: Record<string, any> | string
) {
const querystring = typeof query === 'string' ? query : qs.stringify(query)
if (querystring.length === 0) {
return pathname
......@@ -133,30 +151,12 @@ export function withQuery(pathname, query) {
return `${pathname}?${querystring}`
}
export function renderViaAPI(app, pathname, query) {
const url = query ? withQuery(pathname, query) : pathname
return app.renderToHTML({ url }, {}, pathname, query)
}
/**
* @param {string | number} appPort
* @param {string} pathname
* @param {Record<string, any> | string | undefined} [query]
* @param {import('node-fetch').RequestInit} [opts]
* @returns {Promise<string>}
*/
export function renderViaHTTP(appPort, pathname, query, opts) {
return fetchViaHTTP(appPort, pathname, query, opts).then((res) => res.text())
}
/**
* @param {string | number} appPort
* @param {string} pathname
* @param {Record<string, any> | string | null | undefined} [query]
* @param {import('node-fetch').RequestInit} [opts]
* @returns {Promise<Response & {buffer: any} & {headers: Headers}>}
*/
export function fetchViaHTTP(appPort, pathname, query, opts) {
export function fetchViaHTTP(
appPort: string | number,
pathname: string,
query?: Record<string, any> | string | null | undefined,
opts?: RequestInit
): Promise<Response> {
const url = query ? withQuery(pathname, query) : pathname
return fetch(getFullUrl(appPort, url), {
// in node.js v17 fetch favors IPv6 but Next.js is
......@@ -173,18 +173,50 @@ export function fetchViaHTTP(appPort, pathname, query, opts) {
})
}
export function renderViaHTTP(
appPort: string | number,
pathname: string,
query?: Record<string, any> | string | undefined,
opts?: RequestInit
) {
return fetchViaHTTP(appPort, pathname, query, opts).then((res) => res.text())
}
export function findPort() {
return getPort()
}
export function runNextCommand(argv, options = {}) {
export interface NextOptions {
cwd?: string
env?: NodeJS.Dict<string>
nodeArgs?: string[]
spawnOptions?: SpawnOptions
instance?: (instance: ChildProcess) => void
stderr?: true | 'log'
stdout?: true | 'log'
ignoreFail?: boolean
onStdout?: (data: any) => void
onStderr?: (data: any) => void
}
export function runNextCommand(
argv: string[],
options: NextOptions = {}
): Promise<{
code: number
signal: NodeJS.Signals
stdout: string
stderr: string
}> {
const nextDir = path.dirname(require.resolve('next/package'))
const nextBin = path.join(nextDir, 'dist/bin/next')
const cwd = options.cwd || nextDir
// Let Next.js decide the environment
const env = {
...process.env,
NODE_ENV: '',
NODE_ENV: undefined,
__NEXT_TEST_MODE: 'true',
...options.env,
}
......@@ -279,14 +311,35 @@ export function runNextCommand(argv, options = {}) {
})
instance.on('error', (err) => {
err.stdout = stdoutOutput
err.stderr = stderrOutput
err['stdout'] = stdoutOutput
err['stderr'] = stderrOutput
reject(err)
})
})
}
export function runNextCommandDev(argv, stdOut, opts = {}) {
export interface NextDevOptions {
cwd?: string
env?: NodeJS.Dict<string>
nodeArgs?: string[]
nextBin?: string
bootupMarker?: RegExp
nextStart?: boolean
turbo?: boolean
stderr?: false
stdout?: false
onStdout?: (data: any) => void
onStderr?: (data: any) => void
}
export function runNextCommandDev(
argv: string[],
stdOut?: boolean,
opts: NextDevOptions = {}
): Promise<(typeof stdOut extends true ? string : ChildProcess) | undefined> {
const nextDir = path.dirname(require.resolve('next/package'))
const nextBin = opts.nextBin || path.join(nextDir, 'dist/bin/next')
const cwd = opts.cwd || nextDir
......@@ -363,7 +416,7 @@ export function runNextCommandDev(argv, stdOut, opts = {}) {
instance.stderr.removeListener('data', handleStderr)
if (!didResolve) {
didResolve = true
resolve()
resolve(undefined)
}
})
......@@ -374,12 +427,18 @@ export function runNextCommandDev(argv, stdOut, opts = {}) {
}
// Launch the app in dev mode.
export function launchApp(dir, port, opts) {
export function launchApp(
dir: string,
port: string | number,
opts?: NextDevOptions
) {
const options = opts ?? {}
const useTurbo = shouldRunTurboDevTest()
return runNextCommandDev(
[useTurbo ? '--turbo' : undefined, dir, '-p', port].filter(Boolean),
[useTurbo ? '--turbo' : undefined, dir, '-p', port as string].filter(
Boolean
),
undefined,
{
...options,
......@@ -388,30 +447,46 @@ export function launchApp(dir, port, opts) {
)
}
export function nextBuild(dir, args = [], opts = {}) {
export function nextBuild(
dir: string,
args: string[] = [],
opts: NextOptions = {}
) {
return runNextCommand(['build', dir, ...args], opts)
}
export function nextExport(dir, { outdir }, opts = {}) {
export function nextExport(dir: string, { outdir }, opts: NextOptions = {}) {
return runNextCommand(['export', dir, '--outdir', outdir], opts)
}
export function nextExportDefault(dir, opts = {}) {
export function nextExportDefault(dir: string, opts: NextOptions = {}) {
return runNextCommand(['export', dir], opts)
}
export function nextLint(dir, args = [], opts = {}) {
export function nextLint(
dir: string,
args: string[] = [],
opts: NextOptions = {}
) {
return runNextCommand(['lint', dir, ...args], opts)
}
export function nextStart(dir, port, opts = {}) {
return runNextCommandDev(['start', '-p', port, dir], undefined, {
export function nextStart(
dir: string,
port: string | number,
opts: NextDevOptions = {}
) {
return runNextCommandDev(['start', '-p', port as string, dir], undefined, {
...opts,
nextStart: true,
})
}
export function buildTS(args = [], cwd, env = {}) {
export function buildTS(
args: string[] = [],
cwd?: string,
env?: any
): Promise<void> {
cwd = cwd || path.dirname(require.resolve('next/package'))
env = { ...process.env, NODE_ENV: undefined, ...env }
......@@ -439,8 +514,8 @@ export function buildTS(args = [], cwd, env = {}) {
})
}
export async function killProcess(pid) {
await new Promise((resolve, reject) => {
export async function killProcess(pid: number): Promise<void> {
return await new Promise((resolve, reject) => {
treeKill(pid, (err) => {
if (err) {
if (
......@@ -465,11 +540,11 @@ export async function killProcess(pid) {
}
// Kill a launched app
export async function killApp(instance) {
export async function killApp(instance: ChildProcess) {
await killProcess(instance.pid)
}
export async function startApp(app) {
export async function startApp(app: NextServer) {
// force require usage instead of dynamic import in jest
// x-ref: https://github.com/nodejs/node/issues/35889
process.env.__NEXT_TEST_MODE = 'jest'
......@@ -480,38 +555,29 @@ export async function startApp(app) {
await app.prepare()
const handler = app.getRequestHandler()
const server = http.createServer(handler)
server.__app = app
server['__app'] = app
await promisify(server.listen).apply(server)
await promiseCall(server, 'listen')
return server
}
export async function stopApp(server) {
if (server.__app) {
await server.__app.close()
export async function stopApp(server: http.Server) {
if (server['__app']) {
await server['__app'].close()
}
await promiseCall(server, 'close')
}
export function promiseCall(obj, method, ...args) {
return new Promise((resolve, reject) => {
const newArgs = [
...args,
function (err, res) {
if (err) return reject(err)
resolve(res)
},
]
obj[method](...newArgs)
})
await promisify(server.close).apply(server)
}
export function waitFor(millis) {
export function waitFor(millis: number) {
return new Promise((resolve) => setTimeout(resolve, millis))
}
export async function startStaticServer(dir, notFoundFile, fixedPort) {
export async function startStaticServer(
dir: string,
notFoundFile?: string,
fixedPort?: number
) {
const app = express()
const server = http.createServer(app)
app.use(express.static(dir))
......@@ -522,16 +588,16 @@ export async function startStaticServer(dir, notFoundFile, fixedPort) {
})
}
await promiseCall(server, 'listen', fixedPort)
await promisify(server.listen).call(server, fixedPort)
return server
}
export async function startCleanStaticServer(dir) {
export async function startCleanStaticServer(dir: string) {
const app = express()
const server = http.createServer(app)
app.use(express.static(dir, { extensions: ['html'] }))
await promiseCall(server, 'listen')
await promisify(server.listen).apply(server)
return server
}
......@@ -545,8 +611,8 @@ export async function startCleanStaticServer(dir) {
* @returns {Promise<boolean>}
*/
export async function check(
contentFn,
regex,
contentFn: () => any | Promise<any>,
regex: any,
hardError = true,
maxRetries = 30
) {
......@@ -579,21 +645,24 @@ export async function check(
}
export class File {
constructor(path) {
path: string
originalContent: string
constructor(path: string) {
this.path = path
this.originalContent = existsSync(this.path)
? readFileSync(this.path, 'utf8')
: null
}
write(content) {
write(content: string) {
if (!this.originalContent) {
this.originalContent = content
}
writeFileSync(this.path, content, 'utf8')
}
replace(pattern, newValue) {
replace(pattern: RegExp | string, newValue: string) {
const currentContent = readFileSync(this.path, 'utf8')
if (pattern instanceof RegExp) {
if (!pattern.test(currentContent)) {
......@@ -624,7 +693,10 @@ export class File {
}
}
export async function evaluate(browser, input) {
export async function evaluate(
browser: BrowserInterface,
input: string | Function
) {
if (typeof input === 'function') {
const result = await browser.eval(input)
await new Promise((resolve) => setTimeout(resolve, 30))
......@@ -634,7 +706,12 @@ export async function evaluate(browser, input) {
}
}
export async function retry(fn, duration = 3000, interval = 500, description) {
export async function retry<T>(
fn: () => T | Promise<T>,
duration: number = 3000,
interval: number = 500,
description?: string
): Promise<T> {
if (duration % interval !== 0) {
throw new Error(
`invalid duration ${duration} and interval ${interval} mix, duration must be evenly divisible by interval`
......@@ -661,7 +738,7 @@ export async function retry(fn, duration = 3000, interval = 500, description) {
}
}
export async function hasRedbox(browser, expected = true) {
export async function hasRedbox(browser: BrowserInterface, expected = true) {
for (let i = 0; i < 30; i++) {
const result = await evaluate(browser, () => {
return Boolean(
......@@ -683,7 +760,7 @@ export async function hasRedbox(browser, expected = true) {
return false
}
export async function getRedboxHeader(browser) {
export async function getRedboxHeader(browser: BrowserInterface) {
return retry(
() => {
if (shouldRunTurboDevTest()) {
......@@ -715,7 +792,7 @@ export async function getRedboxHeader(browser) {
)
}
export async function getRedboxSource(browser) {
export async function getRedboxSource(browser: BrowserInterface) {
return retry(
() =>
evaluate(browser, () => {
......@@ -737,7 +814,7 @@ export async function getRedboxSource(browser) {
)
}
export async function getRedboxDescription(browser) {
export async function getRedboxDescription(browser: BrowserInterface) {
return retry(
() =>
evaluate(browser, () => {
......@@ -755,23 +832,23 @@ export async function getRedboxDescription(browser) {
)
}
export function getBrowserBodyText(browser) {
export function getBrowserBodyText(browser: BrowserInterface) {
return browser.eval('document.getElementsByTagName("body")[0].innerText')
}
export function normalizeRegEx(src) {
export function normalizeRegEx(src: string) {
return new RegExp(src).source.replace(/\^\//g, '^\\/')
}
function readJson(path) {
return JSON.parse(readFileSync(path))
function readJson(path: string) {
return JSON.parse(readFileSync(path, 'utf-8'))
}
export function getBuildManifest(dir) {
export function getBuildManifest(dir: string) {
return readJson(path.join(dir, '.next/build-manifest.json'))
}
export function getPageFileFromBuildManifest(dir, page) {
export function getPageFileFromBuildManifest(dir: string, page: string) {
const buildManifest = getBuildManifest(dir)
const pageFiles = buildManifest.pages[page]
if (!pageFiles) {
......@@ -790,24 +867,24 @@ export function getPageFileFromBuildManifest(dir, page) {
return pageFile
}
export function readNextBuildClientPageFile(appDir, page) {
export function readNextBuildClientPageFile(appDir: string, page: string) {
const pageFile = getPageFileFromBuildManifest(appDir, page)
return readFileSync(path.join(appDir, '.next', pageFile), 'utf8')
}
export function getPagesManifest(dir) {
export function getPagesManifest(dir: string) {
const serverFile = path.join(dir, '.next/server/pages-manifest.json')
return readJson(serverFile)
}
export function updatePagesManifest(dir, content) {
export function updatePagesManifest(dir: string, content: any) {
const serverFile = path.join(dir, '.next/server/pages-manifest.json')
return writeFile(serverFile, content)
}
export function getPageFileFromPagesManifest(dir, page) {
export function getPageFileFromPagesManifest(dir: string, page: string) {
const pagesManifest = getPagesManifest(dir)
const pageFile = pagesManifest[page]
if (!pageFile) {
......@@ -817,18 +894,26 @@ export function getPageFileFromPagesManifest(dir, page) {
return pageFile
}
export function readNextBuildServerPageFile(appDir, page) {
export function readNextBuildServerPageFile(appDir: string, page: string) {
const pageFile = getPageFileFromPagesManifest(appDir, page)
return readFileSync(path.join(appDir, '.next', 'server', pageFile), 'utf8')
}
/**
*
* @param {string} suiteName
* @param {{env: 'prod' | 'dev', appDir: string}} context
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function}} options
*/
function runSuite(suiteName, context, options) {
function runSuite(
suiteName: string,
context: { env: 'prod' | 'dev'; appDir: string } & Partial<{
stderr: string
stdout: string
appPort: number
code: number
server: ChildProcess
}>,
options: {
beforeAll?: Function
afterAll?: Function
runTests: Function
} & NextDevOptions
) {
const { appDir, env } = context
describe(`${suiteName} ${env}`, () => {
beforeAll(async () => {
......@@ -878,23 +963,29 @@ function runSuite(suiteName, context, options) {
})
}
/**
*
* @param {string} suiteName
* @param {string} appDir
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function; env?: Record<string, string>}} options
*/
export function runDevSuite(suiteName, appDir, options) {
export function runDevSuite(
suiteName: string,
appDir: string,
options: {
beforeAll?: Function
afterAll?: Function
runTests: Function
env?: NodeJS.ProcessEnv
}
) {
return runSuite(suiteName, { appDir, env: 'dev' }, options)
}
/**
*
* @param {string} suiteName
* @param {string} appDir
* @param {{beforeAll?: Function; afterAll?: Function; runTests: Function; env?: Record<string, string>}} options
*/
export function runProdSuite(suiteName, appDir, options) {
export function runProdSuite(
suiteName: string,
appDir: string,
options: {
beforeAll?: Function
afterAll?: Function
runTests: Function
env?: NodeJS.ProcessEnv
}
) {
return runSuite(suiteName, { appDir, env: 'prod' }, options)
}
......@@ -904,7 +995,7 @@ export function runProdSuite(suiteName, appDir, options) {
* @param {string} eventName
* @returns {Array<{}>}
*/
export function findAllTelemetryEvents(output, eventName) {
export function findAllTelemetryEvents(output: string, eventName: string) {
const regex = /\[telemetry\] ({.+?^})/gms
// Pop the last element of each entry to retrieve contents of the capturing group
const events = [...output.matchAll(regex)].map((entry) =>
......@@ -913,36 +1004,12 @@ export function findAllTelemetryEvents(output, eventName) {
return events.filter((e) => e.eventName === eventName).map((e) => e.payload)
}
/**
* Utility function to determine if a given test case needs to run with --turbo.
*
* This is primarily for the gradual test enablement with latest turbopack upstream changes.
*
* Note: it could be possible to dynamically create test cases itself (createDevTest(): it.each([...])), but
* it makes hard to conform with existing lint rules. Instead, starting off from manual fixture setup and
* update test cases accordingly as turbopack changes enable more test cases.
*/
export function shouldRunTurboDevTest() {
if (!!process.env.TEST_WASM) {
return false
}
const shouldRunTurboDev = !!process.env.TURBOPACK
// short-circuit to run all the test with --turbo enabled skips glob matching costs
if (shouldRunTurboDev) {
console.log(
`Running tests with turbopack via custom environment variable TURBOPACK`
)
return true
}
return false
}
type TestVariants = 'default' | 'turbo'
// WEB-168: There are some differences / incompletes in turbopack implementation enforces jest requires to update
// test snapshot when run against turbo. This fn returns describe, or describe.skip dependes on the running context
// to avoid force-snapshot update per each runs until turbopack update includes all the changes.
export function getSnapshotTestDescribe(variant) {
export function getSnapshotTestDescribe(variant: TestVariants) {
const runningEnv = variant ?? 'default'
if (runningEnv !== 'default' && runningEnv !== 'turbo') {
throw new Error(
......@@ -962,20 +1029,20 @@ export function getSnapshotTestDescribe(variant) {
* For better editor support, pass in the variants this should run on (`default` and/or `turbo`) as cases.
*
* This is necessary if separate snapshots are needed for next.js with webpack vs turbopack.
*
* @type {Pick<import("jest").Describe, "each">}
*/
export const describeVariants = {
each: (variants) => (name, fn) => {
if (
!Array.isArray(variants) ||
!variants.every((val) => typeof val === 'string')
) {
throw new Error('variants need to be an array of strings')
}
each(variants: TestVariants[]) {
return (name: string, fn: (...args: TestVariants[]) => any) => {
if (
!Array.isArray(variants) ||
!variants.every((val) => typeof val === 'string')
) {
throw new Error('variants need to be an array of strings')
}
for (const variant of variants) {
getSnapshotTestDescribe(variant).each([variant])(name, fn)
for (const variant of variants) {
getSnapshotTestDescribe(variant).each([variant])(name, fn)
}
}
},
}
......@@ -46,10 +46,13 @@ export const USE_SELENIUM = Boolean(
*
* @param appPortOrUrl can either be the port or the full URL
* @param url the path/query to append when using appPort
* @param options.waitHydration whether to wait for react hydration to finish
* @param options
* @param options.waitHydration whether to wait for React hydration to finish
* @param options.retryWaitHydration allow retrying hydration wait if reload occurs
* @param options.disableCache disable cache for page load
* @param options.beforePageLoad the callback receiving page instance before loading page
* @param options.locale browser locale
* @param options.disableJavaScript disable javascript
* @returns thenable browser instance
*/
export default async function webdriver(
......@@ -64,7 +67,7 @@ export default async function webdriver(
disableJavaScript?: boolean
}
): Promise<BrowserInterface> {
let CurrentInterface: typeof BrowserInterface
let CurrentInterface: new () => BrowserInterface
const defaultOptions = {
waitHydration: true,
......
let loggedTurbopack = false
/**
* Utility function to determine if a given test case needs to run with --turbo.
*
* This is primarily for the gradual test enablement with latest turbopack upstream changes.
*
* Note: it could be possible to dynamically create test cases itself (createDevTest(): it.each([...])), but
* it makes hard to conform with existing lint rules. Instead, starting off from manual fixture setup and
* update test cases accordingly as turbopack changes enable more test cases.
*/
export function shouldRunTurboDevTest(): boolean {
if (!!process.env.TEST_WASM) {
return false
}
const shouldRunTurboDev = !!process.env.TURBOPACK
if (shouldRunTurboDev && !loggedTurbopack) {
require('console').log(
`Running tests with turbopack because environment variable TURBOPACK is set`
)
loggedTurbopack = true
}
return shouldRunTurboDev
}
......@@ -44,7 +44,7 @@ describe('type-module', () => {
const server = await initNextServerScript(
serverFile,
/Listening on/,
{ ...process.env, PORT: appPort },
{ ...process.env, PORT: appPort.toString() },
undefined,
{ cwd: next.testDir }
)
......
......@@ -3,10 +3,10 @@
"strict": false,
"noEmit": true,
"allowJs": true,
"resolveJsonModule": true,
"jsx": "react",
"module": "esnext",
"target": "ESNext",
"skipLibCheck": true,
"esModuleInterop": true,
"moduleResolution": "node",
"baseUrl": ".",
......
......@@ -38,6 +38,7 @@
"outputs": ["dist/**"]
},
"typescript": {},
"//#typescript": {},
"rust-check": {
"inputs": [
".cargo/**",
......
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