Unverified Commit 4282bc6f authored by Janka Uryga's avatar Janka Uryga Committed by GitHub

remove BrowserInterface (#78308)

rip. you served a purpose once, but now you're just getting in the way. this improves typesafety quite a bit, because `BrowserInterface` had a whole bunch of random `any`s everywhere

also
- removes `evalAsync`. no idea why that was needed, but we're happily using promises in normal eval, so it can be dropped
- adds more safety to `chain`
parent 1f93d497
......@@ -3,9 +3,9 @@ import { createSandbox } from 'development-sandbox'
import { FileRef, nextTestSetup } from 'e2e-utils'
import path from 'path'
import { outdent } from 'outdent'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
function getStaleness(browser: BrowserInterface) {
function getStaleness(browser: Playwright) {
return browser
.waitForElementByCss('.nextjs-container-build-error-version-status')
.text()
......
import { join } from 'path'
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import { FileRef, nextTestSetup } from 'e2e-utils'
import { check, shouldRunTurboDevTest } from 'next-test-utils'
......@@ -27,7 +27,7 @@ describe('TailwindCSS JIT', () => {
})
it('works with JIT enabled', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
const text = await browser.elementByCss('.text-6xl').text()
......
import { createNext, FileRef } from 'e2e-utils'
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import { NextInstance } from 'e2e-utils'
import { join } from 'path'
import { retry } from 'next-test-utils'
describe('client-dev-overlay', () => {
let next: NextInstance
let browser: BrowserInterface
let browser: Playwright
beforeAll(async () => {
next = await createNext({
......@@ -25,7 +25,7 @@ describe('client-dev-overlay', () => {
})
afterAll(() => next.destroy())
// The `BrowserInterface.hasElementByCssSelector` cannot be used for elements inside a shadow DOM.
// The `Playwright.hasElementByCssSelector` cannot be used for elements inside a shadow DOM.
function elementExistsInNextJSPortalShadowDOM(selector: string) {
return browser.eval(
`!!document.querySelector('nextjs-portal').shadowRoot.querySelector('${selector}')`
......
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type { Response } from 'playwright'
describe('app-dir action progressive enhancement', () => {
const { next } = nextTestSetup({
......@@ -17,7 +16,7 @@ describe('app-dir action progressive enhancement', () => {
const browser = await next.browser('/server', {
disableJavaScript: true,
beforePageLoad(page) {
page.on('response', (response: Response) => {
page.on('response', (response) => {
const url = new URL(response.url())
const status = response.status()
if (url.pathname.includes('/server')) {
......
......@@ -7,7 +7,7 @@ import {
waitFor,
getRedboxSource,
} from 'next-test-utils'
import type { Page, Request, Response, Route } from 'playwright'
import type { Request, Response } from 'playwright'
import fs from 'fs-extra'
import nodeFs from 'fs'
import { join } from 'path'
......@@ -30,7 +30,7 @@ describe('app-dir action handling', () => {
const browser = await next.browser('/rewrite-to-static-first')
let actionRequestStatus: number | undefined
browser.on('response', async (res: Response) => {
browser.on('response', async (res) => {
if (
res.url().includes('rewrite-to-static-first') &&
res.request().method() === 'POST'
......@@ -100,8 +100,8 @@ describe('app-dir action handling', () => {
it('should propagate errors from a `text/plain` response to an error boundary', async () => {
const customErrorText = 'Custom error!'
const browser = await next.browser('/error-handling', {
beforePageLoad(page: Page) {
page.route('**/error-handling', async (route: Route) => {
beforePageLoad(page) {
page.route('**/error-handling', async (route) => {
const requestHeaders = await route.request().allHeaders()
if (requestHeaders['next-action']) {
await route.fulfill({
......@@ -124,8 +124,8 @@ describe('app-dir action handling', () => {
it('should trigger an error boundary for action responses with an invalid content-type', async () => {
const customErrorText = 'Custom error!'
const browser = await next.browser('/error-handling', {
beforePageLoad(page: Page) {
page.route('**/error-handling', async (route: Route) => {
beforePageLoad(page) {
page.route('**/error-handling', async (route) => {
const requestHeaders = await route.request().allHeaders()
if (requestHeaders['next-action']) {
await route.fulfill({
......@@ -727,7 +727,7 @@ describe('app-dir action handling', () => {
it('should reset the form state when the action redirects to itself', async () => {
const browser = await next.browser('/self-redirect')
const requests = []
browser.on('request', async (req: Request) => {
browser.on('request', async (req) => {
const url = new URL(req.url())
if (url.pathname === '/self-redirect') {
......@@ -820,7 +820,7 @@ describe('app-dir action handling', () => {
it('should be possible to catch network errors', async () => {
const browser = await next.browser('/catching-error', {
beforePageLoad(page) {
page.route('**/catching-error', (route: Route) => {
page.route('**/catching-error', (route) => {
if (route.request().method() !== 'POST') {
route.fallback()
return
......@@ -918,8 +918,8 @@ describe('app-dir action handling', () => {
async (runtime) => {
let redirectResponseCode
const browser = await next.browser(`/delayed-action/${runtime}`, {
beforePageLoad(page: Page) {
page.on('response', async (res: Response) => {
beforePageLoad(page) {
page.on('response', async (res) => {
const headers = await res.allHeaders().catch(() => ({}))
if (headers['x-action-redirect']) {
redirectResponseCode = res.status()
......@@ -1117,7 +1117,7 @@ describe('app-dir action handling', () => {
const requests: Request[] = []
const responses: Response[] = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
const url = req.url()
if (
......@@ -1128,7 +1128,7 @@ describe('app-dir action handling', () => {
}
})
browser.on('response', (res: Response) => {
browser.on('response', (res) => {
const url = res.url()
if (
......@@ -1234,7 +1234,7 @@ describe('app-dir action handling', () => {
const requests: Request[] = []
const responses: Response[] = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
const url = req.url()
if (
......@@ -1245,7 +1245,7 @@ describe('app-dir action handling', () => {
}
})
browser.on('response', (res: Response) => {
browser.on('response', (res) => {
const url = res.url()
if (
......@@ -1641,14 +1641,14 @@ describe('app-dir action handling', () => {
const browser = await next.browser('/redirects', {
beforePageLoad(page) {
page.on('request', (request: Request) => {
page.on('request', (request) => {
const url = new URL(request.url())
if (request.method() === 'POST') {
postRequests.push(url.pathname)
}
})
page.on('response', (response: Response) => {
page.on('response', (response) => {
const url = new URL(response.url())
const status = response.status()
......@@ -1675,14 +1675,14 @@ describe('app-dir action handling', () => {
const browser = await next.browser('/redirects', {
beforePageLoad(page) {
page.on('request', (request: Request) => {
page.on('request', (request) => {
const url = new URL(request.url())
if (request.method() === 'POST') {
postRequests.push(url.pathname)
}
})
page.on('response', (response: Response) => {
page.on('response', (response) => {
const url = new URL(response.url())
const status = response.status()
......@@ -1769,14 +1769,14 @@ describe('app-dir action handling', () => {
const browser = await next.browser('/redirects', {
beforePageLoad(page) {
page.on('request', (request: Request) => {
page.on('request', (request) => {
const url = new URL(request.url())
if (request.method() === 'POST') {
postRequests.push(`${url.pathname}${url.search}`)
}
})
page.on('response', (response: Response) => {
page.on('response', (response) => {
const url = new URL(response.url())
const status = response.status()
......
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import type { BrowserInterface } from 'next-webdriver'
import type { Playwright } from 'next-webdriver'
describe('app a11y features', () => {
const { next, skipped } = nextTestSetup({
......@@ -14,7 +14,7 @@ describe('app a11y features', () => {
}
describe('route announcer', () => {
async function getAnnouncerContent(browser: BrowserInterface) {
async function getAnnouncerContent(browser: Playwright) {
return browser.eval(
`document.getElementsByTagName('next-route-announcer')[0]?.shadowRoot.childNodes[0]?.innerHTML`
)
......
......@@ -110,7 +110,7 @@ describe('app dir - basepath', () => {
const browser = await next.browser(initialPagePath)
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
const url = req.url()
if (
......@@ -121,7 +121,7 @@ describe('app dir - basepath', () => {
}
})
browser.on('response', (res: Response) => {
browser.on('response', (res) => {
const url = res.url()
if (
......@@ -163,7 +163,7 @@ describe('app dir - basepath', () => {
const browser = await next.browser(initialPagePath)
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
const url = req.url()
if (!url.includes('_next')) {
......@@ -171,7 +171,7 @@ describe('app dir - basepath', () => {
}
})
browser.on('response', (res: Response) => {
browser.on('response', (res) => {
const url = res.url()
if (!url.includes('_next')) {
......
import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
import {
browserConfigWithFixedTime,
createRequestsListener,
......@@ -17,10 +17,7 @@ describe('app dir client cache semantics (default semantics)', () => {
if (isNextDev) {
// dev doesn't support prefetch={true}, so this just performs a basic test to make sure data is reused for 30s
it('should return fresh data every navigation', async () => {
let browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
let browser = await next.browser('/', browserConfigWithFixedTime)
// navigate to prefetch-auto page
await browser.elementByCss('[href="/1"]').click()
......@@ -38,13 +35,10 @@ describe('app dir client cache semantics (default semantics)', () => {
})
} else {
describe('prefetch={true}', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should prefetch the full page', async () => {
......@@ -143,13 +137,10 @@ describe('app dir client cache semantics (default semantics)', () => {
})
})
describe('prefetch={false}', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should not prefetch the page at all', async () => {
const { getRequests } = await createRequestsListener(browser)
......@@ -201,13 +192,10 @@ describe('app dir client cache semantics (default semantics)', () => {
})
})
describe('prefetch={undefined} - default', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should prefetch partially a dynamic page', async () => {
......@@ -334,10 +322,10 @@ describe('app dir client cache semantics (default semantics)', () => {
})
it('should renew the initial seeded data after expiration time', async () => {
const browser = (await next.browser(
const browser = await next.browser(
'/without-loading/1',
browserConfigWithFixedTime
)) as BrowserInterface
)
const initialNumber = await browser.elementById('random-number').text()
......
import { nextTestSetup } from 'e2e-utils'
import { check, retry } from 'next-test-utils'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
import {
browserConfigWithFixedTime,
createRequestsListener,
......@@ -21,10 +21,7 @@ describe('app dir client cache semantics (30s/5min)', () => {
if (isNextDev) {
// dev doesn't support prefetch={true}, so this just performs a basic test to make sure data is reused for 30s
it('should renew the 30s cache once the data is revalidated', async () => {
let browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
let browser = await next.browser('/', browserConfigWithFixedTime)
// navigate to prefetch-auto page
await browser.elementByCss('[href="/1"]').click()
......@@ -70,13 +67,10 @@ describe('app dir client cache semantics (30s/5min)', () => {
})
} else {
describe('prefetch={true}', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should prefetch the full page', async () => {
......@@ -175,13 +169,10 @@ describe('app dir client cache semantics (30s/5min)', () => {
})
})
describe('prefetch={false}', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should not prefetch the page at all', async () => {
const { getRequests } = await createRequestsListener(browser)
......@@ -233,13 +224,10 @@ describe('app dir client cache semantics (30s/5min)', () => {
})
})
describe('prefetch={undefined} - default', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should prefetch partially a dynamic page', async () => {
......@@ -439,10 +427,7 @@ describe('app dir client cache semantics (30s/5min)', () => {
})
it('should seed the prefetch cache with the fetched page data', async () => {
const browser = (await next.browser(
'/1',
browserConfigWithFixedTime
)) as BrowserInterface
const browser = await next.browser('/1', browserConfigWithFixedTime)
const initialNumber = await browser.elementById('random-number').text()
......@@ -458,10 +443,10 @@ describe('app dir client cache semantics (30s/5min)', () => {
})
it('should renew the initial seeded data after expiration time', async () => {
const browser = (await next.browser(
const browser = await next.browser(
'/without-loading/1',
browserConfigWithFixedTime
)) as BrowserInterface
)
const initialNumber = await browser.elementById('random-number').text()
......
import { nextTestSetup } from 'e2e-utils'
import { check } from 'next-test-utils'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
import {
browserConfigWithFixedTime,
createRequestsListener,
......@@ -21,13 +21,10 @@ describe('app dir client cache with parallel routes', () => {
}
describe('prefetch={true}', () => {
let browser: BrowserInterface
let browser: Playwright
beforeEach(async () => {
browser = (await next.browser(
'/',
browserConfigWithFixedTime
)) as BrowserInterface
browser = await next.browser('/', browserConfigWithFixedTime)
})
it('should prefetch the full page', async () => {
......
import { BrowserInterface } from 'next-webdriver'
import type { Request } from 'playwright'
import { Playwright } from 'next-webdriver'
export const getPathname = (url: string) => {
const urlObj = new URL(url)
......@@ -51,13 +50,13 @@ export const fastForwardTo = (ms) => {
}
}
export const createRequestsListener = async (browser: BrowserInterface) => {
export const createRequestsListener = async (browser: Playwright) => {
// wait for network idle
await browser.waitForIdleNetwork()
let requests = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
requests.push([req.url(), !!req.headers()['next-router-prefetch']])
})
......
import type { Request } from 'playwright'
import { nextTestSetup } from 'e2e-utils'
import type { BrowserInterface } from '../../../lib/browsers/base'
import type { Playwright } from 'next-webdriver'
const getPathname = (url: string) => {
const urlObj = new URL(url)
return urlObj.pathname
}
const createRequestsListener = async (browser: BrowserInterface) => {
const createRequestsListener = async (browser: Playwright) => {
// wait for network idle
await browser.waitForIdleNetwork()
let requests = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
requests.push([req.url(), !!req.headers()['next-router-prefetch']])
})
......
import { nextTestSetup } from 'e2e-utils'
import { check, waitFor, retry } from 'next-test-utils'
import type { Page, Request, Route } from 'playwright'
import { NEXT_RSC_UNION_QUERY } from 'next/dist/client/components/app-router-headers'
const browserConfigWithFixedTime = {
......@@ -112,7 +111,7 @@ describe('app dir - prefetching', () => {
requests.push(new URL(req.url()).pathname)
})
await browser.evalAsync('window.next.router.prefetch("/dashboard/123")')
await browser.eval('window.next.router.prefetch("/dashboard/123")')
await browser.waitForIdleNetwork()
expect(requests).toInclude('/dashboard/123')
......@@ -345,8 +344,8 @@ describe('app dir - prefetching', () => {
it('should not unintentionally modify the requested prefetch by escaping the uri encoded query params', async () => {
const rscRequests = []
const browser = await next.browser('/uri-encoded-prefetch', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
if (url.searchParams.has('_rsc')) {
rscRequests.push(url.pathname + url.search)
......@@ -387,8 +386,8 @@ describe('app dir - prefetching', () => {
it('should not re-fetch the initial static page if the same page is prefetched with prefetch={true}', async () => {
const rscRequests = []
const browser = await next.browser('/static-page', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
if (url.pathname === '/static-page' || url.pathname === '/') {
const headers = await req.allHeaders()
......@@ -441,8 +440,8 @@ describe('app dir - prefetching', () => {
it('should not re-fetch the initial dynamic page if the same page is prefetched with prefetch={true}', async () => {
const rscRequests = []
const browser = await next.browser('/dynamic-page', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
if (url.pathname === '/dynamic-page' || url.pathname === '/') {
const headers = await req.allHeaders()
......@@ -575,8 +574,8 @@ describe('app dir - prefetching', () => {
it('should prefetch links in viewport with low priority', async () => {
const requests: { priority: string; url: string }[] = []
const browser = await next.browser('/', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
const headers = await req.allHeaders()
if (headers['rsc']) {
......@@ -600,8 +599,8 @@ describe('app dir - prefetching', () => {
it('should prefetch with high priority when navigating to a page without a prefetch entry', async () => {
const requests: { priority: string; url: string }[] = []
const browser = await next.browser('/prefetch-false/initial', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
const headers = await req.allHeaders()
if (headers['rsc']) {
......@@ -628,8 +627,8 @@ describe('app dir - prefetching', () => {
it('should have an auto priority for all other fetch operations', async () => {
const requests: { priority: string; url: string }[] = []
const browser = await next.browser('/', {
beforePageLoad(page: Page) {
page.on('request', async (req: Request) => {
beforePageLoad(page) {
page.on('request', async (req) => {
const url = new URL(req.url())
const headers = await req.allHeaders()
if (headers['rsc']) {
......@@ -659,8 +658,8 @@ describe('app dir - prefetching', () => {
let interceptRequests = false
const browser = await next.browser('/prefetch-race', {
beforePageLoad(page: Page) {
page.route('**/force-dynamic/**', async (route: Route) => {
beforePageLoad(page) {
page.route('**/force-dynamic/**', async (route) => {
if (!interceptRequests) {
return route.continue()
}
......
......@@ -6,12 +6,12 @@ describe('router autoscrolling on navigation with css modules', () => {
files: __dirname,
})
type BrowserInterface = Awaited<ReturnType<(typeof next)['browser']>>
type Playwright = Awaited<ReturnType<(typeof next)['browser']>>
const getTopScroll = async (browser: BrowserInterface) =>
const getTopScroll = async (browser: Playwright) =>
await browser.eval('document.documentElement.scrollTop')
const getLeftScroll = async (browser: BrowserInterface) =>
const getLeftScroll = async (browser: Playwright) =>
await browser.eval('document.documentElement.scrollLeft')
const waitForScrollToComplete = (
......@@ -27,7 +27,7 @@ describe('router autoscrolling on navigation with css modules', () => {
}, 'success')
const scrollTo = async (
browser: BrowserInterface,
browser: Playwright,
options: { x: number; y: number }
) => {
await browser.eval(`window.scrollTo(${options.x}, ${options.y})`)
......
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
const WITH_PPR = !!process.env.__NEXT_EXPERIMENTAL_PPR
......@@ -16,7 +16,7 @@ describe('dynamic-io', () => {
}
if (isNextDev && !WITH_PPR) {
async function hasStaticIndicator(browser: BrowserInterface) {
async function hasStaticIndicator(browser: Playwright) {
await browser.elementByCss('[data-nextjs-dev-tools-button]').click()
return await browser.eval(
......
......@@ -5,7 +5,6 @@ import {
getTitle,
retry,
} from 'next-test-utils'
import { Request } from 'playwright'
describe('app dir - metadata navigation', () => {
const { next } = nextTestSetup({
......@@ -115,7 +114,7 @@ describe('app dir - metadata navigation', () => {
const browser = await next.browser('/server-action/not-found')
// collect server action requests
let isActionSent = false
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
if (
req.method() === 'POST' &&
req.url().endsWith('/server-action/not-found')
......
import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
import type { Request, Response } from 'playwright'
describe('app dir - navigation', () => {
const { next, isNextDev, isNextStart, isNextDeploy } = nextTestSetup({
......@@ -44,7 +43,7 @@ describe('app dir - navigation', () => {
const browser = await next.browser('/search-params?name=名', {
beforePageLoad(page) {
page.on('response', async (res: Response) => {
page.on('response', async (res) => {
requests.push({
pathname: new URL(res.url()).pathname,
ok: res.ok(),
......@@ -497,7 +496,7 @@ describe('app dir - navigation', () => {
const browser = await next.browser(path, {
beforePageLoad(page) {
page.on('request', async (req: Request) => {
page.on('request', async (req) => {
requestedPathnames.push(new URL(req.url()).pathname)
})
},
......
......@@ -4,7 +4,7 @@ import {
NEXT_RSC_UNION_QUERY,
RSC_HEADER,
} from 'next/src/client/components/app-router-headers'
import type { Route, Page, Request as PlaywrightRequest } from 'playwright'
import type { Page, Request as PlaywrightRequest } from 'playwright'
import { WebdriverOptions } from '../../../../lib/next-webdriver'
import { retry } from '../../../../lib/next-test-utils'
......@@ -20,7 +20,7 @@ _describe('app dir - form prefetching', () => {
it("should prefetch a loading state for the form's target", async () => {
const interceptor = new RequestInterceptor({
pattern: '**/search*',
requestFilter: async (request: PlaywrightRequest) => {
requestFilter: async (request) => {
// only capture RSC requests that *aren't* prefetches
const headers = await request.allHeaders()
const isRSC = headers[RSC_HEADER.toLowerCase()] === '1'
......@@ -66,7 +66,7 @@ _describe('app dir - form prefetching', () => {
it('should not prefetch when prefetch is set to false`', async () => {
const interceptor = new RequestInterceptor({
pattern: '**/search*',
requestFilter: async (request: PlaywrightRequest) => {
requestFilter: async (request) => {
// capture all RSC requests, prefetch or not
const headers = await request.allHeaders()
const isRSC = headers[RSC_HEADER.toLowerCase()] === '1'
......@@ -164,11 +164,11 @@ class RequestInterceptor {
this.isEnabled = false
}
beforePageLoad: BeforePageLoadFn = (page: Page) => {
beforePageLoad: BeforePageLoadFn = (page) => {
const { opts } = this
page.route(
opts.pattern,
async (route: Route, request) => {
async (route, request) => {
if (!this.isEnabled) {
return route.continue()
}
......
import { nextTestSetup } from 'e2e-utils'
import { BrowserInterface } from '../../../../lib/next-webdriver'
import { Playwright } from '../../../../lib/next-webdriver'
const isReact18 = parseInt(process.env.NEXT_TEST_REACT_VERSION) === 18
......@@ -273,7 +273,7 @@ describe.each(['app', 'pages'])('%s dir - form', (type) => {
})
})
async function trackMpaNavs(session: BrowserInterface) {
async function trackMpaNavs(session: Playwright) {
const id = Date.now()
await session.eval(`window.__MPA_NAV_ID = ${id}`)
return {
......
import { nextTestSetup } from 'e2e-utils'
import type { BrowserInterface } from 'next-webdriver'
import type { Playwright } from 'next-webdriver'
describe('parallel-routes-catchall-css', () => {
const { next } = nextTestSetup({
files: __dirname,
})
async function getChildrenBackgroundColor(browser: BrowserInterface) {
async function getChildrenBackgroundColor(browser: Playwright) {
return browser.eval(
`window.getComputedStyle(document.getElementById('main')).backgroundColor`
)
}
async function getSlotBackgroundColor(browser: BrowserInterface) {
async function getSlotBackgroundColor(browser: Playwright) {
return browser.eval(
`window.getComputedStyle(document.getElementById('slot')).backgroundColor`
)
......
......@@ -246,7 +246,9 @@ describe('parallel-routes-revalidation', () => {
})
}
let initialRandomNumber = await browser.elementById('random-number')
let initialRandomNumber = await browser
.elementById('random-number')
.text()
await browser.elementByCss(`[href='${basePath}/login']`).click()
// interception modal should be visible
......
import { nextTestSetup, isNextDev } from 'e2e-utils'
import type { Route as PlaywrightRoute, Page } from 'playwright'
type Route = {
route: string
......@@ -154,8 +153,8 @@ describe('ppr-incremental', () => {
it('should not trigger a dynamic request for static pages', async () => {
let rscRequests = []
const browser = await next.browser('/', {
beforePageLoad(page: Page) {
page.route('**/static*', async (route: PlaywrightRoute) => {
beforePageLoad(page) {
page.route('**/static*', async (route) => {
const request = route.request()
const headers = await request.allHeaders()
const url = new URL(request.url())
......
import { nextTestSetup } from 'e2e-utils'
import type { Route, Page } from 'playwright'
describe('prefetch-navigation', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -17,8 +16,8 @@ describe('prefetch-navigation', () => {
{ resolve: () => Promise<void> }
>()
const browser = await next.browser('/catch-all/1', {
beforePageLoad(page: Page) {
page.route('**/catch-all/**', async (route: Route) => {
beforePageLoad(page) {
page.route('**/catch-all/**', async (route) => {
const request = route.request()
const headers = await request.allHeaders()
const url = new URL(request.url())
......
/* eslint-disable jest/no-standalone-expect */
import { nextTestSetup } from 'e2e-utils'
import { ElementHandle } from 'playwright'
describe('scripts', () => {
const { next } = nextTestSetup({
......@@ -13,7 +14,9 @@ describe('scripts', () => {
async (routerType) => {
const browser = await next.browser(routerType === 'app' ? '/' : '/pages')
expect(await browser.elementByCss('p').text()).toBe('hello world')
const scripts = await browser.elementsByCss('script')
const scripts = (await browser.elementsByCss(
'script'
)) as ElementHandle<HTMLScriptElement>[]
expect(scripts.length).toBeGreaterThan(0)
for (const script of scripts) {
const src = await script.evaluate((script) => script.src)
......@@ -38,11 +41,13 @@ describe('styles', () => {
let body = await browser.elementByCss('body')
expect(
await body.evaluate((el) =>
getComputedStyle(el).getPropertyValue('background-color')
getComputedStyle(el as Element).getPropertyValue('background-color')
)
).toBe('rgb(0, 0, 255)')
const stylesheets = await browser.elementsByCss('link[rel="stylesheet"]')
const stylesheets = (await browser.elementsByCss(
'link[rel="stylesheet"]'
)) as ElementHandle<HTMLLinkElement>[]
expect(stylesheets.length).toBeGreaterThan(0)
for (const stylesheet of stylesheets) {
const href = await stylesheet.evaluate((stylesheet) => stylesheet.href)
......
import webdriver, { type BrowserInterface } from 'next-webdriver'
import webdriver, { type Playwright } from 'next-webdriver'
import { nextTestSetup } from 'e2e-utils'
import { check, assertNoConsoleErrors, retry } from 'next-test-utils'
......@@ -7,14 +7,14 @@ describe('router autoscrolling on navigation', () => {
files: __dirname,
})
const getTopScroll = async (browser: BrowserInterface) =>
const getTopScroll = async (browser: Playwright) =>
await browser.eval('document.documentElement.scrollTop')
const getLeftScroll = async (browser: BrowserInterface) =>
const getLeftScroll = async (browser: Playwright) =>
await browser.eval('document.documentElement.scrollLeft')
const waitForScrollToComplete = async (
browser: BrowserInterface,
browser: Playwright,
options: { x: number; y: number }
) => {
await retry(async () => {
......@@ -26,7 +26,7 @@ describe('router autoscrolling on navigation', () => {
}
const scrollTo = async (
browser: BrowserInterface,
browser: Playwright,
options: { x: number; y: number }
) => {
await browser.eval(`window.scrollTo(${options.x}, ${options.y})`)
......
......@@ -2,7 +2,6 @@ import path from 'path'
import { check } from 'next-test-utils'
import { nextTestSetup } from 'e2e-utils'
import cheerio from 'cheerio'
import { Page } from 'playwright'
// TODO: We should decide on an established pattern for gating test assertions
// on experimental flags. For example, as a first step we could all the common
......@@ -165,7 +164,7 @@ describe('app dir - rsc basics', () => {
const flightRequests: string[] = []
let requestsCount = 0
const browser = await next.browser('/root', {
beforePageLoad(page: Page) {
beforePageLoad(page) {
page.on('request', (request) => {
requestsCount++
const headers = request.headers()
......@@ -376,7 +375,6 @@ describe('app dir - rsc basics', () => {
await browser.loadPage(`${next.url}/edge/dynamic/123`, {
disableCache: false,
beforePageLoad: null,
})
const dynamicRouteUrl = await browser.url()
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import { Request } from 'playwright'
describe('rsc-query-routing', () => {
const { next } = nextTestSetup({
......@@ -11,7 +10,7 @@ describe('rsc-query-routing', () => {
const browser = await next.browser('/redirect')
const rscRequestUrls: string[] = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
if (req.url().includes('?_rsc=')) {
rscRequestUrls.push(req.url())
}
......@@ -35,7 +34,7 @@ describe('rsc-query-routing', () => {
const browser = await next.browser('/rewrite')
const rscRequestUrls: string[] = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
if (req.url().includes('?_rsc=')) {
rscRequestUrls.push(req.url())
}
......
import { nextTestSetup } from 'e2e-utils'
import { retry } from 'next-test-utils'
import type { Route, Page } from 'playwright'
describe('searchparams-reuse-loading', () => {
const { next, isNextDev } = nextTestSetup({
......@@ -181,8 +180,8 @@ describe('searchparams-reuse-loading', () => {
let interceptRequests = false
const browser = await next.browser(path, {
beforePageLoad(page: Page) {
page.route('**/search-params*', async (route: Route) => {
beforePageLoad(page) {
page.route('**/search-params*', async (route) => {
if (!interceptRequests) {
return route.continue()
}
......@@ -291,8 +290,8 @@ describe('searchparams-reuse-loading', () => {
let interceptRequests = false
const browser = await next.browser('/onclick-navs/version-1', {
beforePageLoad(page: Page) {
page.route('**/search-params*', async (route: Route) => {
beforePageLoad(page) {
page.route('**/search-params*', async (route) => {
if (!interceptRequests) {
return route.continue()
}
......@@ -377,8 +376,8 @@ describe('searchparams-reuse-loading', () => {
let interceptRequests = false
const browser = await next.browser('/onclick-navs/version-2', {
beforePageLoad(page: Page) {
page.route('**/search-params*', async (route: Route) => {
beforePageLoad(page) {
page.route('**/search-params*', async (route) => {
if (!interceptRequests) {
return route.continue()
}
......@@ -463,8 +462,8 @@ describe('searchparams-reuse-loading', () => {
let interceptRequests = false
const browser = await next.browser('/onclick-navs/version-3', {
beforePageLoad(page: Page) {
page.route('**/search-params*', async (route: Route) => {
beforePageLoad(page) {
page.route('**/search-params*', async (route) => {
if (!interceptRequests) {
return route.continue()
}
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache (basic tests)', () => {
......@@ -15,7 +14,7 @@ describe('segment cache (basic tests)', () => {
it('navigate before any data has loaded into the prefetch cache', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -58,7 +57,7 @@ describe('segment cache (basic tests)', () => {
it('navigate with prefetched data', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -97,7 +96,7 @@ describe('segment cache (basic tests)', () => {
it('navigate to page with lazily-generated (not at build time) static param', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/lazily-generated-params', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -134,7 +133,7 @@ describe('segment cache (basic tests)', () => {
it('prefetch interception route', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/interception/feed', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -166,7 +165,7 @@ describe('segment cache (basic tests)', () => {
it('skips dynamic request if prefetched data is fully static', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/fully-static', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -197,7 +196,7 @@ describe('segment cache (basic tests)', () => {
it('skips static layouts during partially static navigation', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/partially-static', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -245,7 +244,7 @@ describe('segment cache (basic tests)', () => {
it('refreshes page segments when navigating to the exact same URL as the current location', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/same-page-nav', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache (incremental opt in)', () => {
......@@ -25,9 +24,9 @@ describe('segment cache (incremental opt in)', () => {
let act
const browser = await next.browser('/', {
async beforePageLoad(page: Playwright.Page) {
async beforePageLoad(page) {
act = createRouterAct(page)
await page.route('**/*', async (route: Playwright.Route) => {
await page.route('**/*', async (route) => {
const request = route.request()
const isPrefetch =
request.headerValue('rsc') !== null &&
......@@ -99,7 +98,7 @@ describe('segment cache (incremental opt in)', () => {
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
......@@ -138,7 +137,7 @@ describe('segment cache (incremental opt in)', () => {
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
......@@ -177,7 +176,7 @@ describe('segment cache (incremental opt in)', () => {
async () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
......@@ -238,7 +237,7 @@ describe('segment cache (incremental opt in)', () => {
let act
const browser = await next.browser('/mixed-fetch-strategies', {
beforePageLoad(p: Playwright.Page) {
beforePageLoad(p) {
act = createRouterAct(p)
},
})
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache memory pressure', () => {
......@@ -15,7 +14,7 @@ describe('segment cache memory pressure', () => {
it('evicts least recently used prefetch data once cache size exceeds limit', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/memory-pressure', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......
......@@ -10,13 +10,16 @@ describe('segment cache (MPA navigations)', () => {
return
}
type ElementWithExpando = Element & { __expando?: boolean }
it('triggers MPA navigation when navigating to a different root layout', async () => {
const browser = await next.browser('/')
// Set an expando on the html element so we can detect if the page
// gets unloaded.
const html = await browser.elementByCss('html')
await html.evaluate((el) => (el.__expando = true))
await html.evaluate((el) => ((el as ElementWithExpando).__expando = true))
// Navigate to a page with a different root layout.
const link = await browser.elementByCss(`a[href="/foo"]`)
......@@ -24,7 +27,9 @@ describe('segment cache (MPA navigations)', () => {
// The expando should not be present because we did a full-page navigation.
const htmlAfterNav = await browser.elementByCss('html')
expect(await htmlAfterNav.evaluate((el) => el.__expando)).toBe(undefined)
expect(
await htmlAfterNav.evaluate((el) => (el as ElementWithExpando).__expando)
).toBe(undefined)
})
it(
......@@ -41,7 +46,7 @@ describe('segment cache (MPA navigations)', () => {
// Set an expando on the html element so we can detect if the page
// gets unloaded.
const html = await browser.elementByCss('html')
await html.evaluate((el) => (el.__expando = true))
await html.evaluate((el) => ((el as ElementWithExpando).__expando = true))
// Navigate to a page with a different root layout.
const link = await browser.elementByCss(`a[href="/bar/inner"]`)
......@@ -49,7 +54,11 @@ describe('segment cache (MPA navigations)', () => {
// The expando should not be present because we did a full-page navigation.
const htmlAfterNav = await browser.elementByCss('html')
expect(await htmlAfterNav.evaluate((el) => el.__expando)).toBe(undefined)
expect(
await htmlAfterNav.evaluate(
(el) => (el as ElementWithExpando).__expando
)
).toBe(undefined)
}
)
})
import { isNextDev, isNextDeploy, createNext } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
import { createTestDataServer } from 'test-data-service/writer'
import { createTestLog } from 'test-log'
......@@ -53,7 +52,7 @@ describe('segment cache (revalidation)', () => {
it('evict client cache when Server Action calls revalidatePath', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -104,7 +103,7 @@ describe('segment cache (revalidation)', () => {
// be sufficient.
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -153,7 +152,7 @@ describe('segment cache (revalidation)', () => {
it('evict client cache when Server Action calls revalidateTag', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -200,7 +199,7 @@ describe('segment cache (revalidation)', () => {
it('re-fetch visible links after a navigation, if needed', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/refetch-on-new-base-tree/a', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......
import { nextTestSetup } from 'e2e-utils'
import type * as Playwright from 'playwright'
import { createRouterAct } from '../router-act'
describe('segment cache (search params)', () => {
......@@ -15,7 +14,7 @@ describe('segment cache (search params)', () => {
it('when fetching with PPR, does not include search params in the cache key', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......@@ -71,7 +70,7 @@ describe('segment cache (search params)', () => {
it('when fetching without PPR (e.g. prefetch={true}), includes the search params in the cache key', async () => {
let act: ReturnType<typeof createRouterAct>
const browser = await next.browser('/search-params', {
beforePageLoad(page: Playwright.Page) {
beforePageLoad(page) {
act = createRouterAct(page)
},
})
......
......@@ -2,7 +2,7 @@ import { nextTestSetup } from 'e2e-utils'
import { retry, waitFor } from 'next-test-utils'
import stripAnsi from 'strip-ansi'
import { format } from 'util'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
import {
createRenderResumeDataCache,
RenderResumeDataCache,
......@@ -915,7 +915,7 @@ describe('use-cache', () => {
}
})
async function getSanitizedLogs(browser: BrowserInterface): Promise<string[]> {
async function getSanitizedLogs(browser: Playwright): Promise<string[]> {
const logs = await browser.log({ includeArgs: true })
return logs.map(({ args }) =>
......
import * as path from 'path'
import { nextTestSetup } from 'e2e-utils'
import { BrowserInterface } from 'next-webdriver'
import { Playwright } from 'next-webdriver'
async function assertNoConsoleErrors(browser: BrowserInterface) {
async function assertNoConsoleErrors(browser: Playwright) {
const logs = await browser.log()
const warningsAndErrors = logs.filter((log) => {
return log.source === 'warning' || log.source === 'error'
......
import type { Request } from 'playwright'
import { join } from 'path'
import { FileRef, nextTestSetup } from 'e2e-utils'
......@@ -13,7 +12,7 @@ describe('i18-preferred-locale-redirect', () => {
})
let requestedPreferredLocalePathCount = 0
browser.on('request', (request: Request) => {
browser.on('request', (request) => {
if (new URL(request.url(), 'http://n').pathname === '/id') {
requestedPreferredLocalePathCount++
}
......
......@@ -2,11 +2,11 @@ import { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils'
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import type { HistoryState } from 'next/dist/shared/lib/router/router'
const emitPopsStateEvent = (browser: BrowserInterface, state: HistoryState) =>
const emitPopsStateEvent = (browser: Playwright, state: HistoryState) =>
browser.eval(
`window.dispatchEvent(new PopStateEvent("popstate", { state: ${JSON.stringify(
state
......
......@@ -2,11 +2,11 @@ import { join } from 'path'
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { check, waitFor } from 'next-test-utils'
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import type { HistoryState } from 'next/dist/shared/lib/router/router'
const emitPopsStateEvent = (browser: BrowserInterface, state: HistoryState) =>
const emitPopsStateEvent = (browser: Playwright, state: HistoryState) =>
browser.eval(
`window.dispatchEvent(new PopStateEvent("popstate", { state: ${JSON.stringify(
state
......
......@@ -7,7 +7,6 @@ import { NextInstance } from 'e2e-utils'
import { check, fetchViaHTTP, retry } from 'next-test-utils'
import { createNext, FileRef } from 'e2e-utils'
import escapeStringRegexp from 'escape-string-regexp'
import { Request, Response } from 'playwright'
describe('Middleware Rewrite', () => {
let next: NextInstance
......@@ -30,7 +29,7 @@ describe('Middleware Rewrite', () => {
if (!(global as any).isNextDev) {
let requests = []
browser.on('request', (req: Request) => {
browser.on('request', (req) => {
requests.push(new URL(req.url()).pathname)
})
......@@ -369,7 +368,7 @@ describe('Middleware Rewrite', () => {
await browser.waitForIdleNetwork()
let hasResolvedPrefetch = false
browser.on('response', async (res: Response) => {
browser.on('response', async (res) => {
const req = res.request()
const headers = await req.allHeaders()
if (
......
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { check } from 'next-test-utils'
......@@ -45,7 +45,7 @@ describe('beforeInteractive in document Head', () => {
afterAll(() => next.destroy())
it('Script is injected server-side', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -101,7 +101,7 @@ describe('beforeInteractive in document body', () => {
afterAll(() => next.destroy())
it('Script is injected server-side', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -158,7 +158,7 @@ describe('empty strategy in document Head', () => {
afterAll(() => next.destroy())
it('Script is injected server-side', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -213,7 +213,7 @@ describe('empty strategy in document body', () => {
afterAll(() => next.destroy())
it('Script is injected server-side', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -256,7 +256,7 @@ describe('empty strategy in document body', () => {
afterAll(() => next.destroy())
it('Partytown snippet is not injected to head if not enabled in configuration', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -306,7 +306,7 @@ describe('empty strategy in document body', () => {
afterAll(() => next.destroy())
it('Partytown snippets are injected to head if enabled in configuration', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -331,7 +331,7 @@ describe('empty strategy in document body', () => {
})
it('Worker scripts are modified by Partytown to execute on a worker thread', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -391,7 +391,7 @@ describe('empty strategy in document body', () => {
})
it('Inline worker script through children is modified by Partytown to execute on a worker thread', async () => {
let browser: BrowserInterface
let browser: Playwright
next = await createNextApp(
`<Script id="inline-script" strategy="worker">{"document.getElementById('text').textContent += 'abc'"}</Script>`
......@@ -416,7 +416,7 @@ describe('empty strategy in document body', () => {
})
it('Inline worker script through dangerouslySetInnerHtml is modified by Partytown to execute on a worker thread', async () => {
let browser: BrowserInterface
let browser: Playwright
next = await createNextApp(
`<Script id="inline-script" strategy="worker" dangerouslySetInnerHTML={{__html: "document.getElementById('text').textContent += 'abcd'"}}/>`
......@@ -506,7 +506,7 @@ describe('empty strategy in document body', () => {
afterAll(() => next.destroy())
it('Partytown config script is overwritten', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......
......@@ -11,7 +11,7 @@ import {
getRedboxTotalErrorCount,
openRedbox,
} from './next-test-utils'
import type { BrowserInterface } from './browsers/base'
import type { Playwright } from 'next-webdriver'
import { NextInstance } from 'e2e-utils'
declare global {
......@@ -72,7 +72,7 @@ interface ErrorSnapshot {
}
async function createErrorSnapshot(
browser: BrowserInterface,
browser: Playwright,
next: NextInstance | null
): Promise<ErrorSnapshot> {
const [label, environmentLabel, description, source, stack, componentStack] =
......@@ -164,7 +164,7 @@ async function createErrorSnapshot(
type RedboxSnapshot = ErrorSnapshot | ErrorSnapshot[]
async function createRedboxSnapshot(
browser: BrowserInterface,
browser: Playwright,
next: NextInstance | null
): Promise<RedboxSnapshot> {
const errorTally = await getRedboxTotalErrorCount(browser)
......@@ -196,12 +196,10 @@ async function createRedboxSnapshot(
expect.extend({
async toDisplayRedbox(
this: MatcherContext,
browserOrContext:
| BrowserInterface
| { browser: BrowserInterface; next: NextInstance },
browserOrContext: Playwright | { browser: Playwright; next: NextInstance },
expectedRedboxSnapshot?: string
) {
let browser: BrowserInterface
let browser: Playwright
let next: NextInstance | null
if ('browser' in browserOrContext && 'next' in browserOrContext) {
browser = browserOrContext.browser
......@@ -247,12 +245,10 @@ expect.extend({
},
async toDisplayCollapsedRedbox(
this: MatcherContext,
browserOrContext:
| BrowserInterface
| { browser: BrowserInterface; next: NextInstance },
browserOrContext: Playwright | { browser: Playwright; next: NextInstance },
expectedRedboxSnapshot?: string
) {
let browser: BrowserInterface
let browser: Playwright
let next: NextInstance | null
if ('browser' in browserOrContext && 'next' in browserOrContext) {
browser = browserOrContext.browser
......
export type Event = 'request' | 'response'
/**
* This is the base Browser interface all browser
* classes should build on, it is the bare
* methods we aim to support across tests
*/
export abstract class BrowserInterface<TCurrent = any> {
private promise?: Promise<TCurrent>;
// necessary for the type of the function below
readonly [Symbol.toStringTag]: string = 'BrowserInterface'
protected chain<TNext>(
nextCall: (current: TCurrent | undefined) => TNext | Promise<TNext>
): BrowserInterface<TNext> & Promise<TNext> {
const syncError = new Error('next-browser-base-chain-error')
const promise = Promise.resolve(this.promise)
.then(nextCall)
.catch((reason) => {
if (
reason !== null &&
typeof reason === 'object' &&
'stack' in reason
) {
const syncCallStack = syncError.stack!.split(syncError.message)[1]
reason.stack += `\n${syncCallStack}`
}
throw reason
})
function get(target: BrowserInterface<TNext>, p: string | symbol): any {
switch (p) {
case 'promise':
return promise
case 'then':
return promise.then.bind(promise)
case 'catch':
return promise.catch.bind(promise)
case 'finally':
return promise.finally.bind(promise)
default:
return target[p]
}
}
return new Proxy<any>(this, {
get,
})
}
abstract setup(
browserName: string,
locale: string,
javaScriptEnabled: boolean,
ignoreHttpsErrors: boolean,
headless: boolean,
userAgent: string | undefined
): Promise<void>
abstract close(): Promise<void>
abstract elementsByCss(
selector: string
): BrowserInterface<any[]> & Promise<any[]>
abstract elementByCss(selector: string): BrowserInterface<any> & Promise<any>
abstract elementById(selector: string): BrowserInterface<any> & Promise<any>
abstract touchStart(): BrowserInterface<any> & Promise<any>
abstract click(): BrowserInterface<any> & Promise<any>
abstract keydown(key: string): BrowserInterface<any> & Promise<any>
abstract keyup(key: string): BrowserInterface<any> & Promise<any>
abstract type(text: string): BrowserInterface<any> & Promise<any>
abstract moveTo(): BrowserInterface<any> & Promise<any>
abstract waitForElementByCss(
selector: string,
timeout?: number
): BrowserInterface<any> & Promise<any>
abstract waitForCondition(
snippet: string,
timeout?: number
): BrowserInterface<any> & Promise<any>
/**
* Use browsers `go back` functionality.
*/
abstract back(options?: any): BrowserInterface<any> & Promise<any>
/**
* Use browsers `go forward` functionality. Inverse of back.
*/
abstract forward(options?: any): BrowserInterface<any> & Promise<any>
abstract refresh(): BrowserInterface<any> & Promise<any>
abstract setDimensions(opts: {
height: number
width: number
}): BrowserInterface<any> & Promise<any>
abstract addCookie(opts: {
name: string
value: string
}): BrowserInterface<any> & Promise<any>
abstract deleteCookies(): BrowserInterface<void> & Promise<void>
abstract on(event: Event, cb: (...args: any[]) => void): void
abstract off(event: Event, cb: (...args: any[]) => void): void
abstract loadPage(
url: string,
options?: {
disableCache?: boolean
cpuThrottleRate?: number
beforePageLoad?: Function
pushErrorAsConsoleLog?: boolean
}
): Promise<void>
abstract get(url: string): Promise<void>
abstract getValue(): Promise<string>
abstract getAttribute(name: string): Promise<string | null>
abstract eval(snippet: string | Function, ...args: any[]): Promise<any>
abstract evalAsync(snippet: string | Function, ...args: any[]): Promise<any>
abstract text(): Promise<string>
abstract getComputedCss(prop: string): Promise<string>
abstract hasElementByCssSelector(selector: string): Promise<boolean>
abstract log<T extends boolean = false>(options?: {
includeArgs?: T
}): Promise<
T extends true
? { source: string; message: string; args: unknown[] }[]
: { source: string; message: string }[]
>
abstract websocketFrames(): Promise<any[]>
abstract url(): Promise<string>
abstract waitForIdleNetwork(): Promise<void>
}
This diff is collapsed.
......@@ -14,20 +14,21 @@ import {
} from './next-test-utils'
import webdriver, { WebdriverOptions } from './next-webdriver'
import { NextInstance } from './next-modes/base'
import { BrowserInterface } from './browsers/base'
import { Playwright } from 'next-webdriver'
export function waitForHydration(browser: BrowserInterface): Promise<void> {
return browser.evalAsync(function () {
var callback = arguments[arguments.length - 1]
if ((window as any).__NEXT_HYDRATED) {
callback()
} else {
var timeout = setTimeout(callback, 30 * 1000)
;(window as any).__NEXT_HYDRATED_CB = function () {
clearTimeout(timeout)
callback()
export async function waitForHydration(browser: Playwright) {
await browser.eval(() => {
return new Promise<void>((resolve) => {
if ((window as any).__NEXT_HYDRATED) {
resolve()
} else {
var timeout = setTimeout(resolve, 30 * 1000)
;(window as any).__NEXT_HYDRATED_CB = function () {
clearTimeout(timeout)
resolve()
}
}
}
})
})
}
......@@ -50,6 +51,26 @@ export async function createSandbox(
await next.start()
const browser = await webdriver(next.url, initialUrl, webDriverOptions)
async function evaluate<TFn extends (...args: any[]) => any>(
fn: TFn,
...args: Parameters<TFn>
): Promise<ReturnType<TFn>>
async function evaluate(fn: string): Promise<unknown>
async function evaluate(
snippet: string | ((...args: any) => any)
): Promise<any> {
if (typeof snippet === 'function' || typeof snippet === 'string') {
const result = await browser.eval(snippet)
await waitFor(30)
return result
} else {
throw new Error(
`You must pass a string or function to be evaluated in the browser.`
)
}
}
return {
browser,
session: {
......@@ -106,17 +127,7 @@ export async function createSandbox(
async remove(filename) {
await next.deleteFile(filename)
},
async evaluate(snippet: string | Function) {
if (typeof snippet === 'function' || typeof snippet === 'string') {
const result = await browser.eval(snippet)
await waitFor(30)
return result
} else {
throw new Error(
`You must pass a string or function to be evaluated in the browser.`
)
}
},
evaluate,
async assertHasRedbox() {
return assertHasRedbox(browser)
},
......
......@@ -11,7 +11,7 @@ import webdriver from '../next-webdriver'
import { renderViaHTTP, fetchViaHTTP, findPort } from 'next-test-utils'
import cheerio from 'cheerio'
import { once } from 'events'
import { BrowserInterface } from '../browsers/base'
import { Playwright } from 'next-webdriver'
import escapeStringRegexp from 'escape-string-regexp'
type Event = 'stdout' | 'stderr' | 'error' | 'destroy'
......@@ -656,7 +656,7 @@ export class NextInstance {
*/
public async browser(
...args: Parameters<OmitFirstArgument<typeof webdriver>>
): Promise<BrowserInterface> {
): Promise<Playwright> {
return webdriver(this.url, ...args)
}
......
This diff is collapsed.
import { getFullUrl, waitFor } from 'next-test-utils'
import os from 'os'
import { BrowserInterface } from './browsers/base'
import { Playwright } from './browsers/playwright'
import { Page } from 'playwright'
export type { Playwright }
if (!process.env.TEST_FILE_PATH) {
process.env.TEST_FILE_PATH = module.parent!.filename
......@@ -59,7 +62,7 @@ export interface WebdriverOptions {
* @param page
* @returns
*/
beforePageLoad?: (page: any) => void
beforePageLoad?: (page: Page) => void
/**
* browser locale
*/
......@@ -92,9 +95,7 @@ export default async function webdriver(
appPortOrUrl: string | number,
url: string,
options?: WebdriverOptions
): Promise<BrowserInterface> {
let CurrentInterface: new () => BrowserInterface
): Promise<Playwright> {
const defaultOptions = {
waitHydration: true,
retryWaitHydration: false,
......@@ -116,10 +117,9 @@ export default async function webdriver(
} = options
const { Playwright, quit } = await import('./browsers/playwright')
CurrentInterface = Playwright
browserQuit = quit
const browser = new CurrentInterface()
const browser = new Playwright()
const browserName = process.env.BROWSER_NAME || 'chrome'
await browser.setup(
browserName,
......@@ -155,33 +155,33 @@ export default async function webdriver(
console.log(`\n> Waiting hydration for ${fullUrl}\n`)
const checkHydrated = async () => {
await browser.evalAsync(function () {
var callback = arguments[arguments.length - 1]
// if it's not a Next.js app return
if (
!document.documentElement.innerHTML.includes('__NEXT_DATA__') &&
// @ts-ignore next exists on window if it's a Next.js page.
typeof ((window as any).next && (window as any).next.version) ===
'undefined'
) {
console.log('Not a next.js page, resolving hydrate check')
callback()
}
// TODO: should we also ensure router.isReady is true
// by default before resolving?
if ((window as any).__NEXT_HYDRATED) {
console.log('Next.js page already hydrated')
callback()
} else {
var timeout = setTimeout(callback, 10 * 1000)
;(window as any).__NEXT_HYDRATED_CB = function () {
clearTimeout(timeout)
console.log('Next.js hydrate callback fired')
await browser.eval(() => {
return new Promise<void>((callback) => {
// if it's not a Next.js app return
if (
!document.documentElement.innerHTML.includes('__NEXT_DATA__') &&
// @ts-ignore next exists on window if it's a Next.js page.
typeof ((window as any).next && (window as any).next.version) ===
'undefined'
) {
console.log('Not a next.js page, resolving hydrate check')
callback()
}
// TODO: should we also ensure router.isReady is true
// by default before resolving?
if ((window as any).__NEXT_HYDRATED) {
console.log('Next.js page already hydrated')
callback()
} else {
let timeout = setTimeout(callback, 10 * 1000)
;(window as any).__NEXT_HYDRATED_CB = function () {
clearTimeout(timeout)
console.log('Next.js hydrate callback fired')
callback()
}
}
}
})
})
}
......@@ -209,5 +209,3 @@ export default async function webdriver(
}
return browser
}
export { BrowserInterface }
import { createNext, FileRef } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { join } from 'path'
import { BrowserInterface } from '../../lib/browsers/base'
import { Playwright } from 'next-webdriver'
import webdriver from 'next-webdriver'
import { check } from 'next-test-utils'
......@@ -19,7 +19,7 @@ describe('app-dir-prefetch-non-iso-url', () => {
afterAll(() => next.destroy())
it('should go to iso url', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......@@ -33,7 +33,7 @@ describe('app-dir-prefetch-non-iso-url', () => {
})
it('should go to non-iso url', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
......
......@@ -36,7 +36,7 @@ describe('bfcache-routing', () => {
const browser = await webdriver(port, '/index.html', { headless: false })
// we overwrite the typical waitUntil: 'load' option here as the event is never being triggered if we hit the bfcache
const bfOptions = { waitUntil: 'commit' }
const bfOptions = { waitUntil: 'commit' as const }
await browser.elementByCss('a[href="https://example.vercel.sh"]').click()
await browser.waitForCondition(
......@@ -49,14 +49,14 @@ describe('bfcache-routing', () => {
'window.location.origin.includes("localhost")'
)
let html = await browser.evalAsync('document.documentElement.innerHTML')
let html = await browser.eval<string>('document.documentElement.innerHTML')
expect(html).toContain('BFCache Test')
await browser.evalAsync(`document.querySelector('button').click()`)
await browser.eval(`document.querySelector('button').click()`)
// we should still be on the test page
html = await browser.evalAsync('document.documentElement.innerHTML')
html = await browser.eval<string>('document.documentElement.innerHTML')
expect(html).toContain('BFCache Test')
await browser.forward(bfOptions)
......@@ -67,13 +67,13 @@ describe('bfcache-routing', () => {
)
// we should be back on the test page with no errors
html = await browser.evalAsync('document.documentElement.innerHTML')
html = await browser.eval<string>('document.documentElement.innerHTML')
expect(html).toContain('BFCache Test')
// After restoring from bfcache, a subsequent mpa navigation to the same URL should work
// We trigger the click via `evalAsync` because when restoring from bfcache, our internal
// We trigger the click via `eval` because when restoring from bfcache, our internal
// 'waitForElementByCss' method doesn't think the element is attached to the DOM.
await browser.evalAsync(
await browser.eval(
`document.querySelector('a[href="https://example.vercel.sh"]').click()`
)
await browser.waitForCondition(
......
import { join } from 'path'
import webdriver, { BrowserInterface } from 'next-webdriver'
import webdriver, { Playwright } from 'next-webdriver'
import { createNext } from 'e2e-utils'
import { NextInstance } from 'e2e-utils'
import { fetchViaHTTP } from 'next-test-utils'
......@@ -21,7 +21,7 @@ describe('emitDecoratorMetadata SWC option', () => {
afterAll(() => next.destroy())
it('should compile with emitDecoratorMetadata enabled', async () => {
let browser: BrowserInterface
let browser: Playwright
try {
browser = await webdriver(next.url, '/')
const message = await browser.elementByCss('#message').text()
......
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