Test proxy mode: intercept the http and https client APIs (#54014)
Followup on the https://github.com/vercel/next.js/pull/52520. The enhancements: 1. Both `fetch` and `http(s)` APIs are intercepted in the testmode. 2. The loopback mode that would allow the test-side to use any fetch-mocking library of their choice.
This commit is contained in:
parent
c1fa78bf6c
commit
88b8d15f41
13 changed files with 202 additions and 50 deletions
|
@ -141,6 +141,7 @@
|
|||
"@hapi/accept": "5.0.2",
|
||||
"@jest/transform": "29.5.0",
|
||||
"@jest/types": "29.5.0",
|
||||
"@mswjs/interceptors": "0.23.0",
|
||||
"@napi-rs/cli": "2.16.2",
|
||||
"@napi-rs/triples": "1.1.0",
|
||||
"@next/polyfill-module": "13.4.16",
|
||||
|
|
|
@ -0,0 +1,9 @@
|
|||
MIT License
|
||||
|
||||
Copyright (c) 2018–present Artem Zakharchenko
|
||||
|
||||
Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
|
||||
|
||||
The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
|
||||
|
||||
THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
File diff suppressed because one or more lines are too long
|
@ -0,0 +1 @@
|
|||
{"name":"@mswjs/interceptors","main":"index.js","author":"Artem Zakharchenko","license":"MIT"}
|
|
@ -94,3 +94,26 @@ test('/product/shoe', async ({ page, msw }) => {
|
|||
await expect(page.locator('body')).toHaveText(/Boot/)
|
||||
})
|
||||
```
|
||||
|
||||
### Or use your favorite Fetch mocking library
|
||||
|
||||
The "fetch loopback" mode can be configured in the `playwright.config.ts` or
|
||||
via `test.use()` with a test module. This option loops `fetch()` calls via
|
||||
the `fetch()` of the current test's worker.
|
||||
|
||||
```javascript
|
||||
import { test, expect } from 'next/experimental/testmode/playwright'
|
||||
import { myFetchMocker } from 'my-fetch-mocker'
|
||||
|
||||
test.use({ nextOptions: { fetchLoopback: true } })
|
||||
|
||||
test('/product/shoe', async ({ page, next }) => {
|
||||
myFetchMocker.mock('http://my-db/product/shoe', {
|
||||
title: 'A shoe',
|
||||
})
|
||||
|
||||
await page.goto('/product/shoe')
|
||||
|
||||
await expect(page.locator('body')).toHaveText(/Shoe/)
|
||||
})
|
||||
```
|
||||
|
|
|
@ -1,6 +1,7 @@
|
|||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
import { test as base } from '@playwright/test'
|
||||
import * as base from '@playwright/test'
|
||||
import type { NextFixture } from './next-fixture'
|
||||
import type { NextOptions } from './next-options'
|
||||
import type { NextWorkerFixture } from './next-worker-fixture'
|
||||
import { applyNextWorkerFixture } from './next-worker-fixture'
|
||||
import { applyNextFixture } from './next-fixture'
|
||||
|
@ -8,13 +9,28 @@ import { applyNextFixture } from './next-fixture'
|
|||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
export * from '@playwright/test'
|
||||
|
||||
export type { NextFixture }
|
||||
export type { NextFixture, NextOptions }
|
||||
export type { FetchHandlerResult } from '../proxy'
|
||||
|
||||
export const test = base.extend<
|
||||
{ next: NextFixture },
|
||||
export interface NextOptionsConfig {
|
||||
nextOptions?: NextOptions
|
||||
}
|
||||
|
||||
export function defineConfig<T extends NextOptionsConfig, W>(
|
||||
config: base.PlaywrightTestConfig<T, W>
|
||||
): base.PlaywrightTestConfig<T, W>
|
||||
export function defineConfig<T extends NextOptionsConfig = NextOptionsConfig>(
|
||||
config: base.PlaywrightTestConfig<T>
|
||||
): base.PlaywrightTestConfig<T> {
|
||||
return base.defineConfig<T>(config)
|
||||
}
|
||||
|
||||
export const test = base.test.extend<
|
||||
{ next: NextFixture; nextOptions: NextOptions },
|
||||
{ _nextWorker: NextWorkerFixture }
|
||||
>({
|
||||
nextOptions: [{ fetchLoopback: false }, { option: true }],
|
||||
|
||||
_nextWorker: [
|
||||
// eslint-disable-next-line no-empty-pattern
|
||||
async ({}, use) => {
|
||||
|
@ -23,14 +39,22 @@ export const test = base.extend<
|
|||
{ scope: 'worker', auto: true },
|
||||
],
|
||||
|
||||
next: async ({ _nextWorker, page, extraHTTPHeaders }, use, testInfo) => {
|
||||
await applyNextFixture(use, {
|
||||
testInfo,
|
||||
nextWorker: _nextWorker,
|
||||
page,
|
||||
extraHTTPHeaders,
|
||||
})
|
||||
},
|
||||
next: [
|
||||
async (
|
||||
{ nextOptions, _nextWorker, page, extraHTTPHeaders },
|
||||
use,
|
||||
testInfo
|
||||
) => {
|
||||
await applyNextFixture(use, {
|
||||
testInfo,
|
||||
nextWorker: _nextWorker,
|
||||
page,
|
||||
extraHTTPHeaders,
|
||||
nextOptions,
|
||||
})
|
||||
},
|
||||
{ auto: true },
|
||||
],
|
||||
})
|
||||
|
||||
export default test
|
||||
|
|
|
@ -1,4 +1,4 @@
|
|||
import { test as base } from './index'
|
||||
import { test as base, defineConfig } from './index'
|
||||
import type { NextFixture } from './next-fixture'
|
||||
import {
|
||||
type RequestHandler,
|
||||
|
@ -15,6 +15,7 @@ export * from 'msw'
|
|||
// eslint-disable-next-line import/no-extraneous-dependencies
|
||||
export * from '@playwright/test'
|
||||
export type { NextFixture }
|
||||
export { defineConfig }
|
||||
|
||||
export interface MswFixture {
|
||||
use: (...handlers: RequestHandler[]) => void
|
||||
|
@ -24,7 +25,7 @@ export const test = base.extend<{
|
|||
msw: MswFixture
|
||||
mswHandlers: RequestHandler[]
|
||||
}>({
|
||||
mswHandlers: [],
|
||||
mswHandlers: [[], { option: true }],
|
||||
|
||||
msw: [
|
||||
async ({ next, mswHandlers }, use) => {
|
||||
|
|
|
@ -1,5 +1,7 @@
|
|||
import type { Page, TestInfo } from '@playwright/test'
|
||||
import type { NextWorkerFixture, FetchHandler } from './next-worker-fixture'
|
||||
import type { NextOptions } from './next-options'
|
||||
import type { FetchHandlerResult } from '../proxy'
|
||||
import { handleRoute } from './page-route'
|
||||
|
||||
export interface NextFixture {
|
||||
|
@ -11,12 +13,13 @@ class NextFixtureImpl implements NextFixture {
|
|||
|
||||
constructor(
|
||||
public testId: string,
|
||||
private options: NextOptions,
|
||||
private worker: NextWorkerFixture,
|
||||
private page: Page
|
||||
) {
|
||||
this.page.route('**', (route) =>
|
||||
handleRoute(route, page, this.fetchHandler)
|
||||
)
|
||||
const handleFetch = this.handleFetch.bind(this)
|
||||
worker.onFetch(testId, handleFetch)
|
||||
this.page.route('**', (route) => handleRoute(route, page, handleFetch))
|
||||
}
|
||||
|
||||
teardown(): void {
|
||||
|
@ -25,7 +28,20 @@ class NextFixtureImpl implements NextFixture {
|
|||
|
||||
onFetch(handler: FetchHandler): void {
|
||||
this.fetchHandler = handler
|
||||
this.worker.onFetch(this.testId, handler)
|
||||
}
|
||||
|
||||
private async handleFetch(request: Request): Promise<FetchHandlerResult> {
|
||||
const handler = this.fetchHandler
|
||||
if (handler) {
|
||||
const result = handler(request)
|
||||
if (result) {
|
||||
return result
|
||||
}
|
||||
}
|
||||
if (this.options.fetchLoopback) {
|
||||
return fetch(request)
|
||||
}
|
||||
return undefined
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -33,17 +49,24 @@ export async function applyNextFixture(
|
|||
use: (fixture: NextFixture) => Promise<void>,
|
||||
{
|
||||
testInfo,
|
||||
nextOptions,
|
||||
nextWorker,
|
||||
page,
|
||||
extraHTTPHeaders,
|
||||
}: {
|
||||
testInfo: TestInfo
|
||||
nextOptions: NextOptions
|
||||
nextWorker: NextWorkerFixture
|
||||
page: Page
|
||||
extraHTTPHeaders: Record<string, string> | undefined
|
||||
}
|
||||
): Promise<void> {
|
||||
const fixture = new NextFixtureImpl(testInfo.testId, nextWorker, page)
|
||||
const fixture = new NextFixtureImpl(
|
||||
testInfo.testId,
|
||||
nextOptions,
|
||||
nextWorker,
|
||||
page
|
||||
)
|
||||
page.setExtraHTTPHeaders({
|
||||
...extraHTTPHeaders,
|
||||
'Next-Test-Proxy-Port': String(nextWorker.proxyPort),
|
||||
|
|
|
@ -0,0 +1,3 @@
|
|||
export interface NextOptions {
|
||||
fetchLoopback?: boolean
|
||||
}
|
|
@ -5,6 +5,7 @@ import type {
|
|||
ProxyFetchResponse,
|
||||
ProxyResponse,
|
||||
} from './proxy'
|
||||
import { ClientRequestInterceptor } from 'next/dist/compiled/@mswjs/interceptors/ClientRequest'
|
||||
|
||||
interface TestReqInfo {
|
||||
url: string
|
||||
|
@ -64,9 +65,43 @@ function buildResponse(proxyResponse: ProxyFetchResponse): Response {
|
|||
})
|
||||
}
|
||||
|
||||
async function handleFetch(
|
||||
originalFetch: Fetch,
|
||||
request: Request
|
||||
): Promise<Response> {
|
||||
const testInfo = testStorage.getStore()
|
||||
if (!testInfo) {
|
||||
throw new Error('No test info')
|
||||
}
|
||||
|
||||
const { testData, proxyPort } = testInfo
|
||||
const proxyRequest = await buildProxyRequest(testData, request)
|
||||
|
||||
const resp = await originalFetch(`http://localhost:${proxyPort}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(proxyRequest),
|
||||
})
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Proxy request failed: ${resp.status}`)
|
||||
}
|
||||
|
||||
const proxyResponse = (await resp.json()) as ProxyResponse
|
||||
const { api } = proxyResponse
|
||||
switch (api) {
|
||||
case 'continue':
|
||||
return originalFetch(request)
|
||||
case 'abort':
|
||||
case 'unhandled':
|
||||
throw new Error('Proxy request aborted')
|
||||
default:
|
||||
break
|
||||
}
|
||||
return buildResponse(proxyResponse)
|
||||
}
|
||||
|
||||
function interceptFetch() {
|
||||
const originalFetch = global.fetch
|
||||
global.fetch = async function testFetch(
|
||||
global.fetch = function testFetch(
|
||||
input: FetchInputArg,
|
||||
init?: FetchInitArg
|
||||
): Promise<Response> {
|
||||
|
@ -75,36 +110,7 @@ function interceptFetch() {
|
|||
if (init?.next?.internal) {
|
||||
return originalFetch(input, init)
|
||||
}
|
||||
|
||||
const testInfo = testStorage.getStore()
|
||||
if (!testInfo) {
|
||||
throw new Error('No test info')
|
||||
}
|
||||
|
||||
const { testData, proxyPort } = testInfo
|
||||
const originalRequest = new Request(input, init)
|
||||
const proxyRequest = await buildProxyRequest(testData, originalRequest)
|
||||
|
||||
const resp = await originalFetch(`http://localhost:${proxyPort}`, {
|
||||
method: 'POST',
|
||||
body: JSON.stringify(proxyRequest),
|
||||
})
|
||||
if (!resp.ok) {
|
||||
throw new Error(`Proxy request failed: ${resp.status}`)
|
||||
}
|
||||
|
||||
const proxyResponse = (await resp.json()) as ProxyResponse
|
||||
const { api } = proxyResponse
|
||||
switch (api) {
|
||||
case 'continue':
|
||||
return originalFetch(originalRequest)
|
||||
case 'abort':
|
||||
case 'unhandled':
|
||||
throw new Error('Proxy request aborted')
|
||||
default:
|
||||
break
|
||||
}
|
||||
return buildResponse(proxyResponse)
|
||||
return handleFetch(originalFetch, new Request(input, init))
|
||||
}
|
||||
}
|
||||
|
||||
|
@ -112,8 +118,16 @@ export function interceptTestApis(): () => void {
|
|||
const originalFetch = global.fetch
|
||||
interceptFetch()
|
||||
|
||||
const clientRequestInterceptor = new ClientRequestInterceptor()
|
||||
clientRequestInterceptor.on('request', async ({ request }) => {
|
||||
const response = await handleFetch(originalFetch, request)
|
||||
request.respondWith(response)
|
||||
})
|
||||
clientRequestInterceptor.apply()
|
||||
|
||||
// Cleanup.
|
||||
return () => {
|
||||
clientRequestInterceptor.dispose()
|
||||
global.fetch = originalFetch
|
||||
}
|
||||
}
|
||||
|
|
|
@ -91,6 +91,22 @@ export async function ncc_node_html_parser(task, opts) {
|
|||
.target('src/compiled/node-html-parser')
|
||||
}
|
||||
|
||||
// eslint-disable-next-line camelcase
|
||||
externals['@mswjs/interceptors/ClientRequest'] =
|
||||
'next/dist/compiled/@mswjs/interceptors/ClientRequest'
|
||||
export async function ncc_mswjs_interceptors(task, opts) {
|
||||
await task
|
||||
.source(
|
||||
relative(__dirname, require.resolve('@mswjs/interceptors/ClientRequest'))
|
||||
)
|
||||
.ncc({
|
||||
packageName: '@mswjs/interceptors/ClientRequest',
|
||||
externals,
|
||||
target: 'es5',
|
||||
})
|
||||
.target('src/compiled/@mswjs/interceptors/ClientRequest')
|
||||
}
|
||||
|
||||
export async function capsize_metrics() {
|
||||
const {
|
||||
entireMetricsCollection,
|
||||
|
@ -2345,6 +2361,7 @@ export async function ncc(task, opts) {
|
|||
'ncc_edge_runtime_primitives',
|
||||
'ncc_edge_runtime_ponyfill',
|
||||
'ncc_edge_runtime',
|
||||
'ncc_mswjs_interceptors',
|
||||
],
|
||||
opts
|
||||
)
|
||||
|
@ -2684,6 +2701,7 @@ export async function minimal_next_server(task) {
|
|||
'next/dist/compiled/node-html-parser',
|
||||
'next/dist/compiled/compression',
|
||||
'next/dist/compiled/jsonwebtoken',
|
||||
'next/dist/compiled/@mswjs/interceptors/ClientRequest',
|
||||
].reduce((acc, pkg) => {
|
||||
acc[pkg] = pkg
|
||||
return acc
|
||||
|
|
4
packages/next/types/misc.d.ts
vendored
4
packages/next/types/misc.d.ts
vendored
|
@ -41,6 +41,10 @@ declare module 'next/dist/compiled/node-html-parser' {
|
|||
export * from 'node-html-parser'
|
||||
}
|
||||
|
||||
declare module 'next/dist/compiled/@mswjs/interceptors/ClientRequest' {
|
||||
export * from '@mswjs/interceptors/ClientRequest'
|
||||
}
|
||||
|
||||
declare module 'next/dist/compiled/undici' {}
|
||||
|
||||
declare module 'next/dist/compiled/jest-worker' {
|
||||
|
|
|
@ -814,6 +814,9 @@ importers:
|
|||
'@jest/types':
|
||||
specifier: 29.5.0
|
||||
version: 29.5.0
|
||||
'@mswjs/interceptors':
|
||||
specifier: 0.23.0
|
||||
version: 0.23.0
|
||||
'@napi-rs/cli':
|
||||
specifier: 2.16.2
|
||||
version: 2.16.2
|
||||
|
@ -6682,6 +6685,18 @@ packages:
|
|||
- supports-color
|
||||
dev: true
|
||||
|
||||
/@mswjs/interceptors@0.23.0:
|
||||
resolution: {integrity: sha512-JytvDa7pBbxXvCTXBYQs+0eE6MqxpqH/H4peRNY6zVAlvJ6d/hAWLHAef1D9lWN4zuIigN0VkakGOAUrX7FWLg==}
|
||||
engines: {node: '>=18'}
|
||||
dependencies:
|
||||
'@open-draft/deferred-promise': 2.1.0
|
||||
'@open-draft/logger': 0.3.0
|
||||
'@open-draft/until': 2.1.0
|
||||
headers-polyfill: 3.1.2
|
||||
outvariant: 1.4.0
|
||||
strict-event-emitter: 0.5.0
|
||||
dev: true
|
||||
|
||||
/@napi-rs/cli@2.16.2:
|
||||
resolution: {integrity: sha512-U2aZfnr0s9KkXpZlYC0l5WxWCXL7vJUNpCnWMwq3T9GG9rhYAAUM9CTZsi1Z+0iR2LcHbfq9EfMgoqnuTyUjfg==}
|
||||
engines: {node: '>= 10'}
|
||||
|
@ -7162,10 +7177,25 @@ packages:
|
|||
aggregate-error: 3.1.0
|
||||
dev: true
|
||||
|
||||
/@open-draft/deferred-promise@2.1.0:
|
||||
resolution: {integrity: sha512-Rzd5JrXZX8zErHzgcGyngh4fmEbSHqTETdGj9rXtejlqMIgXFlyKBA7Jn1Xp0Ls0M0Y22+xHcWiEzbmdWl0BOA==}
|
||||
dev: true
|
||||
|
||||
/@open-draft/logger@0.3.0:
|
||||
resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==}
|
||||
dependencies:
|
||||
is-node-process: 1.2.0
|
||||
outvariant: 1.4.0
|
||||
dev: true
|
||||
|
||||
/@open-draft/until@1.0.3:
|
||||
resolution: {integrity: sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==}
|
||||
dev: true
|
||||
|
||||
/@open-draft/until@2.1.0:
|
||||
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
|
||||
dev: true
|
||||
|
||||
/@opentelemetry/api@1.4.1:
|
||||
resolution: {integrity: sha512-O2yRJce1GOc6PAy3QxFM4NzFiWzvScDC1/5ihYBL6BUEVdq0XMWN01sppE+H6bBXbaFYipjwFLEWLg5PaSOThA==}
|
||||
engines: {node: '>=8.0.0'}
|
||||
|
|
Loading…
Reference in a new issue