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 @@ ...@@ -26,6 +26,7 @@
"genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js", "genstats": "cross-env LOCAL_STATS=true node .github/actions/next-stats-action/src/index.js",
"git-reset": "git reset --hard HEAD", "git-reset": "git reset --hard HEAD",
"git-clean": "git clean -d -x -e node_modules -e packages -f", "git-clean": "git clean -d -x -e node_modules -e packages -f",
"typescript": "tsc --noEmit",
"lint-typescript": "turbo run typescript", "lint-typescript": "turbo run typescript",
"lint-eslint": "eslint . --ext js,jsx,ts,tsx --max-warnings=0 --config .eslintrc.json --no-eslintrc", "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", "lint-no-typescript": "run-p prettier-check lint-eslint lint-language",
...@@ -84,7 +85,10 @@ ...@@ -84,7 +85,10 @@
"@swc/helpers": "0.5.1", "@swc/helpers": "0.5.1",
"@testing-library/react": "13.0.0", "@testing-library/react": "13.0.0",
"@types/cheerio": "0.22.16", "@types/cheerio": "0.22.16",
"@types/cookie": "0.3.3",
"@types/cross-spawn": "6.0.0",
"@types/fs-extra": "8.1.0", "@types/fs-extra": "8.1.0",
"@types/glob": "7.1.1",
"@types/html-validator": "5.0.3", "@types/html-validator": "5.0.3",
"@types/http-proxy": "1.17.3", "@types/http-proxy": "1.17.3",
"@types/jest": "24.0.13", "@types/jest": "24.0.13",
...@@ -171,6 +175,7 @@ ...@@ -171,6 +175,7 @@
"open": "9.0.0", "open": "9.0.0",
"outdent": "0.8.0", "outdent": "0.8.0",
"pixrem": "5.0.0", "pixrem": "5.0.0",
"playwright-core": "1.28.1",
"playwright-chromium": "1.28.1", "playwright-chromium": "1.28.1",
"plop": "3.0.5", "plop": "3.0.5",
"postcss": "8.4.14", "postcss": "8.4.14",
......
...@@ -77,11 +77,11 @@ function checkRedirect(route: Redirect): { ...@@ -77,11 +77,11 @@ function checkRedirect(route: Redirect): {
const invalidParts: string[] = [] const invalidParts: string[] = []
let hadInvalidStatus: boolean = false let hadInvalidStatus: boolean = false
if (route.statusCode && !allowedStatusCodes.has(route.statusCode)) { if (route.statusCode && !allowedStatusCodes.has(route['statusCode'])) {
hadInvalidStatus = true hadInvalidStatus = true
invalidParts.push(`\`statusCode\` is not undefined or valid statusCode`) 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\``) invalidParts.push(`\`permanent\` is not set to \`true\` or \`false\``)
} }
......
...@@ -57,7 +57,7 @@ export async function patchIncorrectLockfile(dir: string) { ...@@ -57,7 +57,7 @@ export async function patchIncorrectLockfile(dir: string) {
const lockfileParsed = JSON.parse(content) const lockfileParsed = JSON.parse(content)
const lockfileVersion = parseInt(lockfileParsed?.lockfileVersion, 10) const lockfileVersion = parseInt(lockfileParsed?.lockfileVersion, 10)
const expectedSwcPkgs = Object.keys(nextPkgJson.optionalDependencies || {}) const expectedSwcPkgs = Object.keys(nextPkgJson['optionalDependencies'] || {})
const patchDependency = ( const patchDependency = (
pkg: string, pkg: string,
......
...@@ -43,7 +43,10 @@ importers: ...@@ -43,7 +43,10 @@ importers:
'@swc/helpers': 0.5.1 '@swc/helpers': 0.5.1
'@testing-library/react': 13.0.0 '@testing-library/react': 13.0.0
'@types/cheerio': 0.22.16 '@types/cheerio': 0.22.16
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/fs-extra': 8.1.0 '@types/fs-extra': 8.1.0
'@types/glob': 7.1.1
'@types/html-validator': 5.0.3 '@types/html-validator': 5.0.3
'@types/http-proxy': 1.17.3 '@types/http-proxy': 1.17.3
'@types/jest': 24.0.13 '@types/jest': 24.0.13
...@@ -131,6 +134,7 @@ importers: ...@@ -131,6 +134,7 @@ importers:
outdent: 0.8.0 outdent: 0.8.0
pixrem: 5.0.0 pixrem: 5.0.0
playwright-chromium: 1.28.1 playwright-chromium: 1.28.1
playwright-core: 1.28.1
plop: 3.0.5 plop: 3.0.5
postcss: 8.4.14 postcss: 8.4.14
postcss-nested: 4.2.1 postcss-nested: 4.2.1
...@@ -211,7 +215,10 @@ importers: ...@@ -211,7 +215,10 @@ importers:
'@swc/helpers': 0.5.1 '@swc/helpers': 0.5.1
'@testing-library/react': 13.0.0_biqbaboplfbrettd7655fr4n2y '@testing-library/react': 13.0.0_biqbaboplfbrettd7655fr4n2y
'@types/cheerio': 0.22.16 '@types/cheerio': 0.22.16
'@types/cookie': 0.3.3
'@types/cross-spawn': 6.0.0
'@types/fs-extra': 8.1.0 '@types/fs-extra': 8.1.0
'@types/glob': 7.1.1
'@types/html-validator': 5.0.3 '@types/html-validator': 5.0.3
'@types/http-proxy': 1.17.3 '@types/http-proxy': 1.17.3
'@types/jest': 24.0.13 '@types/jest': 24.0.13
...@@ -299,6 +306,7 @@ importers: ...@@ -299,6 +306,7 @@ importers:
outdent: 0.8.0 outdent: 0.8.0
pixrem: 5.0.0 pixrem: 5.0.0
playwright-chromium: 1.28.1 playwright-chromium: 1.28.1
playwright-core: 1.28.1
plop: 3.0.5 plop: 3.0.5
postcss: 8.4.14 postcss: 8.4.14
postcss-nested: 4.2.1 postcss-nested: 4.2.1
......
...@@ -100,7 +100,7 @@ createNextDescribe( ...@@ -100,7 +100,7 @@ createNextDescribe(
it('should support setting cookies in route handlers with the correct overrides', async () => { it('should support setting cookies in route handlers with the correct overrides', async () => {
const res = await next.fetch('/handler') 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('bar=bar2; Path=/')
expect(setCookieHeader).toContain('baz=baz2; Path=/') expect(setCookieHeader).toContain('baz=baz2; Path=/')
expect(setCookieHeader).toContain('foo=foo1; Path=/') expect(setCookieHeader).toContain('foo=foo1; Path=/')
......
...@@ -3,6 +3,7 @@ import path from 'path' ...@@ -3,6 +3,7 @@ import path from 'path'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import { check, withQuery } from 'next-test-utils' import { check, withQuery } from 'next-test-utils'
import { createNextDescribe, FileRef } from 'e2e-utils' import { createNextDescribe, FileRef } from 'e2e-utils'
import type { Response } from 'node-fetch'
createNextDescribe( createNextDescribe(
'app-dir with middleware', 'app-dir with middleware',
......
import type { Request } from 'playwright-core'
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import type { BrowserInterface } from '../../../lib/browsers/base'
const getPathname = (url: string) => { const getPathname = (url: string) => {
const urlObj = new URL(url) const urlObj = new URL(url)
......
...@@ -58,7 +58,12 @@ type Cookies = { ...@@ -58,7 +58,12 @@ type Cookies = {
* @returns any injected metadata on the request * @returns any injected metadata on the request
*/ */
export function getRequestMeta( export function getRequestMeta(
headersOrCookies: Headers | Cookies | ReadonlyHeaders | ReadonlyRequestCookies headersOrCookies:
| Headers
| import('node-fetch').Headers
| Cookies
| ReadonlyHeaders
| ReadonlyRequestCookies
): Record<string, any> { ): Record<string, any> {
const headerOrCookie = headersOrCookies.get(KEY) const headerOrCookie = headersOrCookies.get(KEY)
if (!headerOrCookie) return {} if (!headerOrCookie) return {}
......
...@@ -70,7 +70,7 @@ if (!(globalThis as any).isNextStart) { ...@@ -70,7 +70,7 @@ if (!(globalThis as any).isNextStart) {
/Listening on/, /Listening on/,
{ {
...process.env, ...process.env,
PORT: appPort, PORT: appPort.toString(),
}, },
undefined, undefined,
{ {
......
import { createNextDescribe } from 'e2e-utils' import { createNextDescribe } from 'e2e-utils'
import type { Response } from 'node-fetch'
import cookies, { nextConfigHeaders } from './cookies.mjs' import cookies, { nextConfigHeaders } from './cookies.mjs'
function getSetCookieHeaders(res: globalThis.Response): ReadonlyArray<string> { function getSetCookieHeaders(res: Response): ReadonlyArray<string> {
return ( return (
(res.headers as any).getSetCookie?.() ?? (res.headers as any).getSetCookie?.() ??
(res.headers as any).raw()['set-cookie'] (res.headers as any).raw()['set-cookie']
......
...@@ -3,6 +3,7 @@ import { NextInstance } from 'test/lib/next-modes/base' ...@@ -3,6 +3,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils' import { fetchViaHTTP, renderViaHTTP } from 'next-test-utils'
import FormData from 'form-data' import FormData from 'form-data'
import path from 'path' import path from 'path'
import type { Response } from 'node-fetch'
async function serialize(response: Response) { async function serialize(response: Response) {
return { return {
......
...@@ -5,6 +5,7 @@ import { NextInstance } from 'test/lib/next-modes/base' ...@@ -5,6 +5,7 @@ import { NextInstance } from 'test/lib/next-modes/base'
import { fetchViaHTTP } from 'next-test-utils' import { fetchViaHTTP } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils' import { createNext, FileRef } from 'e2e-utils'
import cheerio from 'cheerio' import cheerio from 'cheerio'
import type { Response } from 'node-fetch'
describe('Middleware Request Headers Overrides', () => { describe('Middleware Request Headers Overrides', () => {
let next: NextInstance let next: NextInstance
......
import { FileRef, createNext, NextInstance } from 'e2e-utils' import { FileRef, createNext, NextInstance } from 'e2e-utils'
import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils' import { findPort, renderViaHTTP, fetchViaHTTP } from 'next-test-utils'
import { join } from 'path' import { join } from 'path'
import { spawn } from 'cross-spawn' import spawn from 'cross-spawn'
describe('next/font/google with proxy', () => { describe('next/font/google with proxy', () => {
let next: NextInstance let next: NextInstance
...@@ -22,8 +22,8 @@ describe('next/font/google with proxy', () => { ...@@ -22,8 +22,8 @@ describe('next/font/google with proxy', () => {
stdio: 'inherit', stdio: 'inherit',
env: { env: {
...process.env, ...process.env,
PROXY_PORT, PROXY_PORT: PROXY_PORT.toString(),
SERVER_PORT, SERVER_PORT: SERVER_PORT.toString(),
}, },
}) })
......
...@@ -1850,8 +1850,8 @@ describe('Prerender', () => { ...@@ -1850,8 +1850,8 @@ describe('Prerender', () => {
previewRes.headers previewRes.headers
.get('set-cookie') .get('set-cookie')
.split(',') .split(',')
.forEach((c) => { .forEach((s) => {
c = cookie.parse(c) const c = cookie.parse(s)
const isBypass = c.__prerender_bypass const isBypass = c.__prerender_bypass
if (isBypass || c.__next_preview_data) { if (isBypass || c.__next_preview_data) {
......
...@@ -11,6 +11,7 @@ import { ...@@ -11,6 +11,7 @@ import {
import webdriver from 'next-webdriver' import webdriver from 'next-webdriver'
import { join } from 'path' import { join } from 'path'
import fs from 'fs' import fs from 'fs'
import type { Response } from 'node-fetch'
const appDir = join(__dirname, '../') const appDir = join(__dirname, '../')
const nextConfig = new File(join(appDir, 'next.config.js')) const nextConfig = new File(join(appDir, 'next.config.js'))
......
...@@ -43,7 +43,10 @@ describe('Test Draft Mode', () => { ...@@ -43,7 +43,10 @@ describe('Test Draft Mode', () => {
const res = await fetchViaHTTP(appPort, '/api/enable') const res = await fetchViaHTTP(appPort, '/api/enable')
expect(res.status).toBe(200) 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]).toBeTruthy()
expect(cookies[0].__prerender_bypass).toBeTruthy() expect(cookies[0].__prerender_bypass).toBeTruthy()
...@@ -76,7 +79,7 @@ describe('Test Draft Mode', () => { ...@@ -76,7 +79,7 @@ describe('Test Draft 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((c) => cookie.parse(c))
expect(cookies[0]).toBeTruthy() expect(cookies[0]).toBeTruthy()
}) })
...@@ -154,7 +157,7 @@ describe('Test Draft Mode', () => { ...@@ -154,7 +157,7 @@ describe('Test Draft Mode', () => {
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((c) => cookie.parse(c))
expect(cookies.length).toBe(1) expect(cookies.length).toBe(1)
expect(cookies[0]).toBeTruthy() expect(cookies[0]).toBeTruthy()
...@@ -212,7 +215,7 @@ describe('Test Draft Mode', () => { ...@@ -212,7 +215,7 @@ describe('Test Draft 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((c) => cookie.parse(c))
expect(cookies[0]).toBeTruthy() expect(cookies[0]).toBeTruthy()
expect(cookies[0]).toMatchObject({ expect(cookies[0]).toMatchObject({
......
...@@ -12,8 +12,20 @@ ...@@ -12,8 +12,20 @@
"moduleResolution": "node", "moduleResolution": "node",
"resolveJsonModule": true, "resolveJsonModule": true,
"isolatedModules": 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"] "exclude": ["node_modules"]
} }
...@@ -54,7 +54,7 @@ describe('dev mode', () => { ...@@ -54,7 +54,7 @@ describe('dev mode', () => {
context.appPort = await findPort() context.appPort = await findPort()
context.app = await launchApp(appDir, context.appPort, { context.app = await launchApp(appDir, context.appPort, {
...context.handler, ...context.handler,
env: { __NEXT_TEST_WITH_DEVTOOL: 1 }, env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
}) })
}) })
......
...@@ -69,7 +69,7 @@ describe.each([ ...@@ -69,7 +69,7 @@ describe.each([
output = '' output = ''
appPort = await findPort() appPort = await findPort()
app = await launchApp(appDir, appPort, { app = await launchApp(appDir, appPort, {
env: { __NEXT_TEST_WITH_DEVTOOL: 1 }, env: { __NEXT_TEST_WITH_DEVTOOL: '1' },
onStdout(msg) { onStdout(msg) {
output += msg output += msg
}, },
......
...@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => { ...@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => {
nextConfig, nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages') content.replace('// disableStaticImages', 'disableStaticImages')
) )
const app = await launchApp(appDir, await findPort(), []) const app = await launchApp(appDir, await findPort())
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
...@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => { ...@@ -81,7 +81,7 @@ describe('TypeScript Image Component', () => {
nextConfig, nextConfig,
content.replace('// disableStaticImages', 'disableStaticImages') content.replace('// disableStaticImages', 'disableStaticImages')
) )
const app = await launchApp(appDir, await findPort(), []) const app = await launchApp(appDir, await findPort())
await killApp(app) await killApp(app)
await fs.writeFile(nextConfig, content) await fs.writeFile(nextConfig, content)
const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8') const envTypes = await fs.readFile(join(appDir, 'next-env.d.ts'), 'utf8')
......
// @ts-ignore
import * as matchers from 'jest-extended' import * as matchers from 'jest-extended'
expect.extend(matchers) 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' ...@@ -6,22 +6,29 @@ export type Event = 'request'
* methods we aim to support across tests * methods we aim to support across tests
* *
* They will always await last executed command. * 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. * You can manually await this interface to wait for completion of the last scheduled command.
*/ */
export class BrowserInterface implements PromiseLike<any> { export abstract class BrowserInterface implements PromiseLike<any> {
private promise: any private promise?: Promise<any>
then: PromiseLike<any>['then'] then: Promise<any>['then']
private catch: any 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) { if (!this.promise) {
this.promise = Promise.resolve(this) this.promise = Promise.resolve(this)
} }
this.promise = this.promise.then(nextCall) this.promise = this.promise.then(nextCall)
this.then = (...args) => this.promise.then(...args) this.then = (...args) => this.promise.then(...args)
this.catch = (...args) => this.promise.catch(...args) this.catch = (...args) => this.promise.catch(...args)
this.finally = (...args) => this.promise.finally(...args)
return this return this
} }
......
...@@ -28,6 +28,11 @@ export async function quit() { ...@@ -28,6 +28,11 @@ export async function quit() {
browser = undefined browser = undefined
} }
interface ElementHandleExt extends ElementHandle {
getComputedCss(prop: string): Promise<string>
text(): Promise<string>
}
export class Playwright extends BrowserInterface { export class Playwright extends BrowserInterface {
private activeTrace?: string private activeTrace?: string
private eventCallbacks: Record<Event, Set<(...args: any[]) => void>> = { private eventCallbacks: Record<Event, Set<(...args: any[]) => void>> = {
...@@ -95,7 +100,7 @@ export class Playwright extends BrowserInterface { ...@@ -95,7 +100,7 @@ export class Playwright extends BrowserInterface {
} }
async get(url: string): Promise<void> { async get(url: string): Promise<void> {
return page.goto(url) as any await page.goto(url)
} }
async loadPage( async loadPage(
...@@ -192,18 +197,18 @@ export class Playwright extends BrowserInterface { ...@@ -192,18 +197,18 @@ export class Playwright extends BrowserInterface {
} }
back(): BrowserInterface { back(): BrowserInterface {
return this.chain(() => { return this.chain(async () => {
return page.goBack() await page.goBack()
}) })
} }
forward(): BrowserInterface { forward(): BrowserInterface {
return this.chain(() => { return this.chain(async () => {
return page.goForward() await page.goForward()
}) })
} }
refresh(): BrowserInterface { refresh(): BrowserInterface {
return this.chain(() => { return this.chain(async () => {
return page.reload() await page.reload()
}) })
} }
setDimensions({ setDimensions({
...@@ -234,29 +239,22 @@ export class Playwright extends BrowserInterface { ...@@ -234,29 +239,22 @@ export class Playwright extends BrowserInterface {
return this.chain(() => page.bringToFront()) return this.chain(() => page.bringToFront())
} }
private wrapElement(el: ElementHandle, selector: string) { private wrapElement(el: ElementHandle, selector: string): ElementHandleExt {
;(el as any).selector = selector function getComputedCss(prop: string) {
;(el as any).text = () => el.innerText() return page.evaluate(
;(el as any).getComputedCss = (prop) =>
page.evaluate(
function (args) { function (args) {
return ( const style = getComputedStyle(document.querySelector(args.selector))
getComputedStyle(document.querySelector(args.selector))[ return style[args.prop] || null
args.prop
] || null
)
}, },
{ selector, prop } { selector, prop }
) )
;(el as any).getCssValue = (el as any).getComputedCss }
;(el as any).getValue = () =>
page.evaluate( return Object.assign(el, {
function (args) { selector,
return (document.querySelector(args.selector) as any).value getComputedCss,
}, text: () => el.innerText(),
{ selector } })
)
return el
} }
elementByCss(selector: string) { elementByCss(selector: string) {
...@@ -268,38 +266,31 @@ export class Playwright extends BrowserInterface { ...@@ -268,38 +266,31 @@ export class Playwright extends BrowserInterface {
} }
getValue() { getValue() {
return this.chain((el) => return this.chain((el: ElementHandleExt) => el.inputValue())
page.evaluate(
function (args) {
return document.querySelector(args.selector).value
},
{ selector: el.selector }
)
) as any
} }
text() { text() {
return this.chain((el) => el.text()) as any return this.chain((el: ElementHandleExt) => el.innerText())
} }
type(text) { type(text) {
return this.chain((el) => el.type(text)) return this.chain((el: ElementHandleExt) => el.type(text))
} }
moveTo() { moveTo() {
return this.chain((el) => { return this.chain((el: ElementHandleExt) => {
return page.hover(el.selector).then(() => el) return el.hover().then(() => el)
}) })
} }
async getComputedCss(prop: string) { async getComputedCss(prop: string) {
return this.chain((el) => { return this.chain((el: ElementHandleExt) => {
return el.getCssValue(prop) return el.getComputedCss(prop)
}) as any }) as any
} }
async getAttribute<T = any>(attr) { 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) { hasElementByCssSelector(selector: string) {
...@@ -307,25 +298,25 @@ export class Playwright extends BrowserInterface { ...@@ -307,25 +298,25 @@ export class Playwright extends BrowserInterface {
} }
keydown(key: string): BrowserInterface { keydown(key: string): BrowserInterface {
return this.chain((el) => { return this.chain((el: ElementHandleExt) => {
return page.keyboard.down(key).then(() => el) return page.keyboard.down(key).then(() => el)
}) })
} }
keyup(key: string): BrowserInterface { keyup(key: string): BrowserInterface {
return this.chain((el) => { return this.chain((el: ElementHandleExt) => {
return page.keyboard.up(key).then(() => el) return page.keyboard.up(key).then(() => el)
}) })
} }
click() { click() {
return this.chain((el) => { return this.chain((el: ElementHandleExt) => {
return el.click().then(() => el) return el.click().then(() => el)
}) })
} }
touchStart() { touchStart() {
return this.chain((el: ElementHandle) => { return this.chain((el: ElementHandleExt) => {
return el.dispatchEvent('touchstart').then(() => el) return el.dispatchEvent('touchstart').then(() => el)
}) })
} }
......
...@@ -41,7 +41,6 @@ export async function sandbox( ...@@ -41,7 +41,6 @@ export async function sandbox(
await next.start() await next.start()
const browser = await webdriver(next.url, initialUrl, webDriverOptions) const browser = await webdriver(next.url, initialUrl, webDriverOptions)
// await waitForHydration(browser)
return { return {
browser, browser,
session: { session: {
......
import { spawn } from 'cross-spawn' import spawn from 'cross-spawn'
import { Span } from 'next/src/trace' import { Span } from 'next/src/trace'
import { NextInstance } from './base' import { NextInstance } from './base'
......
import path from 'path' import path from 'path'
import fs from 'fs-extra' import fs from 'fs-extra'
import { NextInstance } from './base' import { NextInstance } from './base'
import { spawn, SpawnOptions } from 'cross-spawn' import spawn from 'cross-spawn'
import { Span } from 'next/src/trace' import { Span } from 'next/src/trace'
export class NextStartInstance extends NextInstance { export class NextStartInstance extends NextInstance {
private _buildId: string private _buildId: string
private _cliOutput: string = '' private _cliOutput: string = ''
private spawnOpts: SpawnOptions private spawnOpts: import('child_process').SpawnOptions
public get buildId() { public get buildId() {
return this._buildId return this._buildId
......
...@@ -46,10 +46,13 @@ export const USE_SELENIUM = Boolean( ...@@ -46,10 +46,13 @@ export const USE_SELENIUM = Boolean(
* *
* @param appPortOrUrl can either be the port or the full URL * @param appPortOrUrl can either be the port or the full URL
* @param url the path/query to append when using appPort * @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.retryWaitHydration allow retrying hydration wait if reload occurs
* @param options.disableCache disable cache for page load * @param options.disableCache disable cache for page load
* @param options.beforePageLoad the callback receiving page instance before loading page * @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 * @returns thenable browser instance
*/ */
export default async function webdriver( export default async function webdriver(
...@@ -64,7 +67,7 @@ export default async function webdriver( ...@@ -64,7 +67,7 @@ export default async function webdriver(
disableJavaScript?: boolean disableJavaScript?: boolean
} }
): Promise<BrowserInterface> { ): Promise<BrowserInterface> {
let CurrentInterface: typeof BrowserInterface let CurrentInterface: new () => BrowserInterface
const defaultOptions = { const defaultOptions = {
waitHydration: true, 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', () => { ...@@ -44,7 +44,7 @@ describe('type-module', () => {
const server = await initNextServerScript( const server = await initNextServerScript(
serverFile, serverFile,
/Listening on/, /Listening on/,
{ ...process.env, PORT: appPort }, { ...process.env, PORT: appPort.toString() },
undefined, undefined,
{ cwd: next.testDir } { cwd: next.testDir }
) )
......
...@@ -3,10 +3,10 @@ ...@@ -3,10 +3,10 @@
"strict": false, "strict": false,
"noEmit": true, "noEmit": true,
"allowJs": true, "allowJs": true,
"resolveJsonModule": true,
"jsx": "react", "jsx": "react",
"module": "esnext", "module": "esnext",
"target": "ESNext", "target": "ESNext",
"skipLibCheck": true,
"esModuleInterop": true, "esModuleInterop": true,
"moduleResolution": "node", "moduleResolution": "node",
"baseUrl": ".", "baseUrl": ".",
......
...@@ -38,6 +38,7 @@ ...@@ -38,6 +38,7 @@
"outputs": ["dist/**"] "outputs": ["dist/**"]
}, },
"typescript": {}, "typescript": {},
"//#typescript": {},
"rust-check": { "rust-check": {
"inputs": [ "inputs": [
".cargo/**", ".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