Skip to content

Commit

Permalink
Test proxy mode: intercept the http and https client APIs (#54014)
Browse files Browse the repository at this point in the history
Followup on the #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.
  • Loading branch information
dvoytenko authored Aug 15, 2023
1 parent c1fa78b commit 88b8d15
Show file tree
Hide file tree
Showing 13 changed files with 202 additions and 50 deletions.
1 change: 1 addition & 0 deletions packages/next/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -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",
Expand Down
Original file line number Diff line number Diff line change
@@ -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.

Large diffs are not rendered by default.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
{"name":"@mswjs/interceptors","main":"index.js","author":"Artem Zakharchenko","license":"MIT"}
23 changes: 23 additions & 0 deletions packages/next/src/experimental/testmode/playwright/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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/)
})
```
48 changes: 36 additions & 12 deletions packages/next/src/experimental/testmode/playwright/index.ts
Original file line number Diff line number Diff line change
@@ -1,20 +1,36 @@
// 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'

// 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) => {
Expand All @@ -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
5 changes: 3 additions & 2 deletions packages/next/src/experimental/testmode/playwright/msw.ts
Original file line number Diff line number Diff line change
@@ -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,
Expand All @@ -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
Expand All @@ -24,7 +25,7 @@ export const test = base.extend<{
msw: MswFixture
mswHandlers: RequestHandler[]
}>({
mswHandlers: [],
mswHandlers: [[], { option: true }],

msw: [
async ({ next, mswHandlers }, use) => {
Expand Down
33 changes: 28 additions & 5 deletions packages/next/src/experimental/testmode/playwright/next-fixture.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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 {
Expand All @@ -25,25 +28,45 @@ 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
}
}

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),
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
export interface NextOptions {
fetchLoopback?: boolean
}
76 changes: 45 additions & 31 deletions packages/next/src/experimental/testmode/server.ts
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import type {
ProxyFetchResponse,
ProxyResponse,
} from './proxy'
import { ClientRequestInterceptor } from 'next/dist/compiled/@mswjs/interceptors/ClientRequest'

interface TestReqInfo {
url: string
Expand Down Expand Up @@ -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> {
Expand All @@ -75,45 +110,24 @@ 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))
}
}

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
}
}
Expand Down
18 changes: 18 additions & 0 deletions packages/next/taskfile.js
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down Expand Up @@ -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
)
Expand Down Expand Up @@ -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
Expand Down
4 changes: 4 additions & 0 deletions packages/next/types/misc.d.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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' {
Expand Down
Loading

0 comments on commit 88b8d15

Please sign in to comment.