Unverified Commit 88b8d15f authored by Dima Voytenko's avatar Dima Voytenko Committed by GitHub

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.
parent c1fa78bf
...@@ -141,6 +141,7 @@ ...@@ -141,6 +141,7 @@
"@hapi/accept": "5.0.2", "@hapi/accept": "5.0.2",
"@jest/transform": "29.5.0", "@jest/transform": "29.5.0",
"@jest/types": "29.5.0", "@jest/types": "29.5.0",
"@mswjs/interceptors": "0.23.0",
"@napi-rs/cli": "2.16.2", "@napi-rs/cli": "2.16.2",
"@napi-rs/triples": "1.1.0", "@napi-rs/triples": "1.1.0",
"@next/polyfill-module": "13.4.16", "@next/polyfill-module": "13.4.16",
......
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.
{"name":"@mswjs/interceptors","main":"index.js","author":"Artem Zakharchenko","license":"MIT"}
...@@ -94,3 +94,26 @@ test('/product/shoe', async ({ page, msw }) => { ...@@ -94,3 +94,26 @@ test('/product/shoe', async ({ page, msw }) => {
await expect(page.locator('body')).toHaveText(/Boot/) 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/)
})
```
// eslint-disable-next-line import/no-extraneous-dependencies // 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 { NextFixture } from './next-fixture'
import type { NextOptions } from './next-options'
import type { NextWorkerFixture } from './next-worker-fixture' import type { NextWorkerFixture } from './next-worker-fixture'
import { applyNextWorkerFixture } from './next-worker-fixture' import { applyNextWorkerFixture } from './next-worker-fixture'
import { applyNextFixture } from './next-fixture' import { applyNextFixture } from './next-fixture'
...@@ -8,13 +9,28 @@ import { applyNextFixture } from './next-fixture' ...@@ -8,13 +9,28 @@ import { applyNextFixture } from './next-fixture'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
export * from '@playwright/test' export * from '@playwright/test'
export type { NextFixture } export type { NextFixture, NextOptions }
export type { FetchHandlerResult } from '../proxy' export type { FetchHandlerResult } from '../proxy'
export const test = base.extend< export interface NextOptionsConfig {
{ next: NextFixture }, 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 } { _nextWorker: NextWorkerFixture }
>({ >({
nextOptions: [{ fetchLoopback: false }, { option: true }],
_nextWorker: [ _nextWorker: [
// eslint-disable-next-line no-empty-pattern // eslint-disable-next-line no-empty-pattern
async ({}, use) => { async ({}, use) => {
...@@ -23,14 +39,22 @@ export const test = base.extend< ...@@ -23,14 +39,22 @@ export const test = base.extend<
{ scope: 'worker', auto: true }, { scope: 'worker', auto: true },
], ],
next: async ({ _nextWorker, page, extraHTTPHeaders }, use, testInfo) => { next: [
await applyNextFixture(use, { async (
testInfo, { nextOptions, _nextWorker, page, extraHTTPHeaders },
nextWorker: _nextWorker, use,
page, testInfo
extraHTTPHeaders, ) => {
}) await applyNextFixture(use, {
}, testInfo,
nextWorker: _nextWorker,
page,
extraHTTPHeaders,
nextOptions,
})
},
{ auto: true },
],
}) })
export default test export default test
import { test as base } from './index' import { test as base, defineConfig } from './index'
import type { NextFixture } from './next-fixture' import type { NextFixture } from './next-fixture'
import { import {
type RequestHandler, type RequestHandler,
...@@ -15,6 +15,7 @@ export * from 'msw' ...@@ -15,6 +15,7 @@ export * from 'msw'
// eslint-disable-next-line import/no-extraneous-dependencies // eslint-disable-next-line import/no-extraneous-dependencies
export * from '@playwright/test' export * from '@playwright/test'
export type { NextFixture } export type { NextFixture }
export { defineConfig }
export interface MswFixture { export interface MswFixture {
use: (...handlers: RequestHandler[]) => void use: (...handlers: RequestHandler[]) => void
...@@ -24,7 +25,7 @@ export const test = base.extend<{ ...@@ -24,7 +25,7 @@ export const test = base.extend<{
msw: MswFixture msw: MswFixture
mswHandlers: RequestHandler[] mswHandlers: RequestHandler[]
}>({ }>({
mswHandlers: [], mswHandlers: [[], { option: true }],
msw: [ msw: [
async ({ next, mswHandlers }, use) => { async ({ next, mswHandlers }, use) => {
......
import type { Page, TestInfo } from '@playwright/test' import type { Page, TestInfo } from '@playwright/test'
import type { NextWorkerFixture, FetchHandler } from './next-worker-fixture' import type { NextWorkerFixture, FetchHandler } from './next-worker-fixture'
import type { NextOptions } from './next-options'
import type { FetchHandlerResult } from '../proxy'
import { handleRoute } from './page-route' import { handleRoute } from './page-route'
export interface NextFixture { export interface NextFixture {
...@@ -11,12 +13,13 @@ class NextFixtureImpl implements NextFixture { ...@@ -11,12 +13,13 @@ class NextFixtureImpl implements NextFixture {
constructor( constructor(
public testId: string, public testId: string,
private options: NextOptions,
private worker: NextWorkerFixture, private worker: NextWorkerFixture,
private page: Page private page: Page
) { ) {
this.page.route('**', (route) => const handleFetch = this.handleFetch.bind(this)
handleRoute(route, page, this.fetchHandler) worker.onFetch(testId, handleFetch)
) this.page.route('**', (route) => handleRoute(route, page, handleFetch))
} }
teardown(): void { teardown(): void {
...@@ -25,7 +28,20 @@ class NextFixtureImpl implements NextFixture { ...@@ -25,7 +28,20 @@ class NextFixtureImpl implements NextFixture {
onFetch(handler: FetchHandler): void { onFetch(handler: FetchHandler): void {
this.fetchHandler = handler 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( ...@@ -33,17 +49,24 @@ export async function applyNextFixture(
use: (fixture: NextFixture) => Promise<void>, use: (fixture: NextFixture) => Promise<void>,
{ {
testInfo, testInfo,
nextOptions,
nextWorker, nextWorker,
page, page,
extraHTTPHeaders, extraHTTPHeaders,
}: { }: {
testInfo: TestInfo testInfo: TestInfo
nextOptions: NextOptions
nextWorker: NextWorkerFixture nextWorker: NextWorkerFixture
page: Page page: Page
extraHTTPHeaders: Record<string, string> | undefined extraHTTPHeaders: Record<string, string> | undefined
} }
): Promise<void> { ): Promise<void> {
const fixture = new NextFixtureImpl(testInfo.testId, nextWorker, page) const fixture = new NextFixtureImpl(
testInfo.testId,
nextOptions,
nextWorker,
page
)
page.setExtraHTTPHeaders({ page.setExtraHTTPHeaders({
...extraHTTPHeaders, ...extraHTTPHeaders,
'Next-Test-Proxy-Port': String(nextWorker.proxyPort), 'Next-Test-Proxy-Port': String(nextWorker.proxyPort),
......
export interface NextOptions {
fetchLoopback?: boolean
}
...@@ -5,6 +5,7 @@ import type { ...@@ -5,6 +5,7 @@ import type {
ProxyFetchResponse, ProxyFetchResponse,
ProxyResponse, ProxyResponse,
} from './proxy' } from './proxy'
import { ClientRequestInterceptor } from 'next/dist/compiled/@mswjs/interceptors/ClientRequest'
interface TestReqInfo { interface TestReqInfo {
url: string url: string
...@@ -64,9 +65,43 @@ function buildResponse(proxyResponse: ProxyFetchResponse): Response { ...@@ -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() { function interceptFetch() {
const originalFetch = global.fetch const originalFetch = global.fetch
global.fetch = async function testFetch( global.fetch = function testFetch(
input: FetchInputArg, input: FetchInputArg,
init?: FetchInitArg init?: FetchInitArg
): Promise<Response> { ): Promise<Response> {
...@@ -75,36 +110,7 @@ function interceptFetch() { ...@@ -75,36 +110,7 @@ function interceptFetch() {
if (init?.next?.internal) { if (init?.next?.internal) {
return originalFetch(input, init) return originalFetch(input, init)
} }
return handleFetch(originalFetch, new Request(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)
} }
} }
...@@ -112,8 +118,16 @@ export function interceptTestApis(): () => void { ...@@ -112,8 +118,16 @@ export function interceptTestApis(): () => void {
const originalFetch = global.fetch const originalFetch = global.fetch
interceptFetch() interceptFetch()
const clientRequestInterceptor = new ClientRequestInterceptor()
clientRequestInterceptor.on('request', async ({ request }) => {
const response = await handleFetch(originalFetch, request)
request.respondWith(response)
})
clientRequestInterceptor.apply()
// Cleanup. // Cleanup.
return () => { return () => {
clientRequestInterceptor.dispose()
global.fetch = originalFetch global.fetch = originalFetch
} }
} }
......
...@@ -91,6 +91,22 @@ export async function ncc_node_html_parser(task, opts) { ...@@ -91,6 +91,22 @@ export async function ncc_node_html_parser(task, opts) {
.target('src/compiled/node-html-parser') .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() { export async function capsize_metrics() {
const { const {
entireMetricsCollection, entireMetricsCollection,
...@@ -2345,6 +2361,7 @@ export async function ncc(task, opts) { ...@@ -2345,6 +2361,7 @@ export async function ncc(task, opts) {
'ncc_edge_runtime_primitives', 'ncc_edge_runtime_primitives',
'ncc_edge_runtime_ponyfill', 'ncc_edge_runtime_ponyfill',
'ncc_edge_runtime', 'ncc_edge_runtime',
'ncc_mswjs_interceptors',
], ],
opts opts
) )
...@@ -2684,6 +2701,7 @@ export async function minimal_next_server(task) { ...@@ -2684,6 +2701,7 @@ export async function minimal_next_server(task) {
'next/dist/compiled/node-html-parser', 'next/dist/compiled/node-html-parser',
'next/dist/compiled/compression', 'next/dist/compiled/compression',
'next/dist/compiled/jsonwebtoken', 'next/dist/compiled/jsonwebtoken',
'next/dist/compiled/@mswjs/interceptors/ClientRequest',
].reduce((acc, pkg) => { ].reduce((acc, pkg) => {
acc[pkg] = pkg acc[pkg] = pkg
return acc return acc
......
...@@ -41,6 +41,10 @@ declare module 'next/dist/compiled/node-html-parser' { ...@@ -41,6 +41,10 @@ declare module 'next/dist/compiled/node-html-parser' {
export * from '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/undici' {}
declare module 'next/dist/compiled/jest-worker' { declare module 'next/dist/compiled/jest-worker' {
......
...@@ -814,6 +814,9 @@ importers: ...@@ -814,6 +814,9 @@ importers:
'@jest/types': '@jest/types':
specifier: 29.5.0 specifier: 29.5.0
version: 29.5.0 version: 29.5.0
'@mswjs/interceptors':
specifier: 0.23.0
version: 0.23.0
'@napi-rs/cli': '@napi-rs/cli':
specifier: 2.16.2 specifier: 2.16.2
version: 2.16.2 version: 2.16.2
...@@ -6682,6 +6685,18 @@ packages: ...@@ -6682,6 +6685,18 @@ packages:
- supports-color - supports-color
dev: true 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: /@napi-rs/cli@2.16.2:
resolution: {integrity: sha512-U2aZfnr0s9KkXpZlYC0l5WxWCXL7vJUNpCnWMwq3T9GG9rhYAAUM9CTZsi1Z+0iR2LcHbfq9EfMgoqnuTyUjfg==} resolution: {integrity: sha512-U2aZfnr0s9KkXpZlYC0l5WxWCXL7vJUNpCnWMwq3T9GG9rhYAAUM9CTZsi1Z+0iR2LcHbfq9EfMgoqnuTyUjfg==}
engines: {node: '>= 10'} engines: {node: '>= 10'}
...@@ -7162,10 +7177,25 @@ packages: ...@@ -7162,10 +7177,25 @@ packages:
aggregate-error: 3.1.0 aggregate-error: 3.1.0
dev: true 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: /@open-draft/until@1.0.3:
resolution: {integrity: sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==} resolution: {integrity: sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==}
dev: true dev: true
/@open-draft/until@2.1.0:
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
dev: true
/@opentelemetry/api@1.4.1: /@opentelemetry/api@1.4.1:
resolution: {integrity: sha512-O2yRJce1GOc6PAy3QxFM4NzFiWzvScDC1/5ihYBL6BUEVdq0XMWN01sppE+H6bBXbaFYipjwFLEWLg5PaSOThA==} resolution: {integrity: sha512-O2yRJce1GOc6PAy3QxFM4NzFiWzvScDC1/5ihYBL6BUEVdq0XMWN01sppE+H6bBXbaFYipjwFLEWLg5PaSOThA==}
engines: {node: '>=8.0.0'} engines: {node: '>=8.0.0'}
......
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