rsnext/test/lib/next-webdriver.ts

Ignoring revisions in .git-blame-ignore-revs. Click here to bypass and see the normal blame view.

200 lines
5.5 KiB
TypeScript
Raw Normal View History

Add --ci to jest tests in CI (#60432) ## What? Ensures snapshot tests fail instead of being written in CI. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Closes NEXT-2035
2024-01-11 10:23:20 +01:00
import { getFullUrl, waitFor } from 'next-test-utils'
import os from 'os'
import { BrowserInterface } from './browsers/base'
if (!process.env.TEST_FILE_PATH) {
process.env.TEST_FILE_PATH = module.parent.filename
}
let deviceIP: string
const isBrowserStack = !!process.env.BROWSERSTACK
;(global as any).browserName = process.env.BROWSER_NAME || 'chrome'
if (isBrowserStack) {
const nets = os.networkInterfaces()
for (const key of Object.keys(nets)) {
let done = false
for (const item of nets[key]) {
if (item.family === 'IPv4' && !item.internal) {
deviceIP = item.address
done = true
break
}
}
if (done) break
}
}
let browserTeardown: (() => Promise<void>)[] = []
let browserQuit: (() => Promise<void>) | undefined
if (typeof afterAll === 'function') {
afterAll(async () => {
await Promise.all(browserTeardown.map((f) => f())).catch((e) =>
console.error('browser teardown', e)
)
if (browserQuit) {
await browserQuit()
}
})
}
/**
*
* @param appPortOrUrl can either be the port or the full URL
* @param url the path/query to append when using appPort
* @param options
* @param options.waitHydration whether to wait for React hydration to finish
* @param options.retryWaitHydration allow retrying hydration wait if reload occurs
* @param options.disableCache disable cache for page load
* @param options.beforePageLoad the callback receiving page instance before loading page
* @param options.locale browser locale
* @param options.disableJavaScript disable javascript
* @param options.ignoreHttpsErrors ignore https errors
* @returns thenable browser instance
*/
export default async function webdriver(
appPortOrUrl: string | number,
url: string,
options?: {
waitHydration?: boolean
retryWaitHydration?: boolean
disableCache?: boolean
beforePageLoad?: (page: any) => void
locale?: string
disableJavaScript?: boolean
headless?: boolean
ignoreHTTPSErrors?: boolean
cpuThrottleRate?: number
pushErrorAsConsoleLog?: boolean
}
): Promise<BrowserInterface> {
let CurrentInterface: new () => BrowserInterface
const defaultOptions = {
waitHydration: true,
retryWaitHydration: false,
disableCache: false,
}
options = Object.assign(defaultOptions, options)
const {
waitHydration,
retryWaitHydration,
disableCache,
beforePageLoad,
locale,
disableJavaScript,
ignoreHTTPSErrors,
headless,
cpuThrottleRate,
pushErrorAsConsoleLog,
} = options
// we import only the needed interface
if (
process.env.RECORD_REPLAY === 'true' ||
process.env.RECORD_REPLAY === '1'
) {
const { Replay, quit } = await require('./browsers/replay')
CurrentInterface = Replay
browserQuit = quit
} else {
const { Playwright, quit } = await import('./browsers/playwright')
CurrentInterface = Playwright
browserQuit = quit
}
const browser = new CurrentInterface()
const browserName = process.env.BROWSER_NAME || 'chrome'
await browser.setup(
browserName,
locale,
!disableJavaScript,
ignoreHTTPSErrors,
// allow headless to be overwritten for a particular test
typeof headless !== 'undefined' ? headless : !!process.env.HEADLESS
)
;(global as any).browserName = browserName
const fullUrl = getFullUrl(
appPortOrUrl,
url,
isBrowserStack ? deviceIP : 'localhost'
)
console.log(`\n> Loading browser with ${fullUrl}\n`)
await browser.loadPage(fullUrl, {
disableCache,
cpuThrottleRate,
beforePageLoad,
pushErrorAsConsoleLog,
})
console.log(`\n> Loaded browser with ${fullUrl}\n`)
browserTeardown.push(browser.close.bind(browser))
// Wait for application to hydrate
if (waitHydration) {
console.log(`\n> Waiting hydration for ${fullUrl}\n`)
const checkHydrated = async () => {
await browser.evalAsync(function () {
var callback = arguments[arguments.length - 1]
// if it's not a Next.js app return
if (
!document.documentElement.innerHTML.includes('__NEXT_DATA__') &&
Add prefetch to new router (#39866) Follow-up to #37551 Implements prefetching for the new router. There are multiple behaviors related to prefetching so I've split them out for each case. The list below each case is what's prefetched: Reference: - Checkmark checked → it's implemented. - RSC Payload → Rendered server components. - Router state → Patch for the router history state. - Preloads for client component entry → This will be handled in a follow-up PR. - No `loading.js` static case → Will be handled in a follow-up PR. --- - `prefetch={true}` (default, same as current router, links in viewport are prefetched) - [x] Static all the way down the component tree - [x] RSC payload - [x] Router state - [ ] preloads for the client component entry - [x] Not static all the way down the component tree - [x] With `loading.js` - [x] RSC payload up until the loading below the common layout - [x] router state - [ ] preloads for the client component entry - [x] No `loading.js` (This case can be static files to make sure it’s fast) - [x] router state - [ ] preloads for the client component entry - `prefetch={false}` - [x] always do an optimistic navigation. We already have this implemented where it tries to figure out the router state based on the provided url. That result might be wrong but the router will automatically figure out that --- In the first implementation there is a distinction between `hard` and `soft` navigation. With the addition of prefetching you no longer have to add a `soft` prop to `next/link` in order to leverage the `soft` case. A heuristic has been added that automatically prefers `soft` navigation except when navigating between mismatching dynamic parameters. An example: - `app/[userOrTeam]/dashboard/page.js` and `app/[userOrTeam]/dashboard/settings/page.js` - `/tim/dashboard` → `/tim/dashboard/settings` = Soft navigation - `/tim/dashboard` → `/vercel/dashboard` = Hard navigation - `/vercel/dashboard` → `/vercel/dashboard/settings` = Soft navigation - `/vercel/dashboard/settings` -> `/tim/dashboard` = Hard navigation --- While adding these new heuristics some of the tests started failing and I found some state bugs in `router.reload()` which have been fixed. An example being when you push to `/dashboard` while on `/` in the same transition it would navigate to `/`, it also wouldn't push a new history entry. Both of these cases are now fixed: ``` React.startTransition(() => { router.push('/dashboard') router.reload() }) ``` --- While debugging the various changes I ended up debugging and manually diffing the cache and router state quite often and was looking at a way to automate this. `useReducer` is quite similar to Redux so I was wondering if Redux Devtools could be used in order to debug the various actions as it has diffing built-in. It took a bit of time to figure out the connection mechanism but in the end I figured out how to connect `useReducer`, a new hook `useReducerWithReduxDevtools` has been added, we'll probably want to put this behind a compile-time flag when the new router is marked stable but until then it's useful to have it enabled by default (only when you have Redux Devtools installed ofcourse). > ⚠️ Redux Devtools is only connected to take incoming actions / state. Time travel and other features are not supported because the state sent to the devtools is normalized to allow diffing the maps, you can't move backward based on that state so applying the state is not connected. Example of the integration: <img width="1912" alt="Screen Shot 2022-09-02 at 10 00 40" src="https://user-images.githubusercontent.com/6324199/188637303-ad8d6a81-15e5-4b65-875b-1c4f93df4e44.png">
2022-09-06 19:29:09 +02:00
// @ts-ignore next exists on window if it's a Next.js page.
typeof ((window as any).next && (window as any).next.version) ===
'undefined'
) {
console.log('Not a next.js page, resolving hydrate check')
callback()
}
// TODO: should we also ensure router.isReady is true
// by default before resolving?
if ((window as any).__NEXT_HYDRATED) {
console.log('Next.js page already hydrated')
callback()
} else {
var timeout = setTimeout(callback, 10 * 1000)
;(window as any).__NEXT_HYDRATED_CB = function () {
clearTimeout(timeout)
console.log('Next.js hydrate callback fired')
callback()
}
}
})
}
try {
await checkHydrated()
} catch (err) {
if (retryWaitHydration) {
// re-try in case the page reloaded during check
await new Promise((resolve) => setTimeout(resolve, 2000))
await checkHydrated()
} else {
console.error('failed to check hydration')
throw err
}
}
console.log(`\n> Hydration complete for ${fullUrl}\n`)
}
Add --ci to jest tests in CI (#60432) ## What? Ensures snapshot tests fail instead of being written in CI. <!-- Thanks for opening a PR! Your contribution is much appreciated. To make sure your PR is handled as smoothly as possible we request that you follow the checklist sections below. Choose the right checklist for the change(s) that you're making: ## For Contributors ### Improving Documentation - Run `pnpm prettier-fix` to fix formatting issues before opening the PR. - Read the Docs Contribution Guide to ensure your contribution follows the docs guidelines: https://nextjs.org/docs/community/contribution-guide ### Adding or Updating Examples - The "examples guidelines" are followed from our contributing doc https://github.com/vercel/next.js/blob/canary/contributing/examples/adding-examples.md - Make sure the linting passes by running `pnpm build && pnpm lint`. See https://github.com/vercel/next.js/blob/canary/contributing/repository/linting.md ### Fixing a bug - Related issues linked using `fixes #number` - Tests added. See: https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ### Adding a feature - Implements an existing feature request or RFC. Make sure the feature request has been accepted for implementation before opening a PR. (A discussion must be opened, see https://github.com/vercel/next.js/discussions/new?category=ideas) - Related issues/discussions are linked using `fixes #number` - e2e tests added (https://github.com/vercel/next.js/blob/canary/contributing/core/testing.md#writing-tests-for-nextjs) - Documentation added - Telemetry added. In case of a feature if it's used or not. - Errors have a helpful link attached, see https://github.com/vercel/next.js/blob/canary/contributing.md ## For Maintainers - Minimal description (aim for explaining to someone not on the team to understand the PR) - When linking to a Slack thread, you might want to share details of the conclusion - Link both the Linear (Fixes NEXT-xxx) and the GitHub issues - Add review comments if necessary to explain to the reviewer the logic behind a change ### What? ### Why? ### How? Closes NEXT- Fixes # --> Closes NEXT-2035
2024-01-11 10:23:20 +01:00
// This is a temporary workaround for turbopack starting watching too late.
// So we delay file changes by 500ms to give it some time
// to connect the WebSocket and start watching.
if (process.env.TURBOPACK) {
await waitFor(1000)
}
return browser
}
export { BrowserInterface }