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