Skip to content

:hedgehog: PostHog is the leading platform for building self-driving products. Our developer tools – AI observability, analytics, session replay, flags, experiments, error tracking, logs, and more – capture all the context agents need to diagnose problems, uncover opportunities, and ship fixes. Steer it all from Slack, web, desktop, or the MCP.

chore(devex): [MSW v2 split 2/4] Cutover: msw v2, polyfills, and the unhandled-request harness (#61618)

Georges-Antoine Assi2602b1d2a2ba
diff --git a/.github/scripts/verify-storybook-new-stories.sh b/.github/scripts/verify-storybook-new-stories.sh
index dfa5ef0e4492..fe0b6b6f5bff 100755
--- a/.github/scripts/verify-storybook-new-stories.sh
+++ b/.github/scripts/verify-storybook-new-stories.sh
@@ -58,7 +58,19 @@ if [ ${#stories_to_verify[@]} -eq 0 ]; then
exit 0
fi
-echo "Verifying ${#stories_to_verify[@]} file(s) × $REPEAT_COUNT runs:"
+# Scale repeats down for large story sets so the job fits its time budget
+# (runs are sequential with --maxWorkers=1). Small PRs keep full verification;
+# mass refactors degrade to fewer passes instead of timing out.
+file_count=${#stories_to_verify[@]}
+if [ "$file_count" -gt 30 ] && [ "$REPEAT_COUNT" -gt 1 ]; then
+ echo "NOTE: $file_count story files changed — reducing repeat count from $REPEAT_COUNT to 1 to fit the job time budget"
+ REPEAT_COUNT=1
+elif [ "$file_count" -gt 10 ] && [ "$REPEAT_COUNT" -gt 2 ]; then
+ echo "NOTE: $file_count story files changed — reducing repeat count from $REPEAT_COUNT to 2 to fit the job time budget"
+ REPEAT_COUNT=2
+fi
+
+echo "Verifying $file_count file(s) × $REPEAT_COUNT runs:"
printf " %s\n" "${stories_to_verify[@]}"
# Build a regex pattern matching any of the changed story files.
diff --git a/.github/workflows/ci-storybook.yml b/.github/workflows/ci-storybook.yml
index 80e57421c882..ca38a3c9543d 100644
--- a/.github/workflows/ci-storybook.yml
+++ b/.github/workflows/ci-storybook.yml
@@ -433,7 +433,7 @@ jobs:
runs-on: ubuntu-latest
needs: [changes, build-storybook]
if: needs.changes.outputs.frontend == 'true' && github.event_name == 'pull_request'
- timeout-minutes: 30
+ timeout-minutes: 45
container:
image: ghcr.io/posthog/playwright:v1.60.0
env:
diff --git a/common/storybook/.storybook/preview.tsx b/common/storybook/.storybook/preview.tsx
index 2302e79f59cc..6e3594971dbc 100644
--- a/common/storybook/.storybook/preview.tsx
+++ b/common/storybook/.storybook/preview.tsx
@@ -23,8 +23,9 @@ const setupMsw = (): void => {
onUnhandledRequest(request, print) {
// MSW warns on all unhandled requests, but we don't necessarily care
const pathAllowList = ['/images/']
+ const { pathname } = new URL(request.url)
- if (pathAllowList.some((path) => request.url.pathname.startsWith(path))) {
+ if (pathAllowList.some((path) => pathname.startsWith(path))) {
return
}
diff --git a/common/storybook/.storybook/public/mockServiceWorker.js b/common/storybook/.storybook/public/mockServiceWorker.js
index 3265ad745c2f..a4b27eda271f 100644
--- a/common/storybook/.storybook/public/mockServiceWorker.js
+++ b/common/storybook/.storybook/public/mockServiceWorker.js
@@ -2,25 +2,26 @@
/* tslint:disable */
/**
- * Mock Service Worker (0.49.0).
+ * Mock Service Worker.
* @see https://github.com/mswjs/msw
* - Please do NOT modify this file.
- * - Please do NOT serve this file on production.
*/
-const INTEGRITY_CHECKSUM = '3d6b9f06410d179a7f7404d4bf4c3c70'
+const PACKAGE_VERSION = '2.14.6'
+const INTEGRITY_CHECKSUM = '4db4a41e972cec1b64cc569c66952d82'
+const IS_MOCKED_RESPONSE = Symbol('isMockedResponse')
const activeClientIds = new Set()
-self.addEventListener('install', function () {
+addEventListener('install', function () {
self.skipWaiting()
})
-self.addEventListener('activate', function (event) {
+addEventListener('activate', function (event) {
event.waitUntil(self.clients.claim())
})
-self.addEventListener('message', async function (event) {
- const clientId = event.source.id
+addEventListener('message', async function (event) {
+ const clientId = Reflect.get(event.source || {}, 'id')
if (!clientId || !self.clients) {
return
@@ -47,7 +48,10 @@ self.addEventListener('message', async function (event) {
case 'INTEGRITY_CHECK_REQUEST': {
sendToClient(client, {
type: 'INTEGRITY_CHECK_RESPONSE',
- payload: INTEGRITY_CHECKSUM,
+ payload: {
+ packageVersion: PACKAGE_VERSION,
+ checksum: INTEGRITY_CHECKSUM,
+ },
})
break
}
@@ -57,16 +61,16 @@ self.addEventListener('message', async function (event) {
sendToClient(client, {
type: 'MOCKING_ENABLED',
- payload: true,
+ payload: {
+ client: {
+ id: client.id,
+ frameType: client.frameType,
+ },
+ },
})
break
}
- case 'MOCK_DEACTIVATE': {
- activeClientIds.delete(clientId)
- break
- }
-
case 'CLIENT_CLOSED': {
activeClientIds.delete(clientId)
@@ -84,95 +88,91 @@ self.addEventListener('message', async function (event) {
}
})
-self.addEventListener('fetch', function (event) {
- const { request } = event
- const accept = request.headers.get('accept') || ''
-
- // Bypass server-sent events.
- if (accept.includes('text/event-stream')) {
- return
- }
+addEventListener('fetch', function (event) {
+ const requestInterceptedAt = Date.now()
// Bypass navigation requests.
- if (request.mode === 'navigate') {
+ if (event.request.mode === 'navigate') {
return
}
// Opening the DevTools triggers the "only-if-cached" request
// that cannot be handled by the worker. Bypass such requests.
- if (request.cache === 'only-if-cached' && request.mode !== 'same-origin') {
+ if (event.request.cache === 'only-if-cached' && event.request.mode !== 'same-origin') {
return
}
// Bypass all requests when there are no active clients.
// Prevents the self-unregistered worked from handling requests
- // after it's been deleted (still remains active until the next reload).
+ // after it's been terminated (still remains active until the next reload).
if (activeClientIds.size === 0) {
return
}
- // Generate unique request ID.
- const requestId = Math.random().toString(16).slice(2)
-
- event.respondWith(
- handleRequest(event, requestId).catch((error) => {
- if (error.name === 'NetworkError') {
- console.warn(
- '[MSW] Successfully emulated a network error for the "%s %s" request.',
- request.method,
- request.url
- )
- return
- }
-
- // At this point, any exception indicates an issue with the original request/response.
- console.error(
- `\
-[MSW] Caught an exception from the "%s %s" request (%s). This is probably not a problem with Mock Service Worker. There is likely an additional logging output above.`,
- request.method,
- request.url,
- `${error.name}: ${error.message}`
- )
- })
- )
+ const requestId = crypto.randomUUID()
+ event.respondWith(handleRequest(event, requestId, requestInterceptedAt))
})
-async function handleRequest(event, requestId) {
+/**
+ * @param {FetchEvent} event
+ * @param {string} requestId
+ * @param {number} requestInterceptedAt
+ */
+async function handleRequest(event, requestId, requestInterceptedAt) {
const client = await resolveMainClient(event)
- const response = await getResponse(event, client, requestId)
+ const requestCloneForEvents = event.request.clone()
+ const response = await getResponse(event, client, requestId, requestInterceptedAt)
// Send back the response clone for the "response:*" life-cycle events.
// Ensure MSW is active and ready to handle the message, otherwise
// this message will pend indefinitely.
if (client && activeClientIds.has(client.id)) {
- ;(async function () {
- const clonedResponse = response.clone()
- sendToClient(client, {
+ const serializedRequest = await serializeRequest(requestCloneForEvents)
+
+ // Clone the response so both the client and the library could consume it.
+ const responseClone = response.clone()
+
+ sendToClient(
+ client,
+ {
type: 'RESPONSE',
payload: {
- requestId,
- type: clonedResponse.type,
- ok: clonedResponse.ok,
- status: clonedResponse.status,
- statusText: clonedResponse.statusText,
- body: clonedResponse.body === null ? null : await clonedResponse.text(),
- headers: Object.fromEntries(clonedResponse.headers.entries()),
- redirected: clonedResponse.redirected,
+ isMockedResponse: IS_MOCKED_RESPONSE in response,
+ request: {
+ id: requestId,
+ ...serializedRequest,
+ },
+ response: {
+ type: responseClone.type,
+ status: responseClone.status,
+ statusText: responseClone.statusText,
+ headers: Object.fromEntries(responseClone.headers.entries()),
+ body: responseClone.body,
+ },
},
- })
- })()
+ },
+ responseClone.body ? [serializedRequest.body, responseClone.body] : []
+ )
}
return response
}
-// Resolve the main client for the given event.
-// Client that issues a request doesn't necessarily equal the client
-// that registered the worker. It's with the latter the worker should
-// communicate with during the response resolving phase.
+/**
+ * Resolve the main client for the given event.
+ * Client that issues a request doesn't necessarily equal the client
+ * that registered the worker. It's with the latter the worker should
+ * communicate with during the response resolving phase.
+ * @param {FetchEvent} event
+ * @returns {Promise<Client | undefined>}
+ */
async function resolveMainClient(event) {
const client = await self.clients.get(event.clientId)
+ if (activeClientIds.has(event.clientId)) {
+ return client
+ }
+
if (client?.frameType === 'top-level') {
return client
}
@@ -193,22 +193,39 @@ async function resolveMainClient(event) {
})
}
-async function getResponse(event, client, requestId) {
- const { request } = event
- const clonedRequest = request.clone()
+/**
+ * @param {FetchEvent} event
+ * @param {Client | undefined} client
+ * @param {string} requestId
+ * @param {number} requestInterceptedAt
+ * @returns {Promise<Response>}
+ */
+async function getResponse(event, client, requestId, requestInterceptedAt) {
+ // Clone the request because it might've been already used
+ // (i.e. its body has been read and sent to the client).
+ const requestClone = event.request.clone()
function passthrough() {
- // Clone the request because it might've been already used
- // (i.e. its body has been read and sent to the client).
- const headers = Object.fromEntries(clonedRequest.headers.entries())
-
- // Remove MSW-specific request headers so the bypassed requests
- // comply with the server's CORS preflight check.
- // Operate with the headers as an object because request "Headers"
- // are immutable.
- delete headers['x-msw-bypass']
+ // Cast the request headers to a new Headers instance
+ // so the headers can be manipulated with.
+ const headers = new Headers(requestClone.headers)
+
+ // Remove the "accept" header value that marked this request as passthrough.
+ // This prevents request alteration and also keeps it compliant with the
+ // user-defined CORS policies.
+ const acceptHeader = headers.get('accept')
+ if (acceptHeader) {
+ const values = acceptHeader.split(',').map((value) => value.trim())
+ const filteredValues = values.filter((value) => value !== 'msw/passthrough')
+
+ if (filteredValues.length > 0) {
+ headers.set('accept', filteredValues.join(', '))
+ } else {
+ headers.delete('accept')
+ }
+ }
- return fetch(clonedRequest, { headers })
+ return fetch(requestClone, { headers })
}
// Bypass mocking when the client is not active.
@@ -224,57 +241,41 @@ async function getResponse(event, client, requestId) {
return passthrough()
}
- // Bypass requests with the explicit bypass header.
- // Such requests can be issued by "ctx.fetch()".
- if (request.headers.get('x-msw-bypass') === 'true') {
- return passthrough()
- }
-
// Notify the client that a request has been intercepted.
- const clientMessage = await sendToClient(client, {
- type: 'REQUEST',
- payload: {
- id: requestId,
- url: request.url,
- method: request.method,
- headers: Object.fromEntries(request.headers.entries()),
- cache: request.cache,
- mode: request.mode,
- credentials: request.credentials,
- destination: request.destination,
- integrity: request.integrity,
- redirect: request.redirect,
- referrer: request.referrer,
- referrerPolicy: request.referrerPolicy,
- body: await request.text(),
- bodyUsed: request.bodyUsed,
- keepalive: request.keepalive,
+ const serializedRequest = await serializeRequest(event.request)
+ const clientMessage = await sendToClient(
+ client,
+ {
+ type: 'REQUEST',
+ payload: {
+ id: requestId,
+ interceptedAt: requestInterceptedAt,
+ ...serializedRequest,
+ },
},
- })
+ [serializedRequest.body]
+ )
switch (clientMessage.type) {
case 'MOCK_RESPONSE': {
return respondWithMock(clientMessage.data)
}
- case 'MOCK_NOT_FOUND': {
+ case 'PASSTHROUGH': {
return passthrough()
}
-
- case 'NETWORK_ERROR': {
- const { name, message } = clientMessage.data
- const networkError = new Error(message)
- networkError.name = name
-
- // Rejecting a "respondWith" promise emulates a network error.
- throw networkError
- }
}
return passthrough()
}
-function sendToClient(client, message) {
+/**
+ * @param {Client} client
+ * @param {any} message
+ * @param {Array<Transferable>} transferrables
+ * @returns {Promise<any>}
+ */
+function sendToClient(client, message, transferrables = []) {
return new Promise((resolve, reject) => {
const channel = new MessageChannel()
@@ -286,17 +287,50 @@ function sendToClient(client, message) {
resolve(event.data)
}
- client.postMessage(message, [channel.port2])
+ client.postMessage(message, [channel.port2, ...transferrables.filter(Boolean)])
})
}
-function sleep(timeMs) {
- return new Promise((resolve) => {
- setTimeout(resolve, timeMs)
+/**
+ * @param {Response} response
+ * @returns {Response}
+ */
+function respondWithMock(response) {
+ // Setting response status code to 0 is a no-op.
+ // However, when responding with a "Response.error()", the produced Response
+ // instance will have status code set to 0. Since it's not possible to create
+ // a Response instance with status code 0, handle that use-case separately.
+ if (response.status === 0) {
+ return Response.error()
+ }
+
+ const mockedResponse = new Response(response.body, response)
+
+ Reflect.defineProperty(mockedResponse, IS_MOCKED_RESPONSE, {
+ value: true,
+ enumerable: true,
})
+
+ return mockedResponse
}
-async function respondWithMock(response) {
- await sleep(response.delay)
- return new Response(response.body, response)
+/**
+ * @param {Request} request
+ */
+async function serializeRequest(request) {
+ return {
+ url: request.url,
+ mode: request.mode,
+ method: request.method,
+ headers: Object.fromEntries(request.headers.entries()),
+ cache: request.cache,
+ credentials: request.credentials,
+ destination: request.destination,
+ integrity: request.integrity,
+ redirect: request.redirect,
+ referrer: request.referrer,
+ referrerPolicy: request.referrerPolicy,
+ body: await request.arrayBuffer(),
+ keepalive: request.keepalive,
+ }
}
diff --git a/frontend/jest.config.ts b/frontend/jest.config.ts
index 24b3d3705bcd..0a9e0bce96fe 100644
--- a/frontend/jest.config.ts
+++ b/frontend/jest.config.ts
@@ -61,6 +61,17 @@ const esmModules = [
'longest-streak',
'markdown-table',
'@mathjax/src',
+ // MSW v2 and its dependencies ship ESM that resolves under the forced `default` export condition
+ 'msw',
+ '@mswjs/.*',
+ '@bundled-es-modules/.*',
+ '@open-draft/.*',
+ 'rettime',
+ 'strict-event-emitter',
+ 'headers-polyfill',
+ 'outvariant',
+ 'until-async',
+ 'is-node-process',
// yaml's browser entry (used under the jsdom env) is ESM and re-exports its CJS dist
'yaml/browser',
]
@@ -115,6 +126,14 @@ const config: Config = {
// Make calling deprecated APIs throw helpful error messages
// errorOnDeprecated: false,
+ // Faking queueMicrotask starves the web-streams pump that MSW v2 response bodies ride on:
+ // each pump microtask lands in the fake queue and respawns the next one, so any
+ // advanceTimersByTimeAsync allocates unboundedly until the worker OOMs. Keep microtasks real.
+ // Merged into per-test `jest.useFakeTimers({...})` configs unless they pass their own doNotFake.
+ fakeTimers: {
+ doNotFake: ['queueMicrotask'],
+ },
+
// Force coverage collection from ignored files using an array of glob patterns
// forceCoverageMatch: [],
@@ -207,8 +226,9 @@ const config: Config = {
// Reset the module registry before running each individual test
// resetModules: false,
- // A path to a custom resolver
- // resolver: undefined,
+ // A path to a custom resolver — strips the `browser` export condition for the MSW ecosystem
+ // (whose Node subpaths are null under `browser`) without affecting any other package's resolution.
+ resolver: '<rootDir>/jest.resolver.js',
// Automatically restore mock state between every test
// restoreMocks: false,
@@ -223,7 +243,7 @@ const config: Config = {
// runner: "jest-runner",
// The paths to modules that run some code to configure or set up the testing environment before each test
- setupFiles: ['<rootDir>/jest.setup.ts', 'fake-indexeddb/auto'],
+ setupFiles: ['<rootDir>/jest.polyfills.js', '<rootDir>/jest.setup.ts', 'fake-indexeddb/auto'],
// A list of paths to modules that run some code to configure or set up the testing framework before each test
setupFilesAfterEnv: ['<rootDir>/jest.setupAfterEnv.ts', '<rootDir>/src/mocks/jest.ts'],
@@ -250,7 +270,12 @@ const config: Config = {
// ],
// An array of regexp pattern strings that are matched against all test paths, matched tests are skipped
- testPathIgnorePatterns: ['/node_modules/', '/services/mcp/', '/products/[^/]+/frontend/e2e/', '/products/visual_review/cli/'],
+ testPathIgnorePatterns: [
+ '/node_modules/',
+ '/services/mcp/',
+ '/products/[^/]+/frontend/e2e/',
+ '/products/visual_review/cli/',
+ ],
// The regexp pattern or array of patterns that Jest uses to detect test files
// testRegex: [],
@@ -269,7 +294,8 @@ const config: Config = {
// A map from regular expressions to paths to transformers
transform: {
- '\\.[jt]sx?$': '@sucrase/jest-plugin',
+ // Include .mjs/.cjs so ESM dependencies allowed through transformIgnorePatterns (e.g. MSW's) are transpiled.
+ '\\.[cm]?[jt]sx?$': '@sucrase/jest-plugin',
'\\.yaml$': '<rootDir>/src/test/yamlRawTransformer.js',
},
diff --git a/frontend/jest.polyfills.js b/frontend/jest.polyfills.js
new file mode 100644
index 000000000000..6508ce71b1be
--- /dev/null
+++ b/frontend/jest.polyfills.js
@@ -0,0 +1,81 @@
+// MSW v2 intercepts requests via spec-compliant fetch primitives that jsdom does
+// not provide. Source them from undici (jsdom otherwise clobbers the Node globals)
+// and assign before the test framework boots, so this must run first in setupFiles.
+/* eslint-disable @typescript-eslint/no-require-imports */
+const { TextEncoder, TextDecoder } = require('node:util')
+const { ReadableStream, WritableStream, TransformStream } = require('node:stream/web')
+const { Blob, File } = require('node:buffer')
+const { BroadcastChannel } = require('node:worker_threads')
+
+// configurable so @mswjs/interceptors can wrap Request/Response when the server starts.
+const define = (props) =>
+ Object.defineProperties(
+ globalThis,
+ Object.fromEntries(
+ Object.entries(props).map(([key, value]) => [key, { value, writable: true, configurable: true }])
+ )
+ )
+
+// undici references TextEncoder/streams at module-eval time, so define these first.
+define({
+ TextEncoder,
+ TextDecoder,
+ ReadableStream,
+ WritableStream,
+ TransformStream,
+ Blob,
+ File,
+ BroadcastChannel,
+})
+
+// jsdom's setTimeout returns a number, but undici's internal fast-timer calls `.refresh()`/`.unref()`
+// on the returned handle. Wrap jsdom's timer (so it still tears down with the window — Node's would
+// leak past teardown) and expose a refreshable handle. Jest fake timers override these per-test.
+const jsdomSetTimeout = globalThis.setTimeout
+const jsdomClearTimeout = globalThis.clearTimeout
+const handleId = (handle) => (handle && typeof handle === 'object' ? handle.__id : handle)
+define({
+ setTimeout: (callback, delay, ...args) => {
+ const handle = {
+ refresh() {
+ jsdomClearTimeout(this.__id)
+ this.__id = jsdomSetTimeout(callback, delay, ...args)
+ return this
+ },
+ unref() {
+ return this
+ },
+ ref() {
+ return this
+ },
+ [Symbol.toPrimitive]() {
+ return this.__id
+ },
+ }
+ handle.__id = jsdomSetTimeout(callback, delay, ...args)
+ return handle
+ },
+ clearTimeout: (handle) => jsdomClearTimeout(handleId(handle)),
+})
+
+// jsdom lacks setImmediate/clearImmediate, which undici needs. Node's setImmediate fires on the
+// libuv check phase, which keeps running after jsdom tears down the window — and React 18's
+// scheduler prefers setImmediate for performWorkUntilDeadline, so its render work lands
+// post-teardown and throws "The `document` global ... is not defined anymore", crashing the whole
+// file. Route it through the jsdom-bound setTimeout above so it tears down with the window instead.
+define({
+ setImmediate: (callback, ...args) => globalThis.setTimeout(callback, 0, ...args),
+ clearImmediate: (handle) => globalThis.clearTimeout(handle),
+})
+
+// undici's fetch calls performance.markResourceTiming, which jsdom's performance lacks.
+if (typeof globalThis.performance?.markResourceTiming !== 'function') {
+ if (!globalThis.performance) {
+ globalThis.performance = require('node:perf_hooks').performance
+ }
+ globalThis.performance.markResourceTiming = () => {}
+}
+
+const { fetch, Request, Response, Headers, FormData } = require('undici')
+
+define({ fetch, Request, Response, Headers, FormData })
diff --git a/frontend/jest.resolver.js b/frontend/jest.resolver.js
new file mode 100644
index 000000000000..e570f5425410
--- /dev/null
+++ b/frontend/jest.resolver.js
@@ -0,0 +1,12 @@
+// MSW v2 and its dependencies mark their Node-targeted subpath exports as null under the `browser`
+// export condition that Jest's jsdom environment activates, which breaks resolution of `msw/node`
+// and transitive deps like `@mswjs/interceptors/ClientRequest`. Resolve just the MSW ecosystem with
+// Node conditions; every other package keeps jsdom's default (browser) resolution untouched.
+const MSW_ECOSYSTEM =
+ /^(msw($|\/)|@mswjs\/|@bundled-es-modules\/|@open-draft\/|@inquirer\/|rettime$|strict-event-emitter$|headers-polyfill$|outvariant$|until-async$|is-node-process$)/
+
+module.exports = (request, options) =>
+ options.defaultResolver(request, {
+ ...options,
+ conditions: MSW_ECOSYSTEM.test(request) ? ['node', 'require', 'default'] : options.conditions,
+ })
diff --git a/frontend/jest.setup.ts b/frontend/jest.setup.ts
index 7a61e6f9e222..17b8747a1504 100644
--- a/frontend/jest.setup.ts
+++ b/frontend/jest.setup.ts
@@ -1,5 +1,4 @@
import 'jest-canvas-mock'
-import 'whatwg-fetch'
import { configure } from '@testing-library/react'
import { TextDecoder, TextEncoder } from 'util'
diff --git a/frontend/package.json b/frontend/package.json
index 2260869c0d7e..95d334cc6e85 100644
--- a/frontend/package.json
+++ b/frontend/package.json
@@ -321,7 +321,7 @@
"less": "^3.12.2",
"lint-staged": "catalog:",
"mockdate": "^3.0.5",
- "msw": "^0.49.0",
+ "msw": "^2.14.6",
"safe-stable-stringify": "^2.4.3",
"sass": "^1.26.2",
"stream-browserify": "^3.0.0",
@@ -333,8 +333,8 @@
"ts-node": "^10.9.1",
"tsconfig-paths": "^4.2.0",
"typescript": "catalog:",
- "vite": "^7.3.3",
- "whatwg-fetch": "^3.6.2"
+ "undici": "^6.25.0",
+ "vite": "^7.3.3"
},
"optionalDependencies": {
"fsevents": "^2.3.2"
diff --git a/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx b/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx
index cae6ff97c9b4..2989ca42bb29 100644
--- a/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx
+++ b/frontend/src/lib/components/ActivityLog/ActivityLog.stories.tsx
@@ -35,26 +35,14 @@ const meta: Meta<ActivityLogProps> = {
},
},
],
- '/api/projects/:team/feature_flags/6/activity': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ results: [] }),
- ],
- '/api/projects/:team/feature_flags/7/activity': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ results: featureFlagsActivityResponseJson }),
- ],
- '/api/environments/:team_id/insights/activity': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ results: insightsActivityResponseJson }),
- ],
- '/api/person/:id/activity': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ results: personActivityResponseJson }),
- ],
- '/api/projects/:id/activity': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ results: teamActivityResponseJson }),
+ '/api/projects/:team/feature_flags/6/activity': () => [200, { results: [] }],
+ '/api/projects/:team/feature_flags/7/activity': () => [
+ 200,
+ { results: featureFlagsActivityResponseJson },
],
+ '/api/environments/:team_id/insights/activity': () => [200, { results: insightsActivityResponseJson }],
+ '/api/person/:id/activity': () => [200, { results: personActivityResponseJson }],
+ '/api/projects/:id/activity': () => [200, { results: teamActivityResponseJson }],
},
}),
],
diff --git a/frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx b/frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx
index 8111492a5416..0739068dcce2 100644
--- a/frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx
+++ b/frontend/src/lib/components/ActivityLog/activityLogLogic.test.tsx
@@ -90,8 +90,8 @@ describe('the activity log logic', () => {
beforeEach(() => {
useMocks({
get: {
- [`/api/projects/${MOCK_TEAM_ID}/feature_flags/7/activity/`]: (req) => {
- const isOnPageFour = req.url.searchParams.get('page') === '4'
+ [`/api/projects/${MOCK_TEAM_ID}/feature_flags/7/activity/`]: ({ request }) => {
+ const isOnPageFour = new URL(request.url).searchParams.get('page') === '4'
return [
200,
diff --git a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
index eb59403931d8..95a304527644 100644
--- a/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
+++ b/frontend/src/lib/components/AddToDashboard/addToDashboardModalLogic.test.ts
@@ -94,8 +94,8 @@ describe('addToDashboardModalLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request }) => {
+ const payload = (await request.json()) as Record<string, any>
return [200, { ...MOCK_INSIGHT, ...payload }]
},
},
@@ -162,8 +162,8 @@ describe('addToDashboardModalLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request }) => {
+ const payload = (await request.json()) as Record<string, any>
return [200, { ...insightOnlyOnDash2, ...payload }]
},
},
@@ -215,8 +215,8 @@ describe('addToDashboardModalLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request }) => {
+ const payload = (await request.json()) as Record<string, any>
return [200, { ...insightOnlyOnDash2, ...payload }]
},
},
@@ -267,8 +267,8 @@ describe('addToDashboardModalLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request }) => {
+ const payload = (await request.json()) as Record<string, any>
return [200, { ...insightOnlyOnDash2, ...payload }]
},
},
diff --git a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
index beec302a0688..7636c77dd58f 100644
--- a/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
+++ b/frontend/src/lib/components/AuthorizedUrlList/authorizedUrlListLogic.test.ts
@@ -27,8 +27,8 @@ describe('the authorized urls list logic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/environments/:team_id/insights/trend/': (req) => {
- if (JSON.parse(req.url.searchParams.get('events') || '[]')?.[0]?.throw) {
+ '/api/environments/:team_id/insights/trend/': ({ request }) => {
+ if (JSON.parse(new URL(request.url).searchParams.get('events') || '[]')?.[0]?.throw) {
return [500, { status: 0, detail: 'error from the API' }]
}
return [200, { result: ['result from api'] }]
diff --git a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.test.ts b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.test.ts
index 62550c581a99..e555a8d0cd12 100644
--- a/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.test.ts
+++ b/frontend/src/lib/components/IngestionControls/triggers/triggerGroups/replayTriggersV2Logic.test.ts
@@ -13,7 +13,10 @@ describe('replayTriggersV2Logic', () => {
beforeEach(() => {
useMocks({
patch: {
- 'api/environments/:id': (req) => [200, { id: 1, ...(req.body as Record<string, any>) }],
+ 'api/environments/:id': async ({ request }) => [
+ 200,
+ { id: 1, ...((await request.json()) as Record<string, any>) },
+ ],
},
})
initKeaTests()
diff --git a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
index 58f2fe670afa..6055a930ed03 100644
--- a/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
+++ b/frontend/src/lib/components/MarkdownNotebook/MarkdownNotebook.test.ts
@@ -2307,14 +2307,10 @@ Tail paragraph`
expect(anchorClick).toHaveBeenCalledTimes(1)
expect(createObjectURL).toHaveBeenCalledTimes(1)
+ // The global Blob is node:buffer's (see jest.polyfills.js), which jsdom's
+ // FileReader rejects — but it has .text(), which jsdom's Blob lacked.
const blob = createObjectURL.mock.calls[0][0]
- // jsdom's Blob has no .text()
- const blobText = await new Promise<string>((resolve, reject) => {
- const reader = new FileReader()
- reader.onload = () => resolve(String(reader.result))
- reader.onerror = () => reject(reader.error as Error)
- reader.readAsText(blob)
- })
+ const blobText = await blob.text()
const entries = blobText
.trim()
.split('\n')
diff --git a/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.test.tsx b/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.test.tsx
index 438c38696358..f2ddb9e0961d 100644
--- a/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.test.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/DistinctIdSelect.test.tsx
@@ -44,8 +44,8 @@ describe('DistinctIdSelect', () => {
'/api/environments/:team/persons/': { results: MOCK_PERSONS, next: null },
},
post: {
- '/api/environments/:team/persons/batch_by_distinct_ids/': async (req: any) => {
- const body = (await req.json()) as { distinct_ids?: string[] }
+ '/api/environments/:team/persons/batch_by_distinct_ids/': async ({ request }) => {
+ const body = (await request.json()) as { distinct_ids?: string[] }
const distinctIds = body.distinct_ids ?? []
const results: Record<string, any> = {}
for (const person of MOCK_PERSONS) {
diff --git a/frontend/src/lib/components/PropertyFilters/components/GroupKeyFilterTooltip.test.tsx b/frontend/src/lib/components/PropertyFilters/components/GroupKeyFilterTooltip.test.tsx
index 1456665d8e0d..2bdae5b44469 100644
--- a/frontend/src/lib/components/PropertyFilters/components/GroupKeyFilterTooltip.test.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/GroupKeyFilterTooltip.test.tsx
@@ -35,8 +35,8 @@ describe('GroupKeyFilterTooltip', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/environments/:team/groups/find': (req: any) => {
- const groupKey = req.url.searchParams.get('group_key')
+ '/api/environments/:team/groups/find': ({ request }) => {
+ const groupKey = new URL(request.url).searchParams.get('group_key')
const group = MOCK_GROUPS.find((g) => g.group_key === groupKey)
return group ? [200, group] : [404, { detail: 'Not found' }]
},
@@ -86,9 +86,9 @@ describe('GroupKeyFilterTooltip', () => {
let findCalls = 0
useMocks({
get: {
- '/api/environments/:team/groups/find': (req: any) => {
+ '/api/environments/:team/groups/find': ({ request }) => {
findCalls++
- const groupKey = req.url.searchParams.get('group_key')
+ const groupKey = new URL(request.url).searchParams.get('group_key')
const group = MOCK_GROUPS.find((g) => g.group_key === groupKey)
return group ? [200, group] : [404, { detail: 'Not found' }]
},
diff --git a/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.test.tsx b/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.test.tsx
index f16bf870ce9f..f58f1fdaf1c1 100644
--- a/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.test.tsx
+++ b/frontend/src/lib/components/PropertyFilters/components/GroupKeySelect.test.tsx
@@ -49,8 +49,8 @@ describe('GroupKeySelect', () => {
results: MOCK_GROUPS,
next: null,
},
- '/api/environments/:team/groups/find': (req: any) => {
- const groupKey = req.url.searchParams.get('group_key')
+ '/api/environments/:team/groups/find': ({ request }) => {
+ const groupKey = new URL(request.url).searchParams.get('group_key')
const group = [...MOCK_GROUPS, FIND_ONLY_GROUP].find((g) => g.group_key === groupKey)
return group ? [200, group] : [404, { detail: 'Not found' }]
},
diff --git a/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.test.ts b/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.test.ts
index 50a3d790cac8..e05394a6d54e 100644
--- a/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.test.ts
+++ b/frontend/src/lib/components/SceneDashboardChoice/sceneDashboardChoiceModalLogic.test.ts
@@ -20,8 +20,8 @@ describe('sceneDashboardChoiceModalLogic', () => {
'/api/projects/@current': () => MOCK_DEFAULT_TEAM,
},
post: {
- '/api/users/@me/scene_personalisation': (req) => {
- const data = req.body as any
+ '/api/users/@me/scene_personalisation': async ({ request }) => {
+ const data = (await request.json()) as any
return [
200,
{
@@ -35,8 +35,8 @@ describe('sceneDashboardChoiceModalLogic', () => {
},
},
patch: {
- '/api/environments/:team': (req) => {
- const data = req.body as any
+ '/api/environments/:team': async ({ request }) => {
+ const data = (await request.json()) as any
return [
200,
{
diff --git a/frontend/src/lib/components/Search/Search.stories.tsx b/frontend/src/lib/components/Search/Search.stories.tsx
index 4dd121595eae..f83155a83a6d 100644
--- a/frontend/src/lib/components/Search/Search.stories.tsx
+++ b/frontend/src/lib/components/Search/Search.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { delay, HttpResponse } from 'msw'
import { useStorybookMocks } from '~/mocks/browser'
import { EMPTY_PAGINATED_RESPONSE, toPaginatedResponse } from '~/mocks/handlers'
@@ -188,8 +189,9 @@ export const Default: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/file_system/': (_req, res, ctx) => {
- return res(ctx.delay(10), ctx.json(toPaginatedResponse(MOCK_RECENTS)))
+ '/api/environments/:team_id/file_system/': async () => {
+ await delay(10)
+ return HttpResponse.json(toPaginatedResponse(MOCK_RECENTS))
},
'/api/environments/:team_id/search/': () => [200, { results: [], counts: {} }],
...SHARED_MOCKS,
@@ -216,11 +218,13 @@ export const ProductRecentsAndStarred: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/file_system/': (_req, res, ctx) => {
- return res(ctx.delay(10), ctx.json(toPaginatedResponse(MOCK_PRODUCT_RECENTS)))
+ '/api/environments/:team_id/file_system/': async () => {
+ await delay(10)
+ return HttpResponse.json(toPaginatedResponse(MOCK_PRODUCT_RECENTS))
},
- '/api/environments/:team_id/file_system_shortcut/': (_req, res, ctx) => {
- return res(ctx.delay(10), ctx.json(toPaginatedResponse(MOCK_PRODUCT_STARRED)))
+ '/api/environments/:team_id/file_system_shortcut/': async () => {
+ await delay(10)
+ return HttpResponse.json(toPaginatedResponse(MOCK_PRODUCT_STARRED))
},
'/api/environments/:team_id/search/': () => [200, { results: [], counts: {} }],
...SHARED_MOCKS,
@@ -251,11 +255,13 @@ export const Searching: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/file_system/': (_req, res, ctx) => {
- return res(ctx.delay(10), ctx.json(toPaginatedResponse(MOCK_RECENTS)))
+ '/api/environments/:team_id/file_system/': async () => {
+ await delay(10)
+ return HttpResponse.json(toPaginatedResponse(MOCK_RECENTS))
},
- '/api/environments/:team_id/search/': (_req, res, ctx) => {
- return res(ctx.delay(100), ctx.json(MOCK_SEARCH_RESULTS))
+ '/api/environments/:team_id/search/': async () => {
+ await delay(100)
+ return HttpResponse.json(MOCK_SEARCH_RESULTS)
},
...SHARED_MOCKS,
},
diff --git a/frontend/src/lib/components/Sharing/SharingModal.stories.tsx b/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
index 5cdd5e89e3f5..7e839bed04e6 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.stories.tsx
@@ -7,6 +7,7 @@ import { dashboardLogic } from 'scenes/dashboard/dashboardLogic'
import { useStorybookMocks } from '~/mocks/browser'
import { useAvailableFeatures } from '~/mocks/features'
+import type { MockResolverInfo } from '~/mocks/utils'
import { examples } from '~/queries/examples'
import { AvailableFeature, InsightShortId, QueryBasedInsightModel } from '~/types'
@@ -60,7 +61,8 @@ const meta: Meta<StoryArgs> = {
].reduce(
(acc, url) =>
Object.assign(acc, {
- [url]: (req: any) => {
+ [url]: async ({ request }: MockResolverInfo) => {
+ const body = (await request.json()) as Record<string, unknown>
return [
200,
{
@@ -68,7 +70,7 @@ const meta: Meta<StoryArgs> = {
enabled: true,
access_token: '1AEQjQ2xNLGoiyI0UnNlLzOiBZWWMQ',
password_required: passwordRequired,
- ...req.body,
+ ...body,
},
]
},
diff --git a/frontend/src/lib/components/Sharing/SharingModal.test.tsx b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
index 06e0f8098c04..38b89eba3a44 100644
--- a/frontend/src/lib/components/Sharing/SharingModal.test.tsx
+++ b/frontend/src/lib/components/Sharing/SharingModal.test.tsx
@@ -1,10 +1,11 @@
import '@testing-library/jest-dom'
-import { render, screen, within } from '@testing-library/react'
+import { cleanup, render, screen, within } from '@testing-library/react'
import { expectLogic } from 'kea-test-utils'
import { eventUsageLogic } from 'lib/utils/eventUsageLogic'
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { NodeKind } from '~/queries/schema/schema-general'
@@ -76,11 +77,16 @@ function mockInsightSharingConfiguration({
}
describe('SharingModal (dashboard)', () => {
+ // Unmount the modal portal between tests so its embed CodeSnippet (a themeLogic
+ // consumer) can't commit a deferred render after a later file resets the kea store.
+ afterEach(() => cleanup())
+
function DashboardSharingModalWrapper({ extraProps }: { extraProps?: Partial<SharingModalProps> }): JSX.Element {
// Render the dashboard sharing modal with `WHITE_LABELLING` so the UI shows
// the branding option in the form.
useAvailableFeatures([AvailableFeature.WHITE_LABELLING])
initKeaTests()
+ themeLogic.mount()
useMocks({
get: mockDashboardSharingConfiguration({}),
})
@@ -161,9 +167,12 @@ describe('SharingModal (insight)', () => {
name: 'My insight',
}
+ afterEach(() => cleanup())
+
function InsightSharingModalWrapper({ extraProps }: { extraProps?: Partial<SharingModalProps> }): JSX.Element {
useAvailableFeatures([])
initKeaTests()
+ themeLogic.mount()
useMocks({
get: mockInsightSharingConfiguration({ insightId: defaultInsightId }),
})
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
index fbf9a08a48b4..5238a21812b9 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionLogic.test.ts
@@ -52,8 +52,10 @@ describe('subscriptionLogic', () => {
},
},
post: {
- '/api/environments/:team/subscriptions': (req, res, ctx) =>
- res(ctx.json({ id: 42, ...(req.body as Partial<SubscriptionType>) } as SubscriptionType)),
+ '/api/environments/:team/subscriptions': async ({ request }) => [
+ 200,
+ { id: 42, ...((await request.json()) as Partial<SubscriptionType>) } as SubscriptionType,
+ ],
},
})
initKeaTests()
@@ -202,9 +204,9 @@ describe('subscriptionLogic', () => {
let capturedBody: Partial<SubscriptionType> | undefined
useMocks({
post: {
- '/api/environments/:team/subscriptions': (req, res, ctx) => {
- capturedBody = req.body as Partial<SubscriptionType>
- return res(ctx.json({ id: 42, ...capturedBody } as SubscriptionType))
+ '/api/environments/:team/subscriptions': async ({ request }) => {
+ capturedBody = (await request.json()) as Partial<SubscriptionType>
+ return [200, { id: 42, ...capturedBody } as SubscriptionType]
},
},
})
@@ -231,9 +233,9 @@ describe('subscriptionLogic', () => {
let capturedBody: Partial<SubscriptionType> | undefined
useMocks({
post: {
- '/api/environments/:team/subscriptions': (req, res, ctx) => {
- capturedBody = req.body as Partial<SubscriptionType>
- return res(ctx.json({ id: 43, ...capturedBody } as SubscriptionType))
+ '/api/environments/:team/subscriptions': async ({ request }) => {
+ capturedBody = (await request.json()) as Partial<SubscriptionType>
+ return [200, { id: 43, ...capturedBody } as SubscriptionType]
},
},
})
diff --git a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
index 258f174be7d6..0500b98a43a9 100644
--- a/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
+++ b/frontend/src/lib/components/Subscriptions/subscriptionsLogic.test.ts
@@ -61,15 +61,16 @@ describe('subscriptionsLogic', () => {
get: {
'/api/environments/:team_id/insights/1': fixtureInsightResponse(1),
'/api/environments/:team_id/insights/2': fixtureInsightResponse(2),
- '/api/environments/:team_id/insights': (req) => {
- const insightShortId = req.url.searchParams.get('short_id')
+ '/api/environments/:team_id/insights': ({ request }) => {
+ const insightShortId = new URL(request.url).searchParams.get('short_id')
const res = insightShortId ? [fixtureInsightResponse(parseInt(insightShortId, 10))] : []
return [200, { results: res }]
},
- '/api/environments/:team_id/subscriptions': (req) => {
- const insightId = req.url.searchParams.get('insight')
- const resourceType = req.url.searchParams.get('resource_type')
+ '/api/environments/:team_id/subscriptions': ({ request }) => {
+ const url = new URL(request.url)
+ const insightId = url.searchParams.get('insight')
+ const resourceType = url.searchParams.get('resource_type')
let results: SubscriptionType[] = []
if (resourceType === 'ai_prompt') {
diff --git a/frontend/src/lib/components/TablePreview/DatabaseTablePreview.test.tsx b/frontend/src/lib/components/TablePreview/DatabaseTablePreview.test.tsx
index 5d465d27915d..d04dda0075f5 100644
--- a/frontend/src/lib/components/TablePreview/DatabaseTablePreview.test.tsx
+++ b/frontend/src/lib/components/TablePreview/DatabaseTablePreview.test.tsx
@@ -148,8 +148,8 @@ describe('DatabaseTablePreview', () => {
useMocks({
post: {
- '/api/environments/:team/query/:kind': (req) => {
- const queryString = queryStringFromRequestBody(req.body)
+ '/api/environments/:team/query/:kind': async ({ request }) => {
+ const queryString = queryStringFromRequestBody(await request.json())
executedQueries.push(queryString)
const label = responseIndex === 0 ? 'first result' : 'second result'
@@ -200,8 +200,8 @@ describe('DatabaseTablePreview', () => {
useMocks({
post: {
- '/api/environments/:team/query/:kind': (req) => {
- const queryString = queryStringFromRequestBody(req.body)
+ '/api/environments/:team/query/:kind': async ({ request }) => {
+ const queryString = queryStringFromRequestBody(await request.json())
executedQueries.push(queryString)
return [
diff --git a/frontend/src/lib/components/TaxonomicFilter/InfiniteSelectResults.test.tsx b/frontend/src/lib/components/TaxonomicFilter/InfiniteSelectResults.test.tsx
index f5a58425ad03..f51b81f187ab 100644
--- a/frontend/src/lib/components/TaxonomicFilter/InfiniteSelectResults.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/InfiniteSelectResults.test.tsx
@@ -30,8 +30,8 @@ describe('InfiniteSelectResults - CategoryPill logic mounting', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/event_definitions': (res) => {
- const search = res.url.searchParams.get('search')
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
const results = search
? mockEventDefinitions.filter((e) => e.name.includes(search))
: mockEventDefinitions
diff --git a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx
index 62f29c41a14d..c6759fa4164a 100644
--- a/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx
+++ b/frontend/src/lib/components/TaxonomicFilter/TaxonomicFilter.test.tsx
@@ -9,6 +9,7 @@ import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { useMocks } from '~/mocks/jest'
+import { MockResolverInfo } from '~/mocks/utils'
import { actionsModel } from '~/models/actionsModel'
import { groupsModel } from '~/models/groupsModel'
import { performQuery } from '~/queries/query'
@@ -860,8 +861,8 @@ describe('TaxonomicFilter', () => {
// verify that promotion moves it to position 0.
useMocks({
get: {
- '/api/projects/:team/property_definitions': (req: { url: URL }) => {
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/projects/:team/property_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
const allProps = [
{ ...mockEventPropertyDefinition, id: 'url-other', name: '$initial_referring_url' },
{ ...mockEventPropertyDefinition, id: 'url-other-2', name: 'signup_url' },
@@ -1428,8 +1429,8 @@ describe('TaxonomicFilter', () => {
useMocks({
get: {
'/api/projects/:team/event_definitions': mockGetEventDefinitions,
- '/api/projects/:team/property_definitions': (req: { url: URL }) => {
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/projects/:team/property_definitions': ({ request }: MockResolverInfo) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
const fixture = promotedFixtures[search]
const names = fixture ? [...fixture.decoys, fixture.name] : []
return [
@@ -1702,9 +1703,9 @@ describe('TaxonomicFilter', () => {
// to the DOM in CI. Production latency exceeds this comfortably.
useMocks({
get: {
- '/api/projects/:team/event_definitions': async (req) => {
+ '/api/projects/:team/event_definitions': async (info) => {
await new Promise((resolve) => setTimeout(resolve, 100))
- return mockGetEventDefinitions(req)
+ return mockGetEventDefinitions(info)
},
'/api/projects/:team/property_definitions': mockGetPropertyDefinitions,
'/api/projects/:team/actions': { results: [mockActionDefinition] },
diff --git a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
index bf99f5603424..4d4b3d8737d1 100644
--- a/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/infiniteListLogic.test.ts
@@ -32,10 +32,11 @@ describe('infiniteListLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/event_definitions': (req) => {
- const search = req.url.searchParams.get('search')
- const limit = Number(req.url.searchParams.get('limit'))
- const offset = Number(req.url.searchParams.get('offset'))
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const url = new URL(request.url)
+ const search = url.searchParams.get('search')
+ const limit = Number(url.searchParams.get('limit'))
+ const offset = Number(url.searchParams.get('offset'))
const results = search
? mockEventDefinitions.filter((e) => e.name.includes(search))
: mockEventDefinitions
@@ -49,13 +50,14 @@ describe('infiniteListLogic', () => {
},
]
},
- '/api/projects/:team/property_definitions': (req) => {
- const search = req.url.searchParams.get('search')
+ '/api/projects/:team/property_definitions': ({ request }) => {
+ const url = new URL(request.url)
+ const search = url.searchParams.get('search')
let results = search
? mockEventPropertyDefinitions.filter((e) => e.name.includes(search))
: mockEventPropertyDefinitions
- if (req.url.searchParams.has('filter_by_event_names')) {
- const isEventProperty = req.url.searchParams.get('filter_by_event_names') === 'true'
+ if (url.searchParams.has('filter_by_event_names')) {
+ const isEventProperty = url.searchParams.get('filter_by_event_names') === 'true'
results = results.filter(
(e: PropertyDefinition) => e.is_seen_on_filtered_events === isEventProperty
)
diff --git a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
index 7b0d922e0bc4..d32f9c90c943 100644
--- a/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
+++ b/frontend/src/lib/components/TaxonomicFilter/taxonomicFilterLogic.test.ts
@@ -35,8 +35,8 @@ describe('taxonomicFilterLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/event_definitions': (res) => {
- const search = res.url.searchParams.get('search')
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
const results = search
? mockEventDefinitions.filter((e) => e.name.includes(search))
: mockEventDefinitions
@@ -48,8 +48,8 @@ describe('taxonomicFilterLogic', () => {
},
]
},
- '/api/environments/:team/sessions/property_definitions': (res) => {
- const search = res.url.searchParams.get('search')
+ '/api/environments/:team/sessions/property_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
const results = search
? mockSessionPropertyDefinitions.filter((e) => e.name.includes(search))
: mockSessionPropertyDefinitions
@@ -227,8 +227,8 @@ describe('taxonomicFilterLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/event_definitions': (res) => {
- const search = res.url.searchParams.get('search')
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
const results = search
? eventsWithPageview.filter((e) => e.name.toLowerCase().includes(search.toLowerCase()))
: eventsWithPageview
diff --git a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
index b7332cc87dec..e7b2bfa6a138 100644
--- a/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
+++ b/frontend/src/lib/integrations/SlackChannelPicker.test.tsx
@@ -59,9 +59,10 @@ describe('SlackChannelPicker', () => {
channelIdLookups = []
useMocks({
get: {
- '/api/environments/:team_id/integrations/:id/channels': (req: any) => {
- const search = req.url.searchParams.get('search')
- const channelId = req.url.searchParams.get('channel_id')
+ '/api/environments/:team_id/integrations/:id/channels': ({ request }) => {
+ const url = new URL(request.url)
+ const search = url.searchParams.get('search')
+ const channelId = url.searchParams.get('channel_id')
if (channelId) {
channelIdLookups.push(channelId)
const match =
diff --git a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
index d237ca1a1d35..34130d46dac8 100644
--- a/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
+++ b/frontend/src/lib/integrations/slackIntegrationLogic.test.ts
@@ -40,8 +40,8 @@ describe('slackIntegrationLogic — loadAllSlackChannels search & pagination', (
]
useMocks({
get: {
- '/api/environments/:team_id/integrations/:id/channels': (req) => {
- lastChannelsQuery = Object.fromEntries(req.url.searchParams.entries())
+ '/api/environments/:team_id/integrations/:id/channels': ({ request }) => {
+ lastChannelsQuery = Object.fromEntries(new URL(request.url).searchParams.entries())
return [
200,
{
diff --git a/frontend/src/mocks/browser.tsx b/frontend/src/mocks/browser.tsx
index aa232abd0bd6..31e18c23c5f2 100644
--- a/frontend/src/mocks/browser.tsx
+++ b/frontend/src/mocks/browser.tsx
@@ -1,9 +1,9 @@
import type { ReactRenderer } from '@storybook/react'
import { DecoratorFunction } from '@storybook/types'
-import { rest, setupWorker } from 'msw'
+import { setupWorker } from 'msw/browser'
import { handlers } from '~/mocks/handlers'
-import { MockSignature, Mocks, mocksToHandlers } from '~/mocks/utils'
+import { HTTP_METHODS, MockSignature, Mocks, mocksToHandlers } from '~/mocks/utils'
import type { AppContext } from '~/types'
// Default handlers ensure no request is unhandled by msw
@@ -16,18 +16,17 @@ export const mswDecorator = (mocks: Mocks): DecoratorFunction<ReactRenderer, any
// merge the default mocks provided in `preview.tsx` with any provided by the story
// allow the story to override defaults
const mergedMocks: Mocks = {}
- const restKeys = Object.keys(rest) as Array<keyof typeof rest>
- for (const restMethod of restKeys) {
- mergedMocks[restMethod] = {}
- const storyMethodMocks = (parameters.msw?.mocks?.[restMethod] || {}) as Record<string, MockSignature>
+ for (const method of HTTP_METHODS) {
+ mergedMocks[method] = {}
+ const storyMethodMocks = (parameters.msw?.mocks?.[method] || {}) as Record<string, MockSignature>
// Ensure trailing slashes to avoid default handlers accidentally overshadowing story mocks
for (const [path, handler] of Object.entries(storyMethodMocks)) {
const cleanedPath = path.replace(/\/?$/, '/')
- mergedMocks[restMethod][cleanedPath] = handler
+ mergedMocks[method][cleanedPath] = handler
}
- for (const [path, handler] of Object.entries(mocks?.[restMethod] || {})) {
+ for (const [path, handler] of Object.entries(mocks?.[method] || {})) {
const cleanedPath = path.replace(/\/?$/, '/')
- mergedMocks[restMethod][cleanedPath] = handler
+ mergedMocks[method][cleanedPath] = handler
}
}
useStorybookMocks(mergedMocks)
diff --git a/frontend/src/mocks/handlers.ts b/frontend/src/mocks/handlers.ts
index fc9f9393cda9..273be5709469 100644
--- a/frontend/src/mocks/handlers.ts
+++ b/frontend/src/mocks/handlers.ts
@@ -13,7 +13,7 @@ import {
MOCK_EXPERIMENTS_STATS_RESPONSE,
} from 'lib/api.mock'
-import { ResponseComposition, RestContext, RestRequest } from 'msw'
+import { HttpResponse } from 'msw'
import { STATUS_PAGE_BASE } from 'lib/components/HelpMenu/incidentStatusLogic'
@@ -26,7 +26,7 @@ import { billingJson } from './fixtures/_billing'
import _hogFunctionTemplatesDestinations from './fixtures/_hogFunctionTemplatesDestinations.json'
import _hogFunctionTemplatesTransformations from './fixtures/_hogFunctionTemplatesTransformations.json'
import * as statusPageAllOK from './fixtures/_status_page_all_ok.json'
-import { MockSignature, Mocks, mocksToHandlers } from './utils'
+import { MockResolverInfo, MockSignature, Mocks, mocksToHandlers } from './utils'
export const EMPTY_PAGINATED_RESPONSE = {
count: 0,
@@ -41,38 +41,56 @@ export const toPaginatedResponse = (results: any[]): typeof EMPTY_PAGINATED_RESP
previous: null,
})
-const hogFunctionTemplateRetrieveMock: MockSignature = (req, res, ctx) => {
+const hogFunctionTemplateRetrieveMock: MockSignature = ({ params }) => {
const hogFunctionTemplate =
- _hogFunctionTemplatesDestinations.results.find((conf) => conf.id === req.params.id) ||
- _hogFunctionTemplatesTransformations.results.find((conf) => conf.id === req.params.id)
+ _hogFunctionTemplatesDestinations.results.find((conf) => conf.id === params.id) ||
+ _hogFunctionTemplatesTransformations.results.find((conf) => conf.id === params.id)
if (!hogFunctionTemplate) {
- return res(ctx.status(404))
+ return new HttpResponse(null, { status: 404 })
}
- return res(ctx.json({ ...hogFunctionTemplate }))
+ return HttpResponse.json({ ...hogFunctionTemplate })
}
-const hogFunctionTemplatesMock: MockSignature = (req, res, ctx) => {
- const results = req.url.searchParams.get('types')?.includes('transformation')
+const hogFunctionTemplatesMock: MockSignature = ({ request }) => {
+ const types = new URL(request.url).searchParams.get('types')
+ const results = types?.includes('transformation')
? _hogFunctionTemplatesTransformations
- : req.url.searchParams.get('types')?.includes('destination')
+ : types?.includes('destination')
? _hogFunctionTemplatesDestinations
: []
- return res(ctx.json(results))
+ return HttpResponse.json(results)
}
-// this really returns MaybePromise<ResponseFunction<any>>
-// but MSW doesn't export MaybePromise 🤷
-function posthogCORSResponse(req: RestRequest, res: ResponseComposition, ctx: RestContext): any {
- return res(
- ctx.status(200),
- ctx.json('ok'),
+// Access-Control-Allow-Origin must be an origin (scheme + host + port), not a URL with a path.
+// Prefer the Origin header; fall back to deriving the origin from Referer (which often carries a path).
+function corsAllowOrigin({ request }: MockResolverInfo): string {
+ const origin = request.headers.get('origin')
+ if (origin && origin.length) {
+ return origin
+ }
+ const referer = request.headers.get('referer')
+ if (referer && referer.length) {
+ try {
+ return new URL(referer).origin
+ } catch {
+ // malformed referer — fall through to the default
+ }
+ }
+ return 'http://localhost'
+}
+
+function posthogCORSResponse(info: MockResolverInfo): Response {
+ return HttpResponse.json('ok', {
+ status: 200,
// some of our tests try to make requests via posthog-js e.g. userLogic calls identify
// they have to have CORS allowed, or they pass but print noise to the console
- ctx.set('Access-Control-Allow-Origin', req.referrer.length ? req.referrer : 'http://localhost'),
- ctx.set('Access-Control-Allow-Credentials', 'true'),
- ctx.set('Access-Control-Allow-Headers', '*')
- )
+ headers: {
+ 'Access-Control-Allow-Origin': corsAllowOrigin(info),
+ 'Access-Control-Allow-Credentials': 'true',
+ 'Access-Control-Allow-Headers': '*',
+ },
+ })
}
export const defaultMocks: Mocks = {
@@ -135,7 +153,7 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/core_memory/': { results: [] },
'/api/environments/:team_id/conversations/': EMPTY_PAGINATED_RESPONSE,
'/api/user_home_settings/@me/': { tabs: [], homepage: null },
- '/api/organizations/@current/': (): MockSignature => [
+ '/api/organizations/@current/': () => [
200,
{
...MOCK_DEFAULT_ORGANIZATION,
@@ -157,7 +175,7 @@ export const defaultMocks: Mocks = {
'/api/environments/:team_id/persons': EMPTY_PAGINATED_RESPONSE,
'/api/environments/:team_id/persons/properties/': toPaginatedResponse(MOCK_PERSON_PROPERTIES),
'/api/personal_api_keys/': [],
- '/api/users/@me/': (): MockSignature => [
+ '/api/users/@me/': () => [
200,
{
...MOCK_DEFAULT_USER,
@@ -269,16 +287,16 @@ export const defaultMocks: Mocks = {
'/api/projects/:team_id/tags/': [],
},
post: {
- 'https://us.i.posthog.com/e/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- '/e/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- 'https://us.i.posthog.com/decide/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- 'https://us.i.posthog.com/flags/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- '/decide/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- '/flags/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
- 'https://us.i.posthog.com/engage/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
+ 'https://us.i.posthog.com/e/': posthogCORSResponse,
+ '/e/': posthogCORSResponse,
+ 'https://us.i.posthog.com/decide/': posthogCORSResponse,
+ 'https://us.i.posthog.com/flags/': posthogCORSResponse,
+ '/decide/': posthogCORSResponse,
+ '/flags/': posthogCORSResponse,
+ 'https://us.i.posthog.com/engage/': posthogCORSResponse,
'/api/environments/:team_id/query/': [200, { results: [] }],
'/api/environments/:team_id/query/:query_kind/': [200, { results: [] }],
- '/api/environments/:team_id/insights/viewed/': (): MockSignature => [201, null],
+ '/api/environments/:team_id/insights/viewed/': () => [201, null],
'api/environments/:team_id/query': [200, { results: [] }],
'api/environments/:team_id/query/:query_kind/': [200, { results: [] }],
'/api/environments/:team_id/file_system/log_view/': {},
@@ -290,7 +308,7 @@ export const defaultMocks: Mocks = {
'/api/user_home_settings/@me/': { tabs: [], homepage: null },
},
options: {
- 'https://us.i.posthog.com/decide/': (req, res, ctx): MockSignature => posthogCORSResponse(req, res, ctx),
+ 'https://us.i.posthog.com/decide/': posthogCORSResponse,
},
}
export const handlers = mocksToHandlers(defaultMocks)
diff --git a/frontend/src/mocks/jest.ts b/frontend/src/mocks/jest.ts
index c36e984e7aad..f213a4d8d130 100644
--- a/frontend/src/mocks/jest.ts
+++ b/frontend/src/mocks/jest.ts
@@ -1,32 +1,59 @@
import { setupServer } from 'msw/node'
import { useAvailableFeatures } from '~/mocks/features'
-import { handlers } from '~/mocks/handlers'
+import { EMPTY_PAGINATED_RESPONSE, handlers } from '~/mocks/handlers'
import { Mocks, mocksToHandlers } from '~/mocks/utils'
-export const mswServer = setupServer(...handlers)
+// Jest-only defaults. Under jsdom an unhandled request hits the never-resolving fetch stub
+// (see beforeAll), so any logic that awaits one of these on mount would hang
+// toFinishAllListeners. These live here rather than in the shared `handlers` so the Storybook
+// MSW worker — which serves the same `handlers` to a real browser — is left untouched. Appended
+// after `handlers` so an existing matching handler still wins, and `server.use()` (useMocks)
+// still overrides them per test.
+const jestOnlyDefaultHandlers = mocksToHandlers({
+ get: {
+ '/api/projects/:team_id/product_tours/': EMPTY_PAGINATED_RESPONSE,
+ '/api/environments/:team_id/integrations/': EMPTY_PAGINATED_RESPONSE,
+ '/api/environments/:team_id/llm_analytics/evaluation_config/': { active_provider_key: null },
+ '/api/environments/:team_id/taggers/': EMPTY_PAGINATED_RESPONSE,
+ '/api/projects/:team_id/event_definitions/primary_properties/': { primary_properties: {} },
+ '/api/environments/:team_id/default_release_conditions/': { default_groups: [], enabled: false },
+ // The unhandled-request floor (a paginated `{ results: [] }`) is the wrong shape here and
+ // would crash UsedInBanner, which reads `feature_flags.results` & co.
+ '/api/projects/:team_id/cohorts/:id/used_in/': {
+ feature_flags: { results: [], total: 0, has_more: false },
+ insights: { results: [], total: 0, has_more: false },
+ cohorts: { results: [], total: 0, has_more: false },
+ },
+ },
+})
+
+export const mswServer = setupServer(...handlers, ...jestOnlyDefaultHandlers)
export const useMocks = (mocks: Mocks): void => mswServer.use(...mocksToHandlers(mocks))
window.confirm = jest.fn()
beforeAll(() => {
useAvailableFeatures([])
- mswServer.listen({
- onUnhandledRequest(req) {
- const { hostname } = new URL(req.url)
- // Silence external requests entirely
- if (
- hostname === 'posthog.com' ||
- hostname.endsWith('.posthog.com') ||
- hostname === 'gravatar.com' ||
- hostname.endsWith('.gravatar.com')
- ) {
- return
- }
- // Single-line warning instead of verbose multi-line stack trace
- console.warn(`[MSW] Unhandled ${req.method} ${req.url}`)
- },
- })
+ // MSW passes unhandled requests through to the "real" global fetch. Under MSW v2 in jsdom that
+ // passthrough resolves a response the interceptor then fails to clone ("originalResponse.clone
+ // is not a function"), crashing the whole file. We can't passthrough. The two obvious stubs are
+ // both worse at scale: a never-resolving stub makes any awaited unmocked load hang
+ // toFinishAllListeners, and a rejecting stub turns every fire-and-forget request into an
+ // unhandled "Failed to fetch" rejection that settles after teardown and OOMs the worker.
+ // Instead resolve a benign, cloneable, empty paginated response: awaited loads complete (no
+ // hang), loaders succeed with empty data (no rejection, no post-teardown console), and the 2xx
+ // path never touches `location` (no "location is not defined"). A test that needs real data
+ // from an endpoint mocks it explicitly via useMocks; this is only the floor for the rest.
+ global.fetch = (() =>
+ Promise.resolve(
+ new Response(JSON.stringify({ results: [], count: 0, next: null, previous: null }), {
+ status: 200,
+ headers: { 'content-type': 'application/json' },
+ })
+ )) as typeof fetch
+ // Silent: suites run to completion, so warning on every unhandled request would flood output.
+ mswServer.listen({ onUnhandledRequest: () => {} })
})
afterEach(() => mswServer.resetHandlers())
afterAll(() => mswServer.close())
diff --git a/frontend/src/mocks/utils.ts b/frontend/src/mocks/utils.ts
index 938f1d9763ef..e73aaf729194 100644
--- a/frontend/src/mocks/utils.ts
+++ b/frontend/src/mocks/utils.ts
@@ -1,46 +1,66 @@
-import { rest } from 'msw'
+import { http, HttpResponse, type DefaultBodyType, type HttpHandler, type HttpResponseResolver } from 'msw'
-export type MockSignature =
- | ((
- req: Parameters<Parameters<(typeof rest)['get']>[1]>[0],
- res: Parameters<Parameters<(typeof rest)['get']>[1]>[1],
- ctx: Parameters<Parameters<(typeof rest)['get']>[1]>[2]
- ) => [number, any] | [number])
- | Record<string, any>
-export type Mocks = Partial<Record<keyof typeof rest, Record<string, MockSignature>>>
+export const HTTP_METHODS = ['get', 'post', 'put', 'patch', 'delete', 'options'] as const
+export type HttpMethod = (typeof HTTP_METHODS)[number]
-export const mocksToHandlers = (mocks: Mocks): ReturnType<(typeof rest)['get']>[] => {
- const response: ReturnType<(typeof rest)['get']>[] = []
+// The resolver argument MSW v2 passes to a handler: `{ request, params, cookies, requestId }`.
+export type MockResolverInfo = Parameters<HttpResponseResolver>[0]
+
+// What a mock resolves to:
+// 1. A `[status, body]` tuple
+// 2. A `[status]` tuple
+// 3. `undefined`/`null` — an empty 200 (matches v1's `res()`); for a real network error
+// return `HttpResponse.error()` explicitly
+// 4. A `Response`/`HttpResponse`
+// 5. Any other value — returned as a JSON body
+type MockResult = Response | [number, DefaultBodyType?] | DefaultBodyType | null | undefined
+
+export type MockSignature = ((info: MockResolverInfo) => MockResult | Promise<MockResult>) | Record<string, any> | any[]
+export type Mocks = Partial<Record<HttpMethod, Record<string, MockSignature>>>
+
+const toResponse = (result: MockResult): Response => {
+ if (result instanceof Response) {
+ return result
+ }
+ if (Array.isArray(result)) {
+ if (result.length === 2 && typeof result[0] === 'number') {
+ return HttpResponse.json(result[1] ?? null, { status: result[0] })
+ }
+ if (result.length === 1 && typeof result[0] === 'number') {
+ return new HttpResponse(null, { status: result[0] })
+ }
+ // Any other array is a JSON array body.
+ return HttpResponse.json(result)
+ }
+ if (result == null) {
+ // A bare empty return is an empty 200, matching v1's `res()`. This is the fall-through
+ // for handlers with conditional branches and no final else (e.g. a query mock that only
+ // covers some kinds) — it must NOT be a network error, or apiStatusLogic flips the whole
+ // app into the "trouble connecting to the server" banner. Return HttpResponse.error()
+ // explicitly to model a real network failure.
+ return new HttpResponse(null, { status: 200 })
+ }
+ return HttpResponse.json(result)
+}
+
+export const mocksToHandlers = (mocks: Mocks): HttpHandler[] => {
+ const handlers: HttpHandler[] = []
Object.entries(mocks)
- .filter((entry): entry is [keyof Mocks, Record<string, MockSignature>] => !!entry)
+ .filter((entry): entry is [HttpMethod, Record<string, MockSignature>] => !!entry[1])
.forEach(([method, mockHandlers]) => {
Object.entries(mockHandlers).forEach(([path, handler]) => {
const pathWithoutTrailingSlash = path.replace(/\/$/, '')
- response.push(
- (rest[method] as (typeof rest)['get'])(pathWithoutTrailingSlash, async (req, res, ctx) => {
- // We currently support a few ways to specify a mock response:
- // 1. A function that returns a tuple of [status, body]
- // 2. A function that returns a tuple of [status]
- // 3. A function that returns undefined. This represents that a network error has occurred
- // 4. A function that returns an MSW response
- // 5. A JSON serializable object that will be returned as the response body
+ handlers.push(
+ (http[method] as (typeof http)['get'])(pathWithoutTrailingSlash, async (info) => {
+ // A function handler returns one of the MockResult forms (sync or async);
+ // any other value is a static JSON body (arrays serialized as-is, matching v1).
if (typeof handler === 'function') {
- const response = await handler(req, res, ctx)
- if (Array.isArray(response)) {
- const responseArray = response
- if (responseArray.length === 2 && typeof responseArray[0] === 'number') {
- return res(ctx.status(responseArray[0]), ctx.json(responseArray[1] ?? null))
- }
- return res(...responseArray)
- } else if (!response) {
- return res()
- }
- return response
+ return toResponse(await handler(info))
}
- return res(ctx.json(handler ?? null))
+ return HttpResponse.json((handler as DefaultBodyType) ?? null)
})
)
})
})
- return response
+ return handlers
}
diff --git a/frontend/src/models/cohortsModel.test.ts b/frontend/src/models/cohortsModel.test.ts
index 3e272ae8a950..ee481366f625 100644
--- a/frontend/src/models/cohortsModel.test.ts
+++ b/frontend/src/models/cohortsModel.test.ts
@@ -58,8 +58,8 @@ describe('cohortsModel', () => {
'/api/projects/:team/cohorts/:id/': { success: true },
},
patch: {
- '/api/projects/:team/cohorts/:id/': (req) => {
- const data = req.body as Record<string, any>
+ '/api/projects/:team/cohorts/:id/': async ({ request }) => {
+ const data = (await request.json()) as Record<string, any>
return { ...MOCK_COHORTS.results[0], ...data }
},
},
diff --git a/frontend/src/models/primaryEventPropertiesModel.test.ts b/frontend/src/models/primaryEventPropertiesModel.test.ts
index fba6d033d993..62e4c5b18cd3 100644
--- a/frontend/src/models/primaryEventPropertiesModel.test.ts
+++ b/frontend/src/models/primaryEventPropertiesModel.test.ts
@@ -17,12 +17,12 @@ describe('the primary event properties model', () => {
'/api/projects/:team_id/event_definitions/by_name/': () => [200, { id: 'def-1', name: 'my_event' }],
},
patch: {
- '/api/projects/:team_id/event_definitions/:id/': (req) => [
+ '/api/projects/:team_id/event_definitions/:id/': async ({ request }) => [
200,
{
id: 'def-1',
name: 'my_event',
- primary_property: (req.body as Record<string, any>).primary_property,
+ primary_property: ((await request.json()) as Record<string, any>).primary_property,
},
],
},
diff --git a/frontend/src/models/propertyDefinitionsModel.test.ts b/frontend/src/models/propertyDefinitionsModel.test.ts
index b5bd23609dc8..9c530ffee41d 100644
--- a/frontend/src/models/propertyDefinitionsModel.test.ts
+++ b/frontend/src/models/propertyDefinitionsModel.test.ts
@@ -67,14 +67,14 @@ describe('the property definitions model', () => {
beforeEach(async () => {
useMocks({
get: {
- '/api/projects/:team_id/property_definitions/': (req) => {
- const propertiesToFind = (req.url.searchParams.get('properties') || '').split(',')
+ '/api/projects/:team_id/property_definitions/': ({ request }) => {
+ const url = new URL(request.url)
+ const propertiesToFind = (url.searchParams.get('properties') || '').split(',')
if (propertiesToFind[0] === 'network error') {
- return
+ return [500, { detail: 'simulated network error' }]
}
const filteredPropertyDefinitions =
- req.url.searchParams.get('type') === 'group' &&
- req.url.searchParams.get('group_type_index') !== null
+ url.searchParams.get('type') === 'group' && url.searchParams.get('group_type_index') !== null
? groupPropertyDefinitions
: propertyDefinitions
const foundProperties = filteredPropertyDefinitions.filter(
@@ -527,8 +527,8 @@ describe('the property definitions model', () => {
useMocks({
get: {
- '/api/event/values': (req) => {
- capturedUrl = req.url.toString()
+ '/api/event/values': ({ request }) => {
+ capturedUrl = request.url
return [200, { results: [], refreshing: false }]
},
},
@@ -552,8 +552,8 @@ describe('the property definitions model', () => {
useMocks({
get: {
- '/api/event/values': (req) => {
- capturedUrl = req.url.toString()
+ '/api/event/values': ({ request }) => {
+ capturedUrl = request.url
return [200, { results: [], refreshing: false }]
},
},
@@ -591,8 +591,8 @@ describe('the property definitions model', () => {
useMocks({
get: {
- '/api/event/values': (req) => {
- capturedUrls.push(req.url.toString())
+ '/api/event/values': ({ request }) => {
+ capturedUrls.push(request.url)
return [200, { results: [], refreshing: capturedUrls.length === 1 }]
},
},
diff --git a/frontend/src/models/saveAsActionDialog.test.tsx b/frontend/src/models/saveAsActionDialog.test.tsx
index c5ee9fdf6e64..34bcfdfe2ddc 100644
--- a/frontend/src/models/saveAsActionDialog.test.tsx
+++ b/frontend/src/models/saveAsActionDialog.test.tsx
@@ -60,8 +60,8 @@ describe('saveAsActionDialog', () => {
useMocks({
get: { '/api/projects/:team/actions/': { results: [] } },
post: {
- '/api/projects/:team/actions/': async (req) => {
- capturedBody = await req.json()
+ '/api/projects/:team/actions/': async ({ request }) => {
+ capturedBody = await request.json()
if (postStatus >= 400) {
return [postStatus, postResponseBody]
}
diff --git a/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts b/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
index 882afff8453a..45585379efbe 100644
--- a/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
+++ b/frontend/src/queries/nodes/DataNode/dataNodeLogic.queryCancellation.test.ts
@@ -18,8 +18,8 @@ describe('dataNodeLogic - query cancellation', () => {
featureFlagLogic.mount()
useMocks({
get: {
- '/api/environments/:team_id/insights/trend/': async (req) => {
- if (req.url.searchParams.get('date_from') === '-180d') {
+ '/api/environments/:team_id/insights/trend/': async ({ request }) => {
+ if (new URL(request.url).searchParams.get('date_from') === '-180d') {
// delay for a second before response without pausing
return new Promise<[number, { result: string[] }]>((resolve) =>
setTimeout(() => {
diff --git a/frontend/src/queries/nodes/WebVitals/WebVitals.stories.tsx b/frontend/src/queries/nodes/WebVitals/WebVitals.stories.tsx
index a316b94d4441..da2b28196379 100644
--- a/frontend/src/queries/nodes/WebVitals/WebVitals.stories.tsx
+++ b/frontend/src/queries/nodes/WebVitals/WebVitals.stories.tsx
@@ -23,10 +23,11 @@ const meta: Meta<QueryProps<Node>> = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- if ((req.body as any).query.kind === 'WebVitalsQuery') {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as any
+ if (body.query.kind === 'WebVitalsQuery') {
return [200, webVitals]
- } else if ((req.body as any).query.kind === 'TrendsQuery') {
+ } else if (body.query.kind === 'TrendsQuery') {
return [200, webVitalsTrends]
}
},
diff --git a/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.stories.tsx b/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.stories.tsx
index c993253ab31d..69cf187a21fa 100644
--- a/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.stories.tsx
+++ b/frontend/src/queries/nodes/WebVitals/WebVitalsPathBreakdown.stories.tsx
@@ -18,8 +18,9 @@ const meta: Meta<QueryProps<Node>> = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- if ((req.body as any).query.kind === 'WebVitalsPathBreakdownQuery') {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as any
+ if (body.query.kind === 'WebVitalsPathBreakdownQuery') {
return [200, webVitalsPathBreakdown]
}
},
diff --git a/frontend/src/queries/query.test.ts b/frontend/src/queries/query.test.ts
index 88e90221500e..f99abf20de75 100644
--- a/frontend/src/queries/query.test.ts
+++ b/frontend/src/queries/query.test.ts
@@ -14,8 +14,8 @@ describe('query', () => {
beforeEach(() => {
useMocks({
post: {
- '/api/environments/:team_id/query/:kind': (req) => {
- const data = req.body as any
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const data = (await request.json()) as any
if (data.query?.kind === 'HogQLQuery') {
return [
200,
diff --git a/frontend/src/scenes/PreflightCheck/preflightLogic.test.ts b/frontend/src/scenes/PreflightCheck/preflightLogic.test.ts
index aeef9aefa80f..c5e3b653629e 100644
--- a/frontend/src/scenes/PreflightCheck/preflightLogic.test.ts
+++ b/frontend/src/scenes/PreflightCheck/preflightLogic.test.ts
@@ -96,6 +96,8 @@ describe('preflightLogic', () => {
},
],
})
+ // Drain trailing listeners so the mode-change reload doesn't bleed into the next test
+ await expectLogic(logic).toFinishAllListeners()
})
it('parses checks correctly for experimentation mode', async () => {
diff --git a/frontend/src/scenes/authentication/invite-signup/InviteSignup.stories.tsx b/frontend/src/scenes/authentication/invite-signup/InviteSignup.stories.tsx
index 89fca332ddfb..391c1b1ec979 100644
--- a/frontend/src/scenes/authentication/invite-signup/InviteSignup.stories.tsx
+++ b/frontend/src/scenes/authentication/invite-signup/InviteSignup.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { HttpResponse, delay } from 'msw'
import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
@@ -32,8 +33,14 @@ const meta: Meta = {
],
},
post: {
- '/api/signup': (_, __, ctx) => [ctx.delay(1000), ctx.status(200), ctx.json({ success: true })],
- '/api/signup/1234': (_, __, ctx) => [ctx.delay(1000), ctx.status(200), ctx.json({ success: true })],
+ '/api/signup': async () => {
+ await delay(1000)
+ return HttpResponse.json({ success: true })
+ },
+ '/api/signup/1234': async () => {
+ await delay(1000)
+ return HttpResponse.json({ success: true })
+ },
'/api/login/precheck': { sso_enforcement: null, saml_available: false },
},
}),
diff --git a/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.stories.tsx b/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.stories.tsx
index dbf3197c86ed..9f6fd16b8991 100644
--- a/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.stories.tsx
+++ b/frontend/src/scenes/authentication/password-reset/PasswordResetComplete.stories.tsx
@@ -1,5 +1,6 @@
// PasswordResetComplete.stories.tsx
import { Meta, StoryObj } from '@storybook/react'
+import { HttpResponse, delay } from 'msw'
import { urls } from 'scenes/urls'
@@ -26,7 +27,12 @@ export const Default: Story = {
decorators: [
mswDecorator({
get: { '/api/reset/user-uuid-3f32/': { success: true } },
- post: { '/api/reset/user-uuid-3f32/': (_, __, ctx) => [ctx.delay(1000), ctx.status(200)] },
+ post: {
+ '/api/reset/user-uuid-3f32/': async () => {
+ await delay(1000)
+ return new HttpResponse(null, { status: 200 })
+ },
+ },
}),
],
}
diff --git a/frontend/src/scenes/authentication/signup/Signup.stories.tsx b/frontend/src/scenes/authentication/signup/Signup.stories.tsx
index 9ca3da892b7e..63696684b529 100644
--- a/frontend/src/scenes/authentication/signup/Signup.stories.tsx
+++ b/frontend/src/scenes/authentication/signup/Signup.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { HttpResponse, delay } from 'msw'
import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { userLogic } from 'scenes/userLogic'
@@ -17,7 +18,12 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: { '/api/users/@me': () => [500, null] },
- post: { '/api/signup': (_, __, ctx) => [ctx.delay(1000), ctx.status(200), ctx.json({ success: true })] },
+ post: {
+ '/api/signup': async () => {
+ await delay(1000)
+ return HttpResponse.json({ success: true })
+ },
+ },
}),
],
}
diff --git a/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx b/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
index f05c8ba0971c..fff369d06901 100644
--- a/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
+++ b/frontend/src/scenes/cohorts/AddPersonToCohortModal.stories.tsx
@@ -3,6 +3,7 @@ import { Meta, StoryObj } from '@storybook/react'
import { LemonButton, LemonModal } from '@posthog/lemon-ui'
import { useStorybookMocks } from '~/mocks/browser'
+import type { MockResolverInfo } from '~/mocks/utils'
import { NodeKind } from '~/queries/schema/schema-general'
import { PersonSelectList } from './PersonSelectList'
@@ -45,20 +46,22 @@ const DEFAULT_QUERY = {
}
const noop = (): void => {}
-const actorsQueryHandler = (req: {
- body?: { query?: { kind?: string; source?: { kind?: string } } }
-}): [number, typeof mockQueryResponse] | undefined => {
- const queryKind = req.body?.query?.source?.kind ?? req.body?.query?.kind
+const actorsQueryHandler = async ({
+ request,
+}: MockResolverInfo): Promise<[number, typeof mockQueryResponse] | undefined> => {
+ const body = (await request.json()) as { query?: { kind?: string; source?: { kind?: string } } }
+ const queryKind = body?.query?.source?.kind ?? body?.query?.kind
if (queryKind === 'ActorsQuery') {
return [200, mockQueryResponse]
}
}
-const emptyActorsQueryHandler = (req: {
- body?: { query?: { kind?: string; source?: { kind?: string } } }
-}): [number, typeof mockQueryResponse] | undefined => {
- const queryKind = req.body?.query?.source?.kind ?? req.body?.query?.kind
+const emptyActorsQueryHandler = async ({
+ request,
+}: MockResolverInfo): Promise<[number, typeof mockQueryResponse] | undefined> => {
+ const body = (await request.json()) as { query?: { kind?: string; source?: { kind?: string } } }
+ const queryKind = body?.query?.source?.kind ?? body?.query?.kind
if (queryKind === 'ActorsQuery') {
return [
diff --git a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
index 904b732c16b7..6af9bb4244a0 100644
--- a/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
+++ b/frontend/src/scenes/cohorts/cohortsSceneLogic.test.ts
@@ -61,8 +61,8 @@ describe('cohortsSceneLogic', () => {
'/api/projects/:team/cohorts/:id/': { success: true },
},
patch: {
- '/api/projects/:team/cohorts/:id/': (req) => {
- const data = req.body as Record<string, any>
+ '/api/projects/:team/cohorts/:id/': async ({ request }) => {
+ const data = (await request.json()) as Record<string, any>
return { ...MOCK_COHORTS.results[0], ...data }
},
},
diff --git a/frontend/src/scenes/dashboard/Dashboards.stories.tsx b/frontend/src/scenes/dashboard/Dashboards.stories.tsx
index bc2fc31e0db0..50b116b5f798 100644
--- a/frontend/src/scenes/dashboard/Dashboards.stories.tsx
+++ b/frontend/src/scenes/dashboard/Dashboards.stories.tsx
@@ -9,6 +9,7 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
import { useAvailableFeatures } from '~/mocks/features'
+import type { MockResolverInfo } from '~/mocks/utils'
import { BaseMathType, DashboardMode, EntityTypes } from '~/types'
import { dashboardTemplatesLogic } from './dashboards/templates/dashboardTemplatesLogic'
@@ -43,8 +44,8 @@ const insightMocks = dashboard.tiles.reduce((acc: Record<string, any>, tile: any
}, {})
// Add the generic insight fetching endpoint that requires from_dashboard param
-const insightFetchMock = (req: any): [number, any] => {
- const insightId = req.params.id
+const insightFetchMock = ({ params }: MockResolverInfo): [number, any] => {
+ const insightId = params.id
// Don't require from_dashboard in storybook to simplify things
// Find the insight in the dashboard tiles
diff --git a/frontend/src/scenes/dashboard/dashboardLogic.test.ts b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
index ee708c1166e5..abf26b11f6de 100644
--- a/frontend/src/scenes/dashboard/dashboardLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardLogic.test.ts
@@ -199,12 +199,12 @@ describe('dashboardLogic', () => {
},
'/api/environments/:team_id/insights/1001/': () => [200, { ...insights['1001'] }],
'/api/environments/:team_id/insights/800/': () => [200, { ...insights['800'] }],
- '/api/environments/:team_id/insights/:id/': (req) => {
- const dashboard = req.url.searchParams.get('from_dashboard')
+ '/api/environments/:team_id/insights/:id/': ({ request, params }) => {
+ const dashboard = new URL(request.url).searchParams.get('from_dashboard')
if (!dashboard) {
throw new Error('the logic must always add this param')
}
- const matched = insights[boxToId(req.params['id'])]
+ const matched = insights[boxToId(params.id as string | readonly string[])]
if (!matched) {
return [404, null]
}
@@ -215,19 +215,17 @@ describe('dashboardLogic', () => {
'/api/environments/:team_id/insights/cancel/': [201],
},
patch: {
- '/api/environments/:team_id/dashboards/:id/': async (req) => {
+ '/api/environments/:team_id/dashboards/:id/': async ({ request, params }) => {
const dashboardId =
- typeof req.params['id'] === 'string'
- ? parseInt(req.params['id'])
- : parseInt(req.params['id'][0])
- const payload = await req.json()
+ typeof params.id === 'string' ? parseInt(params.id) : parseInt((params.id as string[])[0])
+ const payload = (await request.json()) as Record<string, any>
return [200, { ...dashboards[dashboardId], ...payload }]
},
- '/api/environments/:team_id/dashboards/:id/move_tile/': async (req) => {
+ '/api/environments/:team_id/dashboards/:id/move_tile/': async ({ request, params }) => {
// backend updates the two dashboards and the insight
- const jsonPayload = await req.json()
+ const jsonPayload = (await request.json()) as Record<string, any>
const { to_dashboard: toDashboard, tile: tileToUpdate } = jsonPayload
- const from = dashboards[Number(req.params.id)]
+ const from = dashboards[Number(params.id)]
// remove the tile from the source dashboard
const fromIndex = from.tiles.findIndex(
(tile) => !!tile.insight && tile.insight.id === tileToUpdate.insight.id
@@ -250,13 +248,13 @@ describe('dashboardLogic', () => {
return [200, { ...from }]
},
- '/api/environments/:team_id/insights/:id/': async (req) => {
+ '/api/environments/:team_id/insights/:id/': async ({ request, params }) => {
try {
- const updates = await req.json()
+ const updates = await request.json()
if (typeof updates !== 'object') {
return [500, `this update should receive an object body not ${JSON.stringify(updates)}`]
}
- const insightId = boxToId(req.params.id)
+ const insightId = boxToId(params.id as string | readonly string[])
const starting: QueryBasedInsightModel = insights[insightId]
insights[insightId] = {
diff --git a/frontend/src/scenes/dashboard/dashboardQuickFiltersDebounce.test.ts b/frontend/src/scenes/dashboard/dashboardQuickFiltersDebounce.test.ts
index 95af7a525d05..f2c52ce5711a 100644
--- a/frontend/src/scenes/dashboard/dashboardQuickFiltersDebounce.test.ts
+++ b/frontend/src/scenes/dashboard/dashboardQuickFiltersDebounce.test.ts
@@ -78,11 +78,9 @@ function setupDashboard(quickFilterIds: string[] | null): () => {
previous: null,
results: [dashboard],
},
- '/api/environments/:team_id/insights/:id/': (req) => {
+ '/api/environments/:team_id/insights/:id/': ({ params }) => {
const id =
- typeof req.params['id'] === 'string'
- ? parseInt(req.params['id'])
- : parseInt(req.params['id'][0])
+ typeof params.id === 'string' ? parseInt(params.id) : parseInt((params.id as string[])[0])
if (id === 101) {
return [200, insight1]
}
diff --git a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
index cc613eb143c4..7f7a79d72bfb 100644
--- a/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
+++ b/frontend/src/scenes/dashboard/dashboards/dashboardsLogic.test.ts
@@ -174,8 +174,8 @@ describe('dashboardsLogic', () => {
const needleDashboard = allDashboards.find((d) => d.name === 'needle')!
useMocks({
get: {
- '/api/environments/:team_id/dashboards/': (req) => {
- if (req.url.searchParams.get('search')) {
+ '/api/environments/:team_id/dashboards/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('search')) {
return [200, { count: 1, next: null, previous: null, results: [needleDashboard] }]
}
return [200, { count: 7, next: null, previous: null, results: allDashboards }]
@@ -216,8 +216,8 @@ describe('dashboardsLogic', () => {
let lastRequestUrl: URL | null = null
useMocks({
get: {
- '/api/environments/:team_id/dashboards/': (req) => {
- lastRequestUrl = req.url
+ '/api/environments/:team_id/dashboards/': ({ request }) => {
+ lastRequestUrl = new URL(request.url)
return [200, { count: 0, next: null, previous: null, results: [] }]
},
},
diff --git a/frontend/src/scenes/data-management/events/EventDefinitionsTable.stories.tsx b/frontend/src/scenes/data-management/events/EventDefinitionsTable.stories.tsx
index 12ecfec7c435..4822a6133095 100644
--- a/frontend/src/scenes/data-management/events/EventDefinitionsTable.stories.tsx
+++ b/frontend/src/scenes/data-management/events/EventDefinitionsTable.stories.tsx
@@ -75,8 +75,8 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: {
- '/api/projects/:team_id/event_definitions/': (req: any) => {
- const verified = req.url.searchParams.get('verified')
+ '/api/projects/:team_id/event_definitions/': ({ request }) => {
+ const verified = new URL(request.url).searchParams.get('verified')
let results = MOCK_EVENT_DEFINITIONS.results
if (verified === 'true') {
diff --git a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
index 4cf9805e19ad..746982b23155 100644
--- a/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
+++ b/frontend/src/scenes/data-management/events/eventDefinitionsTableLogic.test.ts
@@ -27,9 +27,10 @@ describe('eventDefinitionsTableLogic', () => {
beforeEach(async () => {
useMocks({
get: {
- '/api/projects/:team/event_definitions': (req) => {
- const limit = req.url.searchParams.get('limit')
- const offset = req.url.searchParams.get('offset')
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const url = new URL(request.url)
+ const limit = url.searchParams.get('limit')
+ const offset = url.searchParams.get('offset')
if (limit === '50' && !offset) {
return [
@@ -39,7 +40,7 @@ describe('eventDefinitionsTableLogic', () => {
count: 50,
previous: null,
next: `api/projects/${MOCK_TEAM_ID}/event_definitions${
- combineUrl(req.url.pathname, {
+ combineUrl(url.pathname, {
limit: 50,
offset: 50,
event_type: EventDefinitionType.Event,
@@ -55,7 +56,7 @@ describe('eventDefinitionsTableLogic', () => {
results: mockEventDefinitions.slice(50, 56),
count: 6,
previous: `api/projects/${MOCK_TEAM_ID}/event_definitions${
- combineUrl(req.url.pathname, {
+ combineUrl(url.pathname, {
limit: 50,
event_type: EventDefinitionType.Event,
}).search
@@ -65,9 +66,10 @@ describe('eventDefinitionsTableLogic', () => {
]
}
},
- '/api/projects/:team/property_definitions': (req) => {
- const limit = req.url.searchParams.get('limit')
- const offset = req.url.searchParams.get('offset')
+ '/api/projects/:team/property_definitions': ({ request }) => {
+ const url = new URL(request.url)
+ const limit = url.searchParams.get('limit')
+ const offset = url.searchParams.get('offset')
if (limit === '5' && !offset) {
return [
@@ -77,8 +79,8 @@ describe('eventDefinitionsTableLogic', () => {
count: 5,
previous: null,
next: `api/projects/${MOCK_TEAM_ID}/property_definitions${
- combineUrl(req.url.pathname, {
- ...req.url.searchParams,
+ combineUrl(url.pathname, {
+ ...url.searchParams,
limit: 5,
offset: 5,
}).search
@@ -93,8 +95,8 @@ describe('eventDefinitionsTableLogic', () => {
results: mockEventPropertyDefinitions.slice(5, 8),
count: 3,
previous: `api/projects/${MOCK_TEAM_ID}/property_definitions${
- combineUrl(req.url.pathname, {
- ...req.url.searchParams,
+ combineUrl(url.pathname, {
+ ...url.searchParams,
limit: 5,
offset: undefined,
}).search
@@ -104,10 +106,11 @@ describe('eventDefinitionsTableLogic', () => {
]
}
},
- '/api/environments/:team_id/events': (req) => {
+ '/api/environments/:team_id/events': ({ request }) => {
+ const url = new URL(request.url)
if (
- req.url.searchParams.get('limit') === '1' &&
- req.url.searchParams.get('event') === 'event_with_example'
+ url.searchParams.get('limit') === '1' &&
+ url.searchParams.get('event') === 'event_with_example'
) {
return [
200,
@@ -119,7 +122,7 @@ describe('eventDefinitionsTableLogic', () => {
},
]
}
- if (req.url.searchParams.get('limit') === '1') {
+ if (url.searchParams.get('limit') === '1') {
return [200, { results: [mockEvent], next: null }]
}
},
diff --git a/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.stories.tsx b/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.stories.tsx
index 2997e8357fe4..0b1d206a674c 100644
--- a/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.stories.tsx
+++ b/frontend/src/scenes/data-management/properties/PropertyDefinitionsTable.stories.tsx
@@ -70,8 +70,8 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: {
- '/api/projects/:team_id/property_definitions/': (req: any) => {
- const verified = req.url.searchParams.get('verified')
+ '/api/projects/:team_id/property_definitions/': ({ request }) => {
+ const verified = new URL(request.url).searchParams.get('verified')
let results = MOCK_PROPERTY_DEFINITIONS.results
if (verified === 'true') {
diff --git a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
index 017db2fe03bd..6f086246145f 100644
--- a/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
+++ b/frontend/src/scenes/data-management/properties/propertyDefinitionsTableLogic.test.ts
@@ -18,8 +18,9 @@ describe('propertyDefinitionsTableLogic', () => {
beforeEach(async () => {
useMocks({
get: {
- '/api/projects/:team/property_definitions/': (req) => {
- if (req.url.searchParams.get('limit') === '50' && !req.url.searchParams.get('offset')) {
+ '/api/projects/:team/property_definitions/': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('limit') === '50' && !url.searchParams.get('offset')) {
return [
200,
{
@@ -27,8 +28,8 @@ describe('propertyDefinitionsTableLogic', () => {
count: 50,
previous: null,
next: `api/projects/${MOCK_TEAM_ID}/property_definitions${
- combineUrl(req.url.pathname, {
- ...req.url.searchParams,
+ combineUrl(url.pathname, {
+ ...url.searchParams,
limit: 50,
offset: 50,
}).search
@@ -36,15 +37,15 @@ describe('propertyDefinitionsTableLogic', () => {
},
]
}
- if (req.url.searchParams.get('limit') === '50' && req.url.searchParams.get('offset') === '50') {
+ if (url.searchParams.get('limit') === '50' && url.searchParams.get('offset') === '50') {
return [
200,
{
results: mockEventPropertyDefinitions.slice(50, 56),
count: 6,
previous: `api/projects/${MOCK_TEAM_ID}/property_definitions${
- combineUrl(req.url.pathname, {
- ...req.url.searchParams,
+ combineUrl(url.pathname, {
+ ...url.searchParams,
limit: 50,
offset: undefined,
}).search
diff --git a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
index 8f1b58fc6491..584330b4d358 100644
--- a/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
+++ b/frontend/src/scenes/data-pipelines/batch-exports/batchExportConfigFormLogic.test.ts
@@ -5,6 +5,7 @@ import { teamLogic } from 'scenes/teamLogic'
import { urls } from 'scenes/urls'
import { useMocks } from '~/mocks/jest'
+import { MockResolverInfo } from '~/mocks/utils'
import { initKeaTests } from '~/test/init'
import { BatchExportConfiguration } from '~/types'
@@ -343,11 +344,11 @@ describe('batchExportConfigFormLogic', () => {
// Register a GET + PATCH mock for every fixture so any round-trip test can load its
// own fixture by id and look up the captured request body via patchBodiesById[fx.id].
const getMocks: Record<string, BatchExportConfiguration> = {}
- const patchMocks: Record<string, (req: any) => Promise<[number, BatchExportConfiguration]>> = {}
+ const patchMocks: Record<string, (info: MockResolverInfo) => Promise<[number, BatchExportConfiguration]>> = {}
for (const fx of ALL_BATCH_EXPORTS) {
getMocks[`/api/environments/:team_id/batch_exports/${fx.id}`] = fx
- patchMocks[`/api/environments/:team_id/batch_exports/${fx.id}/`] = async (req) => {
- const body = await req.json()
+ patchMocks[`/api/environments/:team_id/batch_exports/${fx.id}/`] = async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
lastPatchBody = body
patchBodiesById[fx.id] = body
return [200, fx]
@@ -359,8 +360,8 @@ describe('batchExportConfigFormLogic', () => {
'/api/environments/:team_id/batch_exports/test': { steps: [] },
},
post: {
- '/api/environments/:team_id/batch_exports/': async (req) => {
- lastPostBody = await req.json()
+ '/api/environments/:team_id/batch_exports/': async ({ request }) => {
+ lastPostBody = (await request.json()) as Record<string, any>
return [200, { ...S3_BATCH_EXPORT, id: 'new-export-id' }]
},
},
diff --git a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
index 19ac0cc6ebac..54dcea5d551c 100644
--- a/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
+++ b/frontend/src/scenes/data-pipelines/event-filtering/EventFilterScene.stories.tsx
@@ -92,9 +92,9 @@ const EMPTY_TOTALS_RESULTS: unknown[][] = []
function metricsHandler(
timeSeriesResults: unknown[][],
totalsResults: unknown[][]
-): (req: { json: () => Promise<unknown> }) => Promise<[number, unknown]> {
- return async (req) => {
- const body = (await req.json()) as { query?: { query?: string } }
+): ({ request }: { request: Request }) => Promise<[number, unknown]> {
+ return async ({ request }) => {
+ const body = (await request.json()) as { query?: { query?: string } }
const isTimeSeries = body.query?.query?.includes('calendar') ?? false
return [200, { results: isTimeSeries ? timeSeriesResults : totalsResults }]
}
diff --git a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
index e18cc2c22198..f0319e8e8fcd 100644
--- a/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
+++ b/frontend/src/scenes/data-warehouse/editor/sqlEditorLogic.test.ts
@@ -171,8 +171,8 @@ describe('sqlEditorLogic', () => {
queryEndpointMock = jest.fn(() => [200, { tables: {}, joins: [] }])
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => {
- const shortId = req.url.searchParams.get('short_id')
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const shortId = new URL(request.url).searchParams.get('short_id')
if (shortId === MOCK_INSIGHT_SHORT_ID) {
return [200, { results: [MOCK_INSIGHT] }]
}
@@ -182,8 +182,8 @@ describe('sqlEditorLogic', () => {
return [200, { results: [] }]
},
'/api/environments/:team_id/warehouse_saved_queries/': { results: [MOCK_VIEW] },
- '/api/environments/:team_id/warehouse_saved_queries/:id/': (req) => {
- if (req.params.id === MOCK_VIEW.id) {
+ '/api/environments/:team_id/warehouse_saved_queries/:id/': ({ params }) => {
+ if (params.id === MOCK_VIEW.id) {
return [200, MOCK_VIEW]
}
return [404]
diff --git a/frontend/src/scenes/experiments/ExperimentForm/ExperimentForm.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/ExperimentForm.test.tsx
index 9d87ea1f958d..fd8050987c42 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/ExperimentForm.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/ExperimentForm.test.tsx
@@ -22,8 +22,8 @@ describe('ExperimentForm Integration', () => {
useMocks({
post: {
- [`/api/projects/${MOCK_TEAM_ID}/experiments`]: async (req) => {
- const body = (await req.json()) as Experiment
+ [`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {
+ const body = (await request.json()) as Experiment
return [
200,
{
diff --git a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
index 026e476176ab..2da3ef210601 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentForm/VariantsPanelCreateFeatureFlag.test.tsx
@@ -47,8 +47,8 @@ describe('VariantsPanelCreateFeatureFlag', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team_id/feature_flags/': (req) => {
- const url = new URL(req.url)
+ '/api/projects/:team_id/feature_flags/': ({ request }) => {
+ const url = new URL(request.url)
const search = url.searchParams.get('search')
// Return existing key if searching for it
diff --git a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts
index 29e674a02f4e..2922be505809 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/createExperimentLogic.test.ts
@@ -35,8 +35,8 @@ describe('createExperimentLogic', () => {
useMocks({
post: {
- [`/api/projects/${MOCK_TEAM_ID}/experiments`]: async (req) => {
- const body = (await req.json()) as Experiment
+ [`/api/projects/${MOCK_TEAM_ID}/experiments`]: async ({ request }) => {
+ const body = (await request.json()) as Experiment
if (!body.name || !body.description) {
return [400, { detail: 'Validation error' }]
}
diff --git a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
index af86724403be..ebe39f8a53da 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/selectExistingFeatureFlagModalLogic.test.ts
@@ -95,8 +95,8 @@ describe('selectExistingFeatureFlagModalLogic', () => {
beforeEach(() => {
useMocks({
get: {
- [`/api/projects/${MOCK_TEAM_ID}/experiments/eligible_feature_flags/`]: (req) => {
- const url = new URL(req.url, 'http://localhost')
+ [`/api/projects/${MOCK_TEAM_ID}/experiments/eligible_feature_flags/`]: ({ request }) => {
+ const url = new URL(request.url, 'http://localhost')
const search = url.searchParams.get('search')
const filteredFlags = search
diff --git a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.test.ts b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.test.ts
index 0201d249632c..ec1120f33e9f 100644
--- a/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.test.ts
+++ b/frontend/src/scenes/experiments/ExperimentForm/variantsPanelLogic.test.ts
@@ -74,8 +74,8 @@ describe('variantsPanelLogic', () => {
beforeEach(() => {
useMocks({
get: {
- [`/api/projects/${MOCK_TEAM_ID}/feature_flags/`]: (req) => {
- const url = new URL(req.url)
+ [`/api/projects/${MOCK_TEAM_ID}/feature_flags/`]: ({ request }) => {
+ const url = new URL(request.url)
const search = url.searchParams.get('search')
if (search) {
diff --git a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
index 6d32144f8730..90d35658d0b6 100644
--- a/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
+++ b/frontend/src/scenes/experiments/ExperimentWizard/experimentWizardLogic.test.tsx
@@ -639,8 +639,8 @@ describe('experimentWizardLogic', () => {
useMocks({
...apiMocks,
post: {
- [`/api/projects/${MOCK_TEAM_ID}/experiments/`]: async (req: any) => {
- capturedPayload = await req.json()
+ [`/api/projects/${MOCK_TEAM_ID}/experiments/`]: async ({ request }) => {
+ capturedPayload = (await request.json()) as Record<string, any>
return [
200,
{
diff --git a/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.test.ts b/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.test.ts
index 784bf2611ef4..624c9fedf398 100644
--- a/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.test.ts
+++ b/frontend/src/scenes/experiments/Metrics/sharedMetricModalLogic.test.ts
@@ -22,9 +22,10 @@ describe('sharedMetricModalLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team_id/experiment_saved_metrics': (req) => {
- const offset = parseInt(req.url.searchParams.get('offset') ?? '0')
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/projects/:team_id/experiment_saved_metrics': ({ request }) => {
+ const url = new URL(request.url)
+ const offset = parseInt(url.searchParams.get('offset') ?? '0')
+ const search = url.searchParams.get('search') ?? ''
if (search === 'nomatch') {
return [200, { count: 0, next: null, previous: null, results: [] }]
}
@@ -149,8 +150,8 @@ describe('sharedMetricModalLogic', () => {
it('a metric covered by another active tag stays selected when one tag is toggled off', async () => {
useMocks({
get: {
- '/api/projects/:team_id/experiment_saved_metrics': (req) => {
- const offset = parseInt(req.url.searchParams.get('offset') ?? '0')
+ '/api/projects/:team_id/experiment_saved_metrics': ({ request }) => {
+ const offset = parseInt(new URL(request.url).searchParams.get('offset') ?? '0')
if (offset === 0) {
return [
200,
diff --git a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts
index 68b32dee610f..b4bef8ac6602 100644
--- a/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts
+++ b/frontend/src/scenes/experiments/SharedMetrics/sharedMetricsLogic.test.ts
@@ -21,14 +21,17 @@ describe('sharedMetricsLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team_id/experiment_saved_metrics': (req) => [
- 200,
- makeMetrics(
- 2,
- req.url.searchParams.get('search') ?? '',
- parseInt(req.url.searchParams.get('offset') ?? '0')
- ),
- ],
+ '/api/projects/:team_id/experiment_saved_metrics': ({ request }) => {
+ const url = new URL(request.url)
+ return [
+ 200,
+ makeMetrics(
+ 2,
+ url.searchParams.get('search') ?? '',
+ parseInt(url.searchParams.get('offset') ?? '0')
+ ),
+ ]
+ },
},
})
initKeaTests()
diff --git a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
index 4314ae45348d..1f4360603562 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentAsymmetricIntervals.stories.tsx
@@ -32,14 +32,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(EXPERIMENT_METRIC_RESULT_WITH_ASYMMETRIC_INTERVALS))
+ return [200, EXPERIMENT_METRIC_RESULT_WITH_ASYMMETRIC_INTERVALS]
},
},
}),
diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
index 0e1783ecdb0f..6e027262b5a1 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistFiveVariants.stories.tsx
@@ -38,17 +38,17 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
if (isExperimentFunnelMetric(body.query.metric as ExperimentMetric)) {
- return res(ctx.json(FUNNEL_METRIC_RESULT))
+ return [200, FUNNEL_METRIC_RESULT]
} else if (isExperimentMeanMetric(body.query.metric as ExperimentMetric)) {
- return res(ctx.json(MEAN_METRIC_RESULT))
+ return [200, MEAN_METRIC_RESULT]
}
},
},
diff --git a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
index e1139bb46356..2c6771a457a1 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentFrequentistTwoVariants.stories.tsx
@@ -33,17 +33,17 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
if (isExperimentFunnelMetric(body.query.metric)) {
- return res(ctx.json(FUNNEL_METRIC_RESULT))
+ return [200, FUNNEL_METRIC_RESULT]
} else if (isExperimentMeanMetric(body.query.metric)) {
- return res(ctx.json(MEAN_METRIC_RESULT))
+ return [200, MEAN_METRIC_RESULT]
}
},
},
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
index 78f1e8ffb0b8..0136bba17d62 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithFunnelMetric.stories.tsx
@@ -31,14 +31,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(FUNNELS_METRIC_RESULT))
+ return [200, FUNNELS_METRIC_RESULT]
},
},
}),
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
index 53fbe339ebfc..28be378a5f2e 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyFunnelsQuery.stories.tsx
@@ -31,14 +31,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(FUNNELS_QUERY_RESULT))
+ return [200, FUNNELS_QUERY_RESULT]
},
},
}),
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
index 438ce4a0020f..13f0b7433055 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithLegacyTrendsQuery.stories.tsx
@@ -31,14 +31,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(TRENDS_QUERY_RESULT))
+ return [200, TRENDS_QUERY_RESULT]
},
},
}),
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
index bff2344c821c..31efb8d56a9e 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMeanMetric.stories.tsx
@@ -30,14 +30,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(MEAN_METRIC_RESULT))
+ return [200, MEAN_METRIC_RESULT]
},
},
}),
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
index 1bc25e86b2f1..3b63b6289cc1 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetrics.stories.tsx
@@ -39,19 +39,19 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
if (isExperimentFunnelMetric(body.query.metric)) {
- return res(ctx.json(FUNNEL_METRIC_RESULT))
+ return [200, FUNNEL_METRIC_RESULT]
} else if (isExperimentMeanMetric(body.query.metric)) {
- return res(ctx.json(MEAN_METRIC_RESULT))
+ return [200, MEAN_METRIC_RESULT]
} else if (isExperimentRatioMetric(body.query.metric)) {
- return res(ctx.json(RATIO_METRIC_RESULT))
+ return [200, RATIO_METRIC_RESULT]
}
},
},
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
index bf08e8fc7e44..210064807889 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithMultipleMetricsReordered.stories.tsx
@@ -40,19 +40,19 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
if (isExperimentFunnelMetric(body.query.metric)) {
- return res(ctx.json(FUNNEL_METRIC_RESULT))
+ return [200, FUNNEL_METRIC_RESULT]
} else if (isExperimentMeanMetric(body.query.metric)) {
- return res(ctx.json(MEAN_METRIC_RESULT))
+ return [200, MEAN_METRIC_RESULT]
} else if (isExperimentRatioMetric(body.query.metric)) {
- return res(ctx.json(RATIO_METRIC_RESULT))
+ return [200, RATIO_METRIC_RESULT]
}
},
},
diff --git a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
index 5046afb5f70a..e493119d419e 100644
--- a/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
+++ b/frontend/src/scenes/experiments/stories/ExperimentWithRatioMetric.stories.tsx
@@ -31,14 +31,14 @@ const meta: Meta = {
[`/api/environments/:team_id/default_release_conditions/`]: [],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === NodeKind.ExperimentExposureQuery) {
- return res(ctx.json(EXPOSURE_QUERY_RESULT))
+ return [200, EXPOSURE_QUERY_RESULT]
}
- return res(ctx.json(RATIO_METRIC_RESULT))
+ return [200, RATIO_METRIC_RESULT]
},
},
}),
diff --git a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
index a7c5d6fb1da5..39072e51dc73 100644
--- a/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/defaultEvaluationContextsLogic.test.ts
@@ -24,8 +24,8 @@ describe('defaultEvaluationContextsLogic', () => {
'/api/environments/:team_id/default_evaluation_contexts/': () => [200, mockResponse],
},
post: {
- '/api/environments/:team_id/default_evaluation_contexts/': async (req) => {
- const body = await req.json()
+ '/api/environments/:team_id/default_evaluation_contexts/': async ({ request }) => {
+ const body = (await request.json()) as any
const contextName = body.context_name
const newContext = {
id: Math.floor(Math.random() * 10000),
@@ -40,8 +40,8 @@ describe('defaultEvaluationContextsLogic', () => {
}
return [200, { ...newContext, created: true, hidden_from_suggestions: false }]
},
- '/api/environments/:team_id/evaluation_context_suggestions/': async (req) => {
- const body = await req.json()
+ '/api/environments/:team_id/evaluation_context_suggestions/': async ({ request }) => {
+ const body = (await request.json()) as any
const contextName = body.context_name
mockResponse.available_contexts = mockResponse.available_contexts.filter((c) => c !== contextName)
if (!mockResponse.hidden_contexts.includes(contextName)) {
@@ -52,15 +52,15 @@ describe('defaultEvaluationContextsLogic', () => {
},
},
delete: {
- '/api/environments/:team_id/default_evaluation_contexts/': (req) => {
- const contextName = req.url.searchParams.get('context_name')
+ '/api/environments/:team_id/default_evaluation_contexts/': ({ request }) => {
+ const contextName = new URL(request.url).searchParams.get('context_name')
mockResponse.default_evaluation_contexts = mockResponse.default_evaluation_contexts.filter(
(c) => c.name !== contextName
)
return [200, { success: true }]
},
- '/api/environments/:team_id/evaluation_context_suggestions/': (req) => {
- const contextName = req.url.searchParams.get('context_name')
+ '/api/environments/:team_id/evaluation_context_suggestions/': ({ request }) => {
+ const contextName = new URL(request.url).searchParams.get('context_name')
mockResponse.hidden_contexts = mockResponse.hidden_contexts.filter((c) => c !== contextName)
if (contextName && !mockResponse.available_contexts.includes(contextName)) {
mockResponse.available_contexts.push(contextName)
@@ -70,8 +70,8 @@ describe('defaultEvaluationContextsLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/': async (req) => {
- const body = await req.json()
+ '/api/environments/:team_id/': async ({ request }) => {
+ const body = (await request.json()) as any
return [200, { ...body }]
},
},
diff --git a/frontend/src/scenes/feature-flags/featureFlagConfirmationSettingsLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagConfirmationSettingsLogic.test.ts
index 0b134406d24c..323da903eaae 100644
--- a/frontend/src/scenes/feature-flags/featureFlagConfirmationSettingsLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagConfirmationSettingsLogic.test.ts
@@ -17,10 +17,10 @@ describe('featureFlagConfirmationSettingsLogic', () => {
lastCapturedPayload = null
useMocks({
patch: {
- '/api/environments/:id': async (req, res, ctx) => {
- lastCapturedPayload = await req.json()
+ '/api/environments/:id': async ({ request }) => {
+ lastCapturedPayload = await request.json()
const updatedTeam = { ...MOCK_DEFAULT_TEAM, ...lastCapturedPayload }
- return res(ctx.json(updatedTeam))
+ return [200, updatedTeam]
},
},
})
diff --git a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
index 4f961b6a1ef2..68a417e3e6f1 100644
--- a/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagLogic.test.ts
@@ -166,10 +166,6 @@ describe('featureFlagLogic', () => {
let logic: ReturnType<typeof featureFlagLogic.build>
beforeEach(async () => {
- initKeaTests()
- logic = featureFlagLogic({ id: 1 })
- logic.mount()
-
useMocks({
get: {
[`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${MOCK_FEATURE_FLAG.id}/`]: () => [
@@ -183,6 +179,10 @@ describe('featureFlagLogic', () => {
},
})
+ initKeaTests()
+ logic = featureFlagLogic({ id: 1 })
+ logic.mount()
+
await expectLogic(logic).toFinishAllListeners()
})
@@ -627,9 +627,6 @@ describe('featureFlagLogic', () => {
experiment_set_metadata: [{ id: MOCK_EXPERIMENT.id, name: MOCK_EXPERIMENT.name, is_running: true }],
}
- const experimentLogic = featureFlagLogic({ id: 2 })
- experimentLogic.mount()
-
useMocks({
get: {
[`/api/projects/${MOCK_DEFAULT_PROJECT.id}/feature_flags/${flagWithExperiment.id}/`]: () => [
@@ -647,10 +644,13 @@ describe('featureFlagLogic', () => {
},
})
- await expectLogic(experimentLogic, () => {
- experimentLogic.actions.loadFeatureFlag()
- })
- .toDispatchActions(['loadFeatureFlagSuccess', 'loadExperimentSuccess'])
+ const experimentLogic = featureFlagLogic({ id: 2 })
+ experimentLogic.mount()
+
+ // The loader awaits the experiment inline before returning the flag,
+ // so loadExperimentSuccess lands before loadFeatureFlagSuccess.
+ await expectLogic(experimentLogic)
+ .toDispatchActions(['loadFeatureFlag', 'loadExperimentSuccess', 'loadFeatureFlagSuccess'])
.toMatchValues({
featureFlag: partial({
id: flagWithExperiment.id,
diff --git a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
index 7bbf11e0185f..6faef8ab79ee 100644
--- a/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/featureFlagTestingLogic.test.ts
@@ -428,8 +428,8 @@ describe('featureFlagTestingLogic', () => {
let capturedBody: Record<string, any> = {}
useMocks({
post: {
- '/api/projects/:team/feature_flags/1/test_evaluation': async (req) => {
- capturedBody = await req.json()
+ '/api/projects/:team/feature_flags/1/test_evaluation': async ({ request }) => {
+ capturedBody = (await request.json()) as Record<string, any>
return [200, {}]
},
},
diff --git a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts
index d3d85c2a6bd7..7a20ce8061be 100644
--- a/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts
+++ b/frontend/src/scenes/feature-flags/projects-grid/projectsGridLogic.test.ts
@@ -30,8 +30,8 @@ describe('projectsGridLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/feature_flags/': (req) => {
- const offset = Number(req.url.searchParams.get('offset') ?? 0)
+ '/api/projects/:team/feature_flags/': ({ request }) => {
+ const offset = Number(new URL(request.url).searchParams.get('offset') ?? 0)
const count = 40
const remaining = Math.max(0, count - offset)
const pageSize = Math.min(25, remaining)
@@ -93,8 +93,8 @@ describe('projectsGridLogic', () => {
next: null,
results: [buildFlag(1), buildFlag(2), buildFlag(3)],
},
- '/api/organizations/:org/feature_flags/:key/': async (req) => {
- const key = req.params.key as string
+ '/api/organizations/:org/feature_flags/:key/': async ({ params }) => {
+ const key = params.key as string
callOrder.push(key)
inFlight += 1
maxInFlight = Math.max(maxInFlight, inFlight)
diff --git a/frontend/src/scenes/funnels/funnelPropertyCorrelationLogic.test.ts b/frontend/src/scenes/funnels/funnelPropertyCorrelationLogic.test.ts
index 6a4ba164e8c4..2b0e6a31666e 100644
--- a/frontend/src/scenes/funnels/funnelPropertyCorrelationLogic.test.ts
+++ b/frontend/src/scenes/funnels/funnelPropertyCorrelationLogic.test.ts
@@ -48,21 +48,24 @@ describe('funnelPropertyCorrelationLogic', () => {
},
},
patch: {
- '/api/environments/:id': (req) => [
- 200,
- {
- ...MOCK_DEFAULT_TEAM,
- correlation_config: {
- ...correlationConfig,
- excluded_person_property_names: (req.body as any)?.correlation_config
- ?.excluded_person_property_names,
+ '/api/environments/:id': async ({ request }) => {
+ const body = (await request.json()) as any
+ return [
+ 200,
+ {
+ ...MOCK_DEFAULT_TEAM,
+ correlation_config: {
+ ...correlationConfig,
+ excluded_person_property_names:
+ body?.correlation_config?.excluded_person_property_names,
+ },
},
- },
- ],
+ ]
+ },
},
post: {
- '/api/environments/:team_id/insights/funnel/correlation': (req) => {
- const data = req.body as any
+ '/api/environments/:team_id/insights/funnel/correlation': async ({ request }) => {
+ const data = (await request.json()) as any
const excludePropertyFromProjectNames = data?.funnel_correlation_exclude_names || []
const includePropertyNames = data?.funnel_correlation_names || []
return [
diff --git a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx
index a8fc4405c55e..9ad79153db16 100644
--- a/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx
+++ b/frontend/src/scenes/heatmaps/scenes/heatmap/HeatmapScene.stories.tsx
@@ -38,8 +38,7 @@ const meta: Meta = {
mswDecorator({
get: {
'/api/environments/:team_id/saved/hm_gen/': generatingSaved,
- '/api/environments/:team_id/heatmap_screenshots/:id/content/': (_req, res, ctx) =>
- res(ctx.status(202), ctx.json(generatingSaved)),
+ '/api/environments/:team_id/heatmap_screenshots/:id/content/': () => [202, generatingSaved],
},
}),
],
@@ -86,28 +85,26 @@ export const IframeExample: Story = {
decorators: [
mswDecorator({
get: {
- '/api/environments/:team_id/saved/hm_iframe/': (_req, res, ctx) =>
- res(ctx.status(200), ctx.json(makeIframeSaved())),
- '/api/projects/:team_id/heatmaps/': (_req, res, ctx) =>
- res(
- ctx.status(200),
- ctx.json({
- results: [
- { pointer_relative_x: 0.4, pointer_target_fixed: false, pointer_y: 355, count: 85 },
- { pointer_relative_x: 0.7, pointer_target_fixed: false, pointer_y: 24, count: 32 },
- { pointer_relative_x: 0.77, pointer_target_fixed: false, pointer_y: 24, count: 28 },
- { pointer_relative_x: 0.84, pointer_target_fixed: false, pointer_y: 24, count: 15 },
- { pointer_relative_x: 0.91, pointer_target_fixed: false, pointer_y: 24, count: 12 },
- { pointer_relative_x: 0.1, pointer_target_fixed: false, pointer_y: 24, count: 18 },
- { pointer_relative_x: 0.17, pointer_target_fixed: false, pointer_y: 395, count: 22 },
- { pointer_relative_x: 0.5, pointer_target_fixed: false, pointer_y: 395, count: 19 },
- { pointer_relative_x: 0.83, pointer_target_fixed: false, pointer_y: 395, count: 14 },
- ],
- count: 9,
- next: null,
- previous: null,
- })
- ),
+ '/api/environments/:team_id/saved/hm_iframe/': () => [200, makeIframeSaved()],
+ '/api/projects/:team_id/heatmaps/': () => [
+ 200,
+ {
+ results: [
+ { pointer_relative_x: 0.4, pointer_target_fixed: false, pointer_y: 355, count: 85 },
+ { pointer_relative_x: 0.7, pointer_target_fixed: false, pointer_y: 24, count: 32 },
+ { pointer_relative_x: 0.77, pointer_target_fixed: false, pointer_y: 24, count: 28 },
+ { pointer_relative_x: 0.84, pointer_target_fixed: false, pointer_y: 24, count: 15 },
+ { pointer_relative_x: 0.91, pointer_target_fixed: false, pointer_y: 24, count: 12 },
+ { pointer_relative_x: 0.1, pointer_target_fixed: false, pointer_y: 24, count: 18 },
+ { pointer_relative_x: 0.17, pointer_target_fixed: false, pointer_y: 395, count: 22 },
+ { pointer_relative_x: 0.5, pointer_target_fixed: false, pointer_y: 395, count: 19 },
+ { pointer_relative_x: 0.83, pointer_target_fixed: false, pointer_y: 395, count: 14 },
+ ],
+ count: 9,
+ next: null,
+ previous: null,
+ },
+ ],
},
}),
],
diff --git a/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx b/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
index e11bbf955a60..4496eb9d01ba 100644
--- a/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
+++ b/frontend/src/scenes/insights/EmptyStates/EmptyStates.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { delay, HttpResponse } from 'msw'
import { useDelayedOnMountEffect } from 'lib/hooks/useOnMountEffect'
import { App } from 'scenes/App'
@@ -30,11 +31,10 @@ export const Empty: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(200),
- ctx.json({ count: 1, results: [{ ...insight, result: [] }] }),
- ],
+ '/api/environments/:team_id/insights/': async () => {
+ await delay(100)
+ return HttpResponse.json({ count: 1, results: [{ ...insight, result: [] }] })
+ },
},
})
@@ -46,19 +46,20 @@ export const ServerError: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(200),
- ctx.json({ count: 1, results: [{ ...insight, result: null }] }),
- ],
- '/api/environments/:team_id/insights/:id': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(500),
- ctx.json({
- type: 'server_error',
- detail: 'There is nothing you can do to stop the impending catastrophe.',
- }),
- ],
+ '/api/environments/:team_id/insights/': async () => {
+ await delay(100)
+ return HttpResponse.json({ count: 1, results: [{ ...insight, result: null }] })
+ },
+ '/api/environments/:team_id/insights/:id': async () => {
+ await delay(100)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ detail: 'There is nothing you can do to stop the impending catastrophe.',
+ },
+ { status: 500 }
+ )
+ },
},
})
@@ -70,24 +71,25 @@ export const QueryServerError: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(200),
- ctx.json({
+ '/api/environments/:team_id/insights/': async () => {
+ await delay(100)
+ return HttpResponse.json({
count: 1,
results: [insight],
- }),
- ],
+ })
+ },
},
post: {
- '/api/environments/:team_id/query/:kind/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(500),
- ctx.json({
- type: 'server_error',
- detail: 'There is nothing you can do to stop the impending catastrophe.',
- }),
- ],
+ '/api/environments/:team_id/query/:kind/': async () => {
+ await delay(100)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ detail: 'There is nothing you can do to stop the impending catastrophe.',
+ },
+ { status: 500 }
+ )
+ },
},
})
@@ -104,21 +106,22 @@ export const ValidationError: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(200),
- ctx.json({ count: 1, results: [{ ...insight, result: null }] }),
- ],
+ '/api/environments/:team_id/insights/': async () => {
+ await delay(100)
+ return HttpResponse.json({ count: 1, results: [{ ...insight, result: null }] })
+ },
},
post: {
- '/api/environments/:team_id/insights/:id': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(400),
- ctx.json({
- type: 'validation_error',
- detail: 'You forgot to hug the person next to you. Please do that now.',
- }),
- ],
+ '/api/environments/:team_id/insights/:id': async () => {
+ await delay(100)
+ return HttpResponse.json(
+ {
+ type: 'validation_error',
+ detail: 'You forgot to hug the person next to you. Please do that now.',
+ },
+ { status: 400 }
+ )
+ },
},
})
@@ -130,20 +133,22 @@ export const EstimatedQueryExecutionTimeTooLong: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ count: 1, results: [{ ...insight, result: null }] }),
+ '/api/environments/:team_id/insights/': () => [
+ 200,
+ { count: 1, results: [{ ...insight, result: null }] },
],
},
post: {
- '/api/environments/:team_id/query/:kind/': (_, __, ctx) => [
- ctx.delay(100),
- ctx.status(512),
- ctx.json({
- type: 'server_error',
- detail: 'Estimated query execution time is too long. Try reducing its scope by changing the time range.',
- }),
- ],
+ '/api/environments/:team_id/query/:kind/': async () => {
+ await delay(100)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ detail: 'Estimated query execution time is too long. Try reducing its scope by changing the time range.',
+ },
+ { status: 512 }
+ )
+ },
},
})
@@ -161,13 +166,16 @@ export const LongLoading: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({ count: 1, results: [{ ...insight, result: null }] }),
+ '/api/environments/:team_id/insights/': () => [
+ 200,
+ { count: 1, results: [{ ...insight, result: null }] },
],
},
post: {
- '/api/environments/:team_id/query/:kind/': (_, __, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/query/:kind/': async () => {
+ await delay('infinite')
+ return HttpResponse.json({})
+ },
},
})
diff --git a/frontend/src/scenes/insights/__mocks__/createInsightScene.tsx b/frontend/src/scenes/insights/__mocks__/createInsightScene.tsx
index aa9cae6b048b..8bfa97d9a9e5 100644
--- a/frontend/src/scenes/insights/__mocks__/createInsightScene.tsx
+++ b/frontend/src/scenes/insights/__mocks__/createInsightScene.tsx
@@ -57,9 +57,9 @@ export function createInsightStory(
useStorybookMocks({
get: {
- '/api/environments/:team_id/insights/': (_, __, ctx) => [
- ctx.status(200),
- ctx.json({
+ '/api/environments/:team_id/insights/': () => [
+ 200,
+ {
count: 1,
results: [
{
@@ -69,14 +69,14 @@ export function createInsightStory(
query: setLegendFilter(insight.query, showLegend),
},
],
- }),
+ },
],
},
post: {
- '/api/environments/:team_id/query/:kind/': (req, __, ctx) => [
- ctx.status(200),
- ctx.json({
- cache_key: req.params.query,
+ '/api/environments/:team_id/query/:kind/': ({ params }) => [
+ 200,
+ {
+ cache_key: params.query,
calculation_trigger: null,
error: '',
hasMore: false,
@@ -86,7 +86,7 @@ export function createInsightStory(
// sql insights
columns: (insight as any).columns,
types: (insight as any).types,
- }),
+ },
],
},
})
diff --git a/frontend/src/scenes/insights/insightLogic.test.ts b/frontend/src/scenes/insights/insightLogic.test.ts
index 7e580b9351da..a44829b8ccfe 100644
--- a/frontend/src/scenes/insights/insightLogic.test.ts
+++ b/frontend/src/scenes/insights/insightLogic.test.ts
@@ -144,16 +144,17 @@ describe('insightLogic', () => {
'/api/environments/:team_id/quick_filters/': {
results: [],
},
- '/api/environments/:team_id/insights/trend/': async (req) => {
- const clientQueryId = req.url.searchParams.get('client_query_id')
+ '/api/environments/:team_id/insights/trend/': async ({ request }) => {
+ const url = new URL(request.url)
+ const clientQueryId = url.searchParams.get('client_query_id')
if (clientQueryId !== null) {
seenQueryIDs.push(clientQueryId)
}
- if (JSON.parse(req.url.searchParams.get('events') || '[]')?.[0]?.throw) {
+ if (JSON.parse(url.searchParams.get('events') || '[]')?.[0]?.throw) {
return [500, { status: 0, detail: 'error from the API' }]
}
- if (req.url.searchParams.get('date_from') === '-180d') {
+ if (url.searchParams.get('date_from') === '-180d') {
// delay for 2 seconds before response without pausing
return new Promise<[number, { result: string[] }]>((resolve) =>
setTimeout(() => {
@@ -170,8 +171,9 @@ describe('insightLogic', () => {
'/api/environments/:team_id/insights/42': partialInsight42,
'/api/environments/:team_id/insights/43/': partialInsight43,
'/api/environments/:team_id/insights/44/': partialInsight44,
- '/api/environments/:team_id/insights/': (req) => {
- if (req.url.searchParams.get('saved')) {
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('saved')) {
return [
200,
{
@@ -189,7 +191,7 @@ describe('insightLogic', () => {
},
]
}
- const shortId = req.url.searchParams.get('short_id') || ''
+ const shortId = url.searchParams.get('short_id') || ''
if (shortId === '500') {
return [500, { status: 0, detail: 'error from the API' }]
}
@@ -201,7 +203,7 @@ describe('insightLogic', () => {
result: parseInt(shortId) === 42 ? ['result from api'] : null,
id: parseInt(shortId),
short_id: shortId.toString(),
- filters: JSON.parse(req.url.searchParams.get('filters') || 'false') || API_FILTERS,
+ filters: JSON.parse(url.searchParams.get('filters') || 'false') || API_FILTERS,
name: 'original name',
dashboards: [1, 2, 3],
},
@@ -247,25 +249,25 @@ describe('insightLogic', () => {
post: {
'/api/environments/:team_id/insights/funnel/': { result: ['result from api'] },
'/api/environments/:team_id/insights/viewed': [201],
- '/api/environments/:team_id/insights/': (req) => [
+ '/api/environments/:team_id/insights/': async ({ request }) => [
200,
- { ...(req.body as any), id: 12, short_id: Insight12 },
+ { ...((await request.json()) as any), id: 12, short_id: Insight12 },
],
'/api/environments/997/insights/cancel/': [201],
},
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request, params }) => {
+ const payload = (await request.json()) as Record<string, any>
const response = patchResponseFor(
payload,
- req.params['id'] as string,
- JSON.parse(req.url.searchParams.get('filters') || 'false')
+ params.id as string,
+ JSON.parse(new URL(request.url).searchParams.get('filters') || 'false')
)
return [200, response]
},
- '/api/projects/:team/insights/:id': async (req) => {
- const payload = await req.json()
- return [200, { ...payload, id: req.params['id'] }]
+ '/api/projects/:team/insights/:id': async ({ request, params }) => {
+ const payload = (await request.json()) as Record<string, any>
+ return [200, { ...payload, id: params.id }]
},
},
})
@@ -1099,8 +1101,8 @@ describe('insightLogic', () => {
it('syncs favorited to savedInsight on metadata save', async () => {
useMocks({
patch: {
- '/api/environments/:team_id/insights/:id': async (req) => {
- const payload = await req.json()
+ '/api/environments/:team_id/insights/:id': async ({ request }) => {
+ const payload = (await request.json()) as Record<string, any>
return [
200,
{
diff --git a/frontend/src/scenes/insights/insightSceneLogic.test.ts b/frontend/src/scenes/insights/insightSceneLogic.test.ts
index 20d7a12f960f..59eedcb5a670 100644
--- a/frontend/src/scenes/insights/insightSceneLogic.test.ts
+++ b/frontend/src/scenes/insights/insightSceneLogic.test.ts
@@ -30,9 +30,9 @@ describe('insightSceneLogic', () => {
},
post: {
'/api/environments/:team_id/insights/funnel/': { result: ['result from api'] },
- '/api/environments/:team_id/insights/': (req) => [
+ '/api/environments/:team_id/insights/': async ({ request }) => [
200,
- { id: 12, short_id: Insight12, ...(req.body as any) },
+ { id: 12, short_id: Insight12, ...((await request.json()) as any) },
],
'/api/environments/:team_id/query/upgrade/': { query: {} },
},
@@ -208,8 +208,8 @@ describe('insightSceneLogic', () => {
useMocks({
get: {
'/api/environments/:team_id/insights/trend/': { result: ['result from api'] },
- '/api/environments/:team_id/insights/': (req) => {
- const shortId = req.url.searchParams.get('short_id') || ''
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const shortId = new URL(request.url).searchParams.get('short_id') || ''
const id = shortId === '12' ? 12 : 42
const sid = (shortId === '12' ? Insight12 : Insight42) as InsightShortId
return [
@@ -229,9 +229,9 @@ describe('insightSceneLogic', () => {
},
post: {
'/api/environments/:team_id/insights/funnel/': { result: ['result from api'] },
- '/api/environments/:team_id/insights/': (req) => [
+ '/api/environments/:team_id/insights/': async ({ request }) => [
200,
- { id: 12, short_id: Insight12, ...(req.body as any) },
+ { id: 12, short_id: Insight12, ...((await request.json()) as any) },
],
'/api/environments/:team_id/query/upgrade/': { query: {} },
},
diff --git a/frontend/src/scenes/max/Max.stories.tsx b/frontend/src/scenes/max/Max.stories.tsx
index 93725631ddd7..7a2bf193ccf8 100644
--- a/frontend/src/scenes/max/Max.stories.tsx
+++ b/frontend/src/scenes/max/Max.stories.tsx
@@ -13,6 +13,7 @@ import { MOCK_DEFAULT_BASIC_USER, MOCK_DEFAULT_ORGANIZATION } from 'lib/api.mock
import { Meta, StoryObj } from '@storybook/react'
import { useActions, useValues } from 'kea'
+import { HttpResponse, delay } from 'msw'
import { useEffect } from 'react'
import { twMerge } from 'tailwind-merge'
@@ -46,7 +47,7 @@ const meta: Meta = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) => res(ctx.text(chatResponseChunk)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(chatResponseChunk),
},
get: {
'/api/organizations/@current/': () => [
@@ -155,7 +156,10 @@ export const EmptyThreadLoading: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_req, _res, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/conversations/': async () => {
+ await delay('infinite')
+ return new HttpResponse()
+ },
},
})
@@ -194,7 +198,7 @@ export const GenerationFailureThread: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) => res(ctx.text(generationFailureChunk)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(generationFailureChunk),
},
})
@@ -234,7 +238,7 @@ export const ThreadWithFailedGeneration: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) => res(ctx.text(failureChunk)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(failureChunk),
},
})
@@ -268,9 +272,9 @@ export const ThreadWithRateLimit: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- // Retry-After header is present so we should be showing its value in the UI
- res(ctx.text(chatResponseChunk), ctx.set({ 'Retry-After': '3899' }), ctx.status(429)),
+ // Retry-After header is present so we should be showing its value in the UI
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(chatResponseChunk, { status: 429, headers: { 'Retry-After': '3899' } }),
},
})
@@ -304,9 +308,8 @@ export const ThreadWithRateLimitNoRetryAfter: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- // Testing rate limit error when the Retry-After header is MISSING
- res(ctx.text(chatResponseChunk), ctx.status(429)),
+ // Testing rate limit error when the Retry-After header is MISSING
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(chatResponseChunk, { status: 429 }),
},
})
@@ -340,14 +343,13 @@ export const ThreadWithBillingLimitExceeded: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- // Testing billing limit exceeded error (402 Payment Required)
- res(
- ctx.status(402),
- ctx.json({
- detail: 'Your organization reached its AI credit usage limit. Increase the limits in [Billing](/organization/billing), or ask an org admin to do so.',
- })
- ),
+ // Testing billing limit exceeded error (402 Payment Required)
+ '/api/environments/:team_id/conversations/': () => [
+ 402,
+ {
+ detail: 'Your organization reached its AI credit usage limit. Increase the limits in [Billing](/organization/billing), or ask an org admin to do so.',
+ },
+ ],
},
})
@@ -381,7 +383,7 @@ export const ThreadWithQuickReplies: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) => res(ctx.text(formChunk)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(formChunk),
},
})
@@ -415,7 +417,10 @@ export const ThreadWithConversationLoading: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/conversations/': (_req, _res, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/conversations/': async () => {
+ await delay('infinite')
+ return new HttpResponse()
+ },
},
})
@@ -515,7 +520,10 @@ export const ThreadWithInProgressConversation: Story = {
useStorybookMocks({
get: {
'/api/environments/:team_id/conversations/': () => [200, conversationList],
- '/api/environments/:team_id/conversations/in_progress/': (_req, _res, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/conversations/in_progress/': async () => {
+ await delay('infinite')
+ return new HttpResponse()
+ },
},
})
@@ -601,7 +609,10 @@ export const ChatHistoryLoading: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/environments/:team_id/conversations/': (_req, _res, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/conversations/': async () => {
+ await delay('infinite')
+ return new HttpResponse()
+ },
},
})
@@ -712,8 +723,10 @@ export const ThreadScrollsToBottomOnNewMessages: Story = {
'/api/environments/:team_id/conversations/': () => [200, conversationList],
},
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(ctx.delay(100), ctx.text(longResponseChunk)),
+ '/api/environments/:team_id/conversations/': async () => {
+ await delay(100)
+ return new HttpResponse(longResponseChunk)
+ },
},
})
@@ -751,8 +764,7 @@ export const ChatWithUIContext: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(ctx.text(chatResponseWithEventContext)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(chatResponseWithEventContext),
},
get: {
'/api/environments/:team_id/conversations/': () => [200, conversationList],
@@ -872,21 +884,19 @@ export const PlanningComponent: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Create a comprehensive analysis plan',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(planningMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Create a comprehensive analysis plan',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(planningMessage)}`,
+ ])
),
},
})
@@ -936,18 +946,16 @@ export const ReasoningComponent: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({ ...humanMessage, content: 'Analyze user engagement' })}`,
- 'event: message',
- `data: ${JSON.stringify(reasoningMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({ ...humanMessage, content: 'Analyze user engagement' })}`,
+ 'event: message',
+ `data: ${JSON.stringify(reasoningMessage)}`,
+ ])
),
},
})
@@ -1072,34 +1080,35 @@ export const TaskExecutionComponent: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: 'in_progress' })}`,
- 'event: message',
- `data: ${JSON.stringify({ ...humanMessage, content: 'Execute analysis tasks' })}`,
- 'event: message',
- `data: ${JSON.stringify(taskExecutionMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallCompletion1)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallCompletion2)}`,
- 'event: update',
- `data: ${JSON.stringify(updateMessages[0])}`,
- 'event: update',
- `data: ${JSON.stringify(updateMessages[1])}`,
- 'event: update',
- `data: ${JSON.stringify(updateMessages[2])}`,
- 'event: update',
- `data: ${JSON.stringify(updateMessages[3])}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: 'in_progress' })}`,
+ 'event: message',
+ `data: ${JSON.stringify({ ...humanMessage, content: 'Execute analysis tasks' })}`,
+ 'event: message',
+ `data: ${JSON.stringify(taskExecutionMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallCompletion1)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallCompletion2)}`,
+ 'event: update',
+ `data: ${JSON.stringify(updateMessages[0])}`,
+ 'event: update',
+ `data: ${JSON.stringify(updateMessages[1])}`,
+ 'event: update',
+ `data: ${JSON.stringify(updateMessages[2])}`,
+ 'event: update',
+ `data: ${JSON.stringify(updateMessages[3])}`,
+ ])
),
},
get: {
- '/api/environments/:team_id/conversations/in_progress/': (_req, _res, ctx) => [ctx.delay('infinite')],
+ '/api/environments/:team_id/conversations/in_progress/': async () => {
+ await delay('infinite')
+ return new HttpResponse()
+ },
},
})
@@ -1203,27 +1212,25 @@ export const TaskExecutionWithFailure: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Execute analysis with some failures',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(taskExecutionMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallCompletion1)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallCompletion2)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallCompletion3)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Execute analysis with some failures',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(taskExecutionMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallCompletion1)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallCompletion2)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallCompletion3)}`,
+ ])
),
},
})
@@ -1268,7 +1275,7 @@ export const MultiVisualizationInThread: Story = {
hogql: 'SELECT count() FROM events',
},
],
- '/api/environments/:team_id/conversations/': (_, res, ctx) => {
+ '/api/environments/:team_id/conversations/': () => {
const humanMsg = {
type: AssistantMessageType.Human,
content: 'Analyze our product metrics comprehensively',
@@ -1322,20 +1329,18 @@ export const MultiVisualizationInThread: Story = {
- Apply dashboard rollout strategy to future features`,
}
- return res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMsg,
- content: 'Analyze our product metrics comprehensively',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiVizMessage)}`,
- ])
- )
+ return new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMsg,
+ content: 'Analyze our product metrics comprehensively',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiVizMessage)}`,
+ ])
)
},
},
@@ -1371,7 +1376,7 @@ export const ThreadWithSQLQueryOverflow: Story = {
render: () => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) => res(ctx.text(sqlQueryResponseChunk)),
+ '/api/environments/:team_id/conversations/': () => new HttpResponse(sqlQueryResponseChunk),
},
})
@@ -1475,24 +1480,22 @@ export const SearchSessionRecordingsEmpty: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content:
- 'Show me recordings where users are on Chrome with Mac OR Firefox with Windows',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallResult)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content:
+ 'Show me recordings where users are on Chrome with Mac OR Firefox with Windows',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallResult)}`,
+ ])
),
},
})
@@ -1583,23 +1586,21 @@ export const SearchSessionRecordingsWithResults: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Show me recordings where users are on Microsoft Edge with Linux',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallResult)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Show me recordings where users are on Microsoft Edge with Linux',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallResult)}`,
+ ])
),
},
})
@@ -1631,8 +1632,8 @@ export const SearchSessionRecordingsWithResults: Story = {
decorators: [
mswDecorator({
get: {
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [
200,
{
@@ -1689,23 +1690,21 @@ export const SearchErrorTrackingIssuesEmpty: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Show me active payment errors from the last week',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallResult)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Show me active payment errors from the last week',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallResult)}`,
+ ])
),
},
})
@@ -1818,24 +1817,22 @@ export const SearchErrorTrackingIssuesWithResults: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content:
- 'Show me all payment-related errors from the last month, sorted by occurrences',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallResult)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content:
+ 'Show me all payment-related errors from the last month, sorted by occurrences',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallResult)}`,
+ ])
),
},
})
@@ -1923,23 +1920,21 @@ export const DangerousOperationPendingApproval: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Update my Sales Analytics dashboard with new metrics',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: approval',
- `data: ${JSON.stringify(pendingApproval)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Update my Sales Analytics dashboard with new metrics',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: approval',
+ `data: ${JSON.stringify(pendingApproval)}`,
+ ])
),
},
get: {
@@ -2117,23 +2112,21 @@ The following services will need to be notified:
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Run the database migration',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(toolCallMessage)}`,
- 'event: approval',
- `data: ${JSON.stringify(pendingApproval)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Run the database migration',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(toolCallMessage)}`,
+ 'event: approval',
+ `data: ${JSON.stringify(pendingApproval)}`,
+ ])
),
},
get: {
@@ -2247,21 +2240,19 @@ export const ThreadWithMultiQuestionForm: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Help me get started with PostHog',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Help me get started with PostHog',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiQuestionFormMessage)}`,
+ ])
),
},
})
@@ -2345,21 +2336,19 @@ export const ThreadWithMultiFieldQuestion: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Help me set up an A/B test',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Help me set up an A/B test',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiQuestionFormMessage)}`,
+ ])
),
},
})
@@ -2429,21 +2418,19 @@ export const ThreadWithSingleQuestionForm: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'What pricing plan should I choose?',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(singleQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'What pricing plan should I choose?',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(singleQuestionFormMessage)}`,
+ ])
),
},
})
@@ -2583,22 +2570,20 @@ export const ThreadWithMultiQuestionFormLongContent: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content:
- 'Can you help me understand why our user retention has been declining? I need a comprehensive analysis.',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(longContentFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content:
+ 'Can you help me understand why our user retention has been declining? I need a comprehensive analysis.',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(longContentFormMessage)}`,
+ ])
),
},
})
@@ -2685,21 +2670,19 @@ export const ThreadWithMultiQuestionFormNoCustomAnswer: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Help me prioritize my analytics work',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(formMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Help me prioritize my analytics work',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(formMessage)}`,
+ ])
),
},
})
@@ -2775,21 +2758,19 @@ export const NotebookArtifactMarkdownOnly: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Create a retention analysis notebook',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(notebookArtifactMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Create a retention analysis notebook',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(notebookArtifactMessage)}`,
+ ])
),
},
})
@@ -2868,21 +2849,19 @@ export const NotebookArtifactWithVisualizations: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Create a dashboard analysis notebook with charts',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(notebookArtifactMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Create a dashboard analysis notebook with charts',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(notebookArtifactMessage)}`,
+ ])
),
},
})
@@ -2982,21 +2961,19 @@ export const NotebookArtifactMixedContent: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Create a comprehensive product analysis notebook',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(notebookArtifactMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Create a comprehensive product analysis notebook',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(notebookArtifactMessage)}`,
+ ])
),
},
})
@@ -3080,21 +3057,19 @@ export const NotebookArtifactWithLoadingAndErrors: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Show me an analysis with loading and error states',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(notebookArtifactMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Show me an analysis with loading and error states',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(notebookArtifactMessage)}`,
+ ])
),
},
})
@@ -3232,21 +3207,19 @@ export const ThreadWithMixedFieldTypeForm: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Help me set up analytics for my team',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Help me set up analytics for my team',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiQuestionFormMessage)}`,
+ ])
),
},
})
@@ -3332,21 +3305,19 @@ export const ThreadWithTextAndNumberForm: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'I want to set up event tracking for my project',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'I want to set up event tracking for my project',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiQuestionFormMessage)}`,
+ ])
),
},
})
@@ -3414,21 +3385,19 @@ export const ThreadWithSliderForm: Story = {
useStorybookMocks({
post: {
- '/api/environments/:team_id/conversations/': (_, res, ctx) =>
- res(
- ctx.text(
- generateChunk([
- 'event: conversation',
- `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
- 'event: message',
- `data: ${JSON.stringify({
- ...humanMessage,
- content: 'Help me set up an A/B test experiment',
- })}`,
- 'event: message',
- `data: ${JSON.stringify(multiQuestionFormMessage)}`,
- ])
- )
+ '/api/environments/:team_id/conversations/': () =>
+ new HttpResponse(
+ generateChunk([
+ 'event: conversation',
+ `data: ${JSON.stringify({ id: CONVERSATION_ID })}`,
+ 'event: message',
+ `data: ${JSON.stringify({
+ ...humanMessage,
+ content: 'Help me set up an A/B test experiment',
+ })}`,
+ 'event: message',
+ `data: ${JSON.stringify(multiQuestionFormMessage)}`,
+ ])
),
},
})
diff --git a/frontend/src/scenes/max/maxThreadLogic.test.ts b/frontend/src/scenes/max/maxThreadLogic.test.ts
index 2ed6cfc0002a..1f6e24e6d0e4 100644
--- a/frontend/src/scenes/max/maxThreadLogic.test.ts
+++ b/frontend/src/scenes/max/maxThreadLogic.test.ts
@@ -64,6 +64,12 @@ describe('maxThreadLogic', () => {
get: {
...maxMocks.get,
'/api/environments/:team_id/conversations/:conversation_id/': MOCK_IN_PROGRESS_CONVERSATION,
+ // loadQueueData fires on mount; without a shaped default it hits the empty-response
+ // floor (no `messages`/`max_queue_messages`) and the queue reducers reduce to undefined.
+ '/api/environments/:team_id/conversations/:conversation_id/queue': {
+ messages: [],
+ max_queue_messages: 0,
+ },
},
})
initKeaTests()
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.test.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.test.ts
index f54c602be897..db6be0c6fbec 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.test.ts
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.test.ts
@@ -147,10 +147,10 @@ describe('notebookNodePersonFeedLogic', () => {
[`/api/environments/${MOCK_TEAM_ID}/query/:kind/`]: {
results: mockSessionsWithRecording,
},
- [`/api/environments/${MOCK_TEAM_ID}/session_summaries/create_session_summaries_individually`]: async (
- req: any
- ) => {
- const { session_ids } = await req.json()
+ [`/api/environments/${MOCK_TEAM_ID}/session_summaries/create_session_summaries_individually`]: async ({
+ request,
+ }) => {
+ const { session_ids } = (await request.json()) as Record<string, any>
const sessionId = session_ids[0]
if (failingSessionIds.includes(sessionId)) {
return [500, { detail: 'Server error' }]
diff --git a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
index 9892296b16c6..3e92f3b094b6 100644
--- a/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
+++ b/frontend/src/scenes/notebooks/Nodes/NotebookNodePersonFeed/notebookNodePersonFeedLogic.ts
@@ -33,7 +33,7 @@ export const notebookNodePersonFeedLogic = kea<notebookNodePersonFeedLogicType>(
setSummarizingState: (state: 'idle' | 'loading' | 'completed') => ({ state }),
}),
- loaders(({ values, props }) => ({
+ loaders(({ props }) => ({
sessions: [
null as SessionsTimelineQueryResponse['results'] | null,
{
@@ -49,14 +49,16 @@ export const notebookNodePersonFeedLogic = kea<notebookNodePersonFeedLogicType>(
},
},
],
- summaries: [
- {} as Record<string, SessionSummaryContent>,
+ // Loader drives the per-session request and the summarizeSession{,Success,Failure} actions.
+ // Accumulation lives in the `summaries` reducer below so concurrent requests can't race on a
+ // read-modify-write of the shared map (the last response would otherwise clobber the others).
+ sessionSummary: [
+ null as Record<string, SessionSummaryContent> | null,
{
summarizeSession: async ({ sessionId }) => {
- const response = await api.sessionSummaries.createIndividual({
+ return await api.sessionSummaries.createIndividual({
session_ids: [sessionId],
})
- return { ...values.summaries, ...response }
},
},
],
@@ -79,6 +81,12 @@ export const notebookNodePersonFeedLogic = kea<notebookNodePersonFeedLogicType>(
})),
reducers(() => ({
+ summaries: [
+ {} as Record<string, SessionSummaryContent>,
+ {
+ summarizeSessionSuccess: (state, { sessionSummary }) => ({ ...state, ...sessionSummary }),
+ },
+ ],
summarizingState: [
'idle' as 'idle' | 'loading' | 'completed',
{
@@ -102,6 +110,7 @@ export const notebookNodePersonFeedLogic = kea<notebookNodePersonFeedLogicType>(
(sessionIdsWithRecording) => sessionIdsWithRecording.length,
],
numSummaries: [(s) => [s.summaries], (summaries) => Object.keys(summaries).length],
+ summariesLoading: [(s) => [s.sessionSummaryLoading], (sessionSummaryLoading) => sessionSummaryLoading],
numFailedSummaries: [(s) => [s.summaryErrors], (summaryErrors) => summaryErrors.length],
numProcessedSessions: [
(s) => [s.numSummaries, s.numFailedSummaries],
diff --git a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx b/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
index dce5caf9c628..648ef9009026 100644
--- a/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
+++ b/frontend/src/scenes/notebooks/Nodes/utils.test.tsx
@@ -55,7 +55,7 @@ describe('notebook node utils', () => {
})
})
- it('should do nothing if an attribute is unchanged', () => {
+ it('should do nothing if an attribute is unchanged', async () => {
const { result } = renderHook(() => useSyncedAttributes(nodeViewProps))
expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()
@@ -70,7 +70,7 @@ describe('notebook node utils', () => {
})
})
- jest.runOnlyPendingTimers()
+ await jest.runOnlyPendingTimersAsync()
expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()
@@ -79,7 +79,7 @@ describe('notebook node utils', () => {
})
})
- it('should call the update attributes function if changed', () => {
+ it('should call the update attributes function if changed', async () => {
const { result, rerender } = renderHook(() => useSyncedAttributes(nodeViewProps))
expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()
@@ -90,7 +90,7 @@ describe('notebook node utils', () => {
})
})
- jest.runOnlyPendingTimers()
+ await jest.runOnlyPendingTimersAsync()
expect(nodeViewProps.updateAttributes).toHaveBeenCalledWith({
foo: 'bar2',
@@ -103,7 +103,7 @@ describe('notebook node utils', () => {
})
})
- it('should stringify and parse content', () => {
+ it('should stringify and parse content', async () => {
harness.node.attrs = {
filters: { my: 'data' },
number: 1,
@@ -126,7 +126,7 @@ describe('notebook node utils', () => {
})
})
- jest.runOnlyPendingTimers()
+ await jest.runOnlyPendingTimersAsync()
expect(nodeViewProps.updateAttributes).toHaveBeenCalledWith({
filters: '{"my":"changed data"}',
@@ -152,7 +152,7 @@ describe('notebook node utils', () => {
})
})
- jest.runOnlyPendingTimers()
+ await jest.runOnlyPendingTimersAsync()
expect(nodeViewProps.updateAttributes).not.toHaveBeenCalled()
})
})
diff --git a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
index 9b1e184600ba..599eb5235852 100644
--- a/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
+++ b/frontend/src/scenes/notebooks/Notebook/migrations/migrate.test.ts
@@ -12,8 +12,8 @@ describe('migrate()', () => {
beforeEach(() => {
useMocks({
post: {
- '/api/environments/:team_id/query/upgrade': (req) => {
- const data = req.body as any
+ '/api/environments/:team_id/query/upgrade': async ({ request }) => {
+ const data = (await request.json()) as any
if (data?.query?.source?.kind === 'RetentionQuery') {
return [
200,
diff --git a/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.stories.tsx b/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.stories.tsx
index 065c3d1a1777..5cc03afe4535 100644
--- a/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.stories.tsx
+++ b/frontend/src/scenes/notebooks/NotebookSelectButton/NotebookSelectButton.stories.tsx
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react'
+import { delay, HttpResponse } from 'msw'
import {
NotebookSelectButton,
@@ -49,8 +50,8 @@ const allNotebooks = [
const renderNotebookSelect = (props: any): JSX.Element => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/notebooks/': (req, res, ctx) => {
- const contains = req.url.searchParams.get('contains')
+ '/api/projects/:team_id/notebooks/': async ({ request }) => {
+ const contains = new URL(request.url).searchParams.get('contains')
const sessionRecordingId = contains?.split(':')[1]
const unfiltered = contains == null && sessionRecordingId === undefined
@@ -67,7 +68,8 @@ const renderNotebookSelect = (props: any): JSX.Element => {
}
if (sessionRecordingId === 'very_slow') {
- return res(ctx.delay('infinite'), ctx.status(200), ctx.json({ count: 0, results: [] }))
+ await delay('infinite')
+ return HttpResponse.json({ count: 0, results: [] })
}
},
},
diff --git a/frontend/src/scenes/persons-management/Persons.stories.tsx b/frontend/src/scenes/persons-management/Persons.stories.tsx
index 6477f8f7287d..40e7a7eaabfa 100644
--- a/frontend/src/scenes/persons-management/Persons.stories.tsx
+++ b/frontend/src/scenes/persons-management/Persons.stories.tsx
@@ -25,8 +25,8 @@ export const Persons: Story = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- const query = (req.body as any)?.query
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const query = ((await request.json()) as any)?.query
// Check if it's a DataTableNode query, which is used for Events/Exceptions tabs
if (query && query.kind === 'ActorsQuery') {
return [
diff --git a/frontend/src/scenes/persons/PersonScene.stories.tsx b/frontend/src/scenes/persons/PersonScene.stories.tsx
index 0b305d793c62..55c72c5b85b7 100644
--- a/frontend/src/scenes/persons/PersonScene.stories.tsx
+++ b/frontend/src/scenes/persons/PersonScene.stories.tsx
@@ -89,8 +89,8 @@ const meta: Meta = {
},
},
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- const query = (req.body as any)?.query
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const query = ((await request.json()) as any)?.query
// Check if it's a DataTableNode query, which is used for Events/Exceptions tabs
if (
query &&
diff --git a/frontend/src/scenes/persons/personsLogic.test.ts b/frontend/src/scenes/persons/personsLogic.test.ts
index b7f3be364722..35a8c12000e2 100644
--- a/frontend/src/scenes/persons/personsLogic.test.ts
+++ b/frontend/src/scenes/persons/personsLogic.test.ts
@@ -16,11 +16,12 @@ import { personsLogic } from './personsLogic'
describe('personsLogic', () => {
let logic: ReturnType<typeof personsLogic.build>
- const mockPersonsApiHandler: MockSignature = (req) => {
- if (['+', 'abc', 'xyz'].includes(req.url.searchParams.get('distinct_id') ?? '')) {
+ const mockPersonsApiHandler: MockSignature = ({ request }) => {
+ const url = new URL(request.url)
+ if (['+', 'abc', 'xyz'].includes(url.searchParams.get('distinct_id') ?? '')) {
return [200, { results: ['person from api'] }]
}
- if (['[email protected]'].includes(req.url.searchParams.get('distinct_id') ?? '')) {
+ if (['[email protected]'].includes(url.searchParams.get('distinct_id') ?? '')) {
return [
200,
{
diff --git a/frontend/src/scenes/project-homepage/ProjectHomepage.stories.tsx b/frontend/src/scenes/project-homepage/ProjectHomepage.stories.tsx
index c42230e88b18..2ebe79ad7fa8 100644
--- a/frontend/src/scenes/project-homepage/ProjectHomepage.stories.tsx
+++ b/frontend/src/scenes/project-homepage/ProjectHomepage.stories.tsx
@@ -10,6 +10,7 @@ import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
import { EMPTY_PAGINATED_RESPONSE } from '~/mocks/handlers'
+import type { MockResolverInfo } from '~/mocks/utils'
const dashboardRaw = require('../dashboard/__mocks__/dashboard1.json')
// Mark all tiles as cached to prevent refresh attempts in storybook
@@ -41,8 +42,8 @@ const insightMocks = dashboard.tiles.reduce((acc: Record<string, any>, tile: any
}, {})
// Add the generic insight fetching endpoint that requires from_dashboard param
-const insightFetchMock = (req: any): [number, any] => {
- const insightId = req.params.id
+const insightFetchMock = ({ params }: MockResolverInfo): [number, any] => {
+ const insightId = params.id
// Don't require from_dashboard in storybook to simplify things
// Find the insight in the dashboard tiles
diff --git a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
index 0fcf790fcb33..d056b1ab7198 100644
--- a/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
+++ b/frontend/src/scenes/saved-insights/SavedInsightsFilters.test.tsx
@@ -42,10 +42,10 @@ describe('SavedInsightsFilters Created by dropdown', () => {
]
useMocks({
get: {
- '/api/organizations/:organization_id/members/': (req) => {
+ '/api/organizations/:organization_id/members/': ({ request }) => {
// membersLogic now does server-side search; mock honors `?search=`
// by filtering on first_name, last_name, and email substring.
- const search = new URL(req.url).searchParams.get('search')?.toLowerCase()
+ const search = new URL(request.url).searchParams.get('search')?.toLowerCase()
const results = search
? allMembers.filter((m) => {
const u = m.user
diff --git a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
index 5f4e07502ddf..523ec9eb70d6 100644
--- a/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/addSavedInsightsModalLogic.test.ts
@@ -50,9 +50,10 @@ function useSetupWithUrlCapture(options: { userInsightCount?: number; variant?:
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => {
- capturedUrls.push(req.url)
- if (req.url.searchParams.get('user') === 'true') {
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const url = new URL(request.url)
+ capturedUrls.push(url)
+ if (url.searchParams.get('user') === 'true') {
return [200, { count: userInsightCount, results: [] }]
}
return [200, { count: 0, results: [] }]
@@ -182,11 +183,12 @@ describe('addSavedInsightsModalLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => {
- if (req.url.searchParams.get('user') === 'true') {
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('user') === 'true') {
return [200, { count: 0, results: [] }]
}
- const search = req.url.searchParams.get('search') ?? ''
+ const search = url.searchParams.get('search') ?? ''
const results = [createInsight(1, search || 'default'), createInsight(2, search || 'default')]
return [200, { count: results.length, results }]
},
@@ -207,11 +209,12 @@ describe('addSavedInsightsModalLogic', () => {
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => {
- if (req.url.searchParams.get('user') === 'true') {
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('user') === 'true') {
return [200, { count: 0, results: [] }]
}
- const search = req.url.searchParams.get('search')
+ const search = url.searchParams.get('search')
const label = search || 'unfiltered'
return [200, { count: 1, results: [createInsight(1, label)] }]
},
diff --git a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
index 9b668ea1bb19..ac3744a4649c 100644
--- a/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
+++ b/frontend/src/scenes/saved-insights/savedInsightsLogic.test.ts
@@ -54,13 +54,16 @@ describe('savedInsightsLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => [
- 200,
- createSavedInsights(
- req.url.searchParams.get('search') ?? '',
- parseInt(req.url.searchParams.get('offset') ?? '0')
- ),
- ],
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const url = new URL(request.url)
+ return [
+ 200,
+ createSavedInsights(
+ url.searchParams.get('search') ?? '',
+ parseInt(url.searchParams.get('offset') ?? '0')
+ ),
+ ]
+ },
'/api/environments/:team_id/insights/42': createInsight(42),
'/api/environments/:team_id/insights/123': createInsight(123),
},
@@ -260,8 +263,8 @@ describe('savedInsightsLogic', () => {
useMocks({
get: {
- '/api/environments/:team_id/insights/': (req) => {
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/environments/:team_id/insights/': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
return new Promise<[number, any]>((resolve) => {
pendingRequests.push({ resolve, search })
onRequestArrived?.()
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
index 5ab483b5aee7..ff724837aff4 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-activity-modal.stories.tsx
@@ -1,5 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
import { combineUrl, router } from 'kea-router'
+import { HttpResponse } from 'msw'
import { App } from 'scenes/App'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -42,9 +43,9 @@ export const EventExplorerWithModal: Story = {
200,
{ ...recordingMetaJson, id: 'modal-recording-001' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-group-scene.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-group-scene.stories.tsx
index bd7d2a7e4753..b930e11617d0 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-group-scene.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-group-scene.stories.tsx
@@ -1,5 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
import { combineUrl, router } from 'kea-router'
+import { HttpResponse } from 'msw'
import { App } from 'scenes/App'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -198,9 +199,9 @@ export const GroupRecordingTabMultipleAndFound: Story = {
200,
{ ...recordingMetaJson, id: 'group-rec-002' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -251,9 +252,9 @@ export const GroupRecordingTabWide: Story = {
200,
{ ...recordingMetaJson, id: 'group-rec-001' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -305,9 +306,9 @@ export const GroupRecordingTabNarrow: Story = {
200,
{ ...recordingMetaJson, id: 'group-rec-001' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -358,9 +359,9 @@ export const GroupEventsTabWithModal: Story = {
200,
{ ...recordingMetaJson, id: 'group-rec-001' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-person-scene.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-person-scene.stories.tsx
index 7728d4b09718..34515e872321 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-person-scene.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-person-scene.stories.tsx
@@ -1,5 +1,6 @@
import { Meta, StoryObj } from '@storybook/react'
import { combineUrl, router } from 'kea-router'
+import { HttpResponse } from 'msw'
import { App } from 'scenes/App'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -129,8 +130,8 @@ const meta: Meta = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- const query = (req.body as any)?.query
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const query = ((await request.json()) as any)?.query
if (query?.kind === 'HogQLQuery' && query?.values?.id === personUUID) {
return [200, personQueryResponse]
}
@@ -151,8 +152,8 @@ export const PersonRecordingTabEmpty: Story = {
'/api/environments/:team_id/session_recordings': () => [200, { results: [] }],
},
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- const query = (req.body as any)?.query
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const query = ((await request.json()) as any)?.query
if (query?.kind === 'HogQLQuery' && query?.values?.id === personUUID) {
return [200, personQueryResponse]
}
@@ -190,9 +191,9 @@ export const PersonRecordingTabMultipleAndFound: Story = {
200,
{ ...recordingMetaJson, id: 'rec-002-banana' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -238,9 +239,9 @@ export const PersonRecordingTabWide: Story = {
200,
{ ...recordingMetaJson, id: 'rec-001-apple' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -287,9 +288,9 @@ export const PersonRecordingTabNarrow: Story = {
200,
{ ...recordingMetaJson, id: 'rec-001-apple' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -336,9 +337,9 @@ export const PersonEventsTabWithModal: Story = {
200,
{ ...recordingMetaJson, id: 'rec-001-apple' },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
index 8cf2561d51b9..9023409ac8b9 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-player-failure.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { HttpResponse } from 'msw'
import { App } from 'scenes/App'
import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'
@@ -24,8 +25,8 @@ const meta: Meta = {
mswDecorator({
get: {
'/stats': () => [200, { users_on_product: 42, active_recordings: 7 }],
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [
200,
{
@@ -36,8 +37,8 @@ const meta: Meta = {
]
},
'/api/projects/:team_id/session_recording_playlists': recordingPlaylists,
- '/api/projects/:team_id/session_recording_playlists/:playlist_id': (req) => {
- const playlistId = req.params.playlist_id
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': ({ params }) => {
+ const playlistId = params.playlist_id
return [
200,
@@ -84,15 +85,15 @@ const meta: Meta = {
},
]
},
- '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': (req) => {
- const playlistId = req.params.playlist_id
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': ({ params }) => {
+ const playlistId = params.playlist_id
const response = playlistId === '1234567' ? recordings : []
return [200, { has_next: false, results: response, version: 1 }]
},
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
// with no sources, returns sources...
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
// with no source requested should return sources
return [
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
index e688070e616f..86523dc1872b 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-player-success.stories.tsx
@@ -2,6 +2,7 @@ import { MOCK_DEFAULT_ORGANIZATION, MOCK_DEFAULT_USER } from 'lib/api.mock'
import { Meta, StoryObj } from '@storybook/react'
import { combineUrl, router } from 'kea-router'
+import { HttpResponse } from 'msw'
import { App } from 'scenes/App'
import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'
@@ -102,8 +103,8 @@ const meta: Meta = {
mswDecorator({
get: {
'/stats': () => [200, { users_on_product: 42, active_recordings: 7 }],
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [
200,
{
@@ -114,20 +115,20 @@ const meta: Meta = {
]
},
'/api/projects/:team_id/session_recording_playlists': recordingPlaylists,
- '/api/projects/:team_id/session_recording_playlists/:playlist_id': (req) => {
- const playlistId = req.params.playlist_id as string
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': ({ params }) => {
+ const playlistId = params.playlist_id as string
return [200, playlist(playlistId)]
},
- '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': (req) => {
- const playlistId = req.params.playlist_id
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': ({ params }) => {
+ const playlistId = params.playlist_id
const response = playlistId === '1234567' ? recordings : []
return [200, { has_next: false, results: response, version: 1 }]
},
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
// with no sources, returns sources...
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
// with no source requested should return sources
return [
@@ -153,9 +154,9 @@ const meta: Meta = {
},
},
patch: {
- '/api/projects/:team_id/session_recording_playlists/:playlist_id': (req) => {
- const playlistId = req.params.playlist_id as string
- const body = req.body as Partial<SessionRecordingPlaylistType>
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': async ({ request, params }) => {
+ const playlistId = params.playlist_id as string
+ const body = (await request.json()) as Partial<SessionRecordingPlaylistType>
return [200, { ...playlist(playlistId), ...body }]
},
},
@@ -168,34 +169,32 @@ const meta: Meta = {
200,
{ success: true },
],
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === 'HogQLQuery' && body.query.query.includes('$session_id as session_id')) {
- return res(
- ctx.json({
- results: recordings.map((r) => [
- r.id,
- 'NG',
- 'Chrome',
- 'Desktop',
- 'Mac OS X',
- 'Mac OS X',
- 'google.com',
- null,
- null,
- 'https://example.com',
- ]),
- })
- )
+ return HttpResponse.json({
+ results: recordings.map((r) => [
+ r.id,
+ 'NG',
+ 'Chrome',
+ 'Desktop',
+ 'Mac OS X',
+ 'Mac OS X',
+ 'google.com',
+ null,
+ null,
+ 'https://example.com',
+ ]),
+ })
}
if (body.query.kind === 'EventsQuery' && body.query.properties.length === 1) {
- return res(ctx.json(recordingEventsJson))
+ return HttpResponse.json(recordingEventsJson)
}
// default to an empty response or we duplicate information
- return res(ctx.json({ results: [] }))
+ return HttpResponse.json({ results: [] })
},
},
}),
@@ -271,8 +270,8 @@ const userSeenReplayIntroMock = (): MockSignature => [
},
]
-const manyRecordingsMock: MockSignature = (req) => {
- const version = req.url.searchParams.get('version')
+const manyRecordingsMock: MockSignature = ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [200, { has_next: false, results: generateManyRecordings(25), version }]
}
diff --git a/frontend/src/scenes/session-recordings/SessionsRecordings-playlist-listing.stories.tsx b/frontend/src/scenes/session-recordings/SessionsRecordings-playlist-listing.stories.tsx
index f57457842bda..2cf83a9bade8 100644
--- a/frontend/src/scenes/session-recordings/SessionsRecordings-playlist-listing.stories.tsx
+++ b/frontend/src/scenes/session-recordings/SessionsRecordings-playlist-listing.stories.tsx
@@ -24,8 +24,8 @@ const meta: Meta = {
get: {
'/stats': () => [200, { users_on_product: 42, active_recordings: 7 }],
'/api/projects/:team_id/session_recording_playlists': recordingPlaylists,
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [
200,
{
diff --git a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts
index 13f7bc8e75f3..f50ca587f9db 100644
--- a/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/collections/SessionRecordingCollectionsLogic.test.ts
@@ -24,8 +24,8 @@ describe('sessionRecordingCollectionsLogic', () => {
beforeEach(() => {
useMocks({
get: {
- '/api/projects/:team/session_recording_playlists': (req) => {
- const { searchParams } = req.url
+ '/api/projects/:team/session_recording_playlists': ({ request }) => {
+ const { searchParams } = new URL(request.url)
if (searchParams.get('date_to') === '2021-10-05') {
return [
200,
diff --git a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
index 4b58e4021b64..62cf159183cf 100644
--- a/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
+++ b/frontend/src/scenes/session-recordings/filters/RecordingsUniversalFiltersEmbed.stories.tsx
@@ -31,8 +31,8 @@ const meta: Meta = {
get: {
'/stats': () => [200, { users_on_product: 42, active_recordings: 7 }],
'/api/projects/:team_id/session_recording_playlists': recordingPlaylists,
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [200, { has_next: false, results: recordings, version }]
},
},
diff --git a/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts b/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
index 81fa162fc196..989b8c61bef2 100644
--- a/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
+++ b/frontend/src/scenes/session-recordings/player/__mocks__/test-setup.ts
@@ -1,3 +1,5 @@
+import { HttpResponse } from 'msw'
+
import { useAvailableFeatures } from '~/mocks/features'
import { useMocks } from '~/mocks/jest'
import { MockSignature } from '~/mocks/utils'
@@ -22,11 +24,11 @@ export const EMPTY_PAGINATED_RESPONSE = {
}
function createSnapshotMockHandler(sources: SessionRecordingSnapshotSource[]): MockSignature {
- return async (req, res, ctx) => {
- const sourceParam = req.url.searchParams.get('source')
+ return ({ request }) => {
+ const sourceParam = new URL(request.url).searchParams.get('source')
if (sourceParam === 'blob_v2' || sourceParam === 'blob') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
@@ -131,8 +133,8 @@ export function createDifferentiatedQueryHandler(
types: recordingEventsJson.types,
}
): MockSignature {
- return async (req) => {
- const body = await req.json()
+ return async ({ request }) => {
+ const body = (await request.json()) as any
const query = body.query?.query || ''
if (query.includes('$session_id =')) {
diff --git a/frontend/src/scenes/session-recordings/player/controller/PlayerController.stories.tsx b/frontend/src/scenes/session-recordings/player/controller/PlayerController.stories.tsx
index 3d22ba880ad4..ab7520037e7d 100644
--- a/frontend/src/scenes/session-recordings/player/controller/PlayerController.stories.tsx
+++ b/frontend/src/scenes/session-recordings/player/controller/PlayerController.stories.tsx
@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
import { BindLogic } from 'kea'
+import { HttpResponse } from 'msw'
import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -35,9 +36,9 @@ const meta: Meta<ControllerStoryProps> = {
mswDecorator({
get: {
'/api/projects/:team_id/notebooks/recording_comments': { results: [] },
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -56,12 +57,12 @@ const meta: Meta<ControllerStoryProps> = {
'/api/environments/:team_id/session_recordings/:id': () => [200, recordingMetaJson],
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === 'EventsQuery') {
- return res(ctx.json(recordingEventsJson))
+ return [200, recordingEventsJson]
}
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
}),
diff --git a/frontend/src/scenes/session-recordings/player/inspector/PlayerInspector.stories.tsx b/frontend/src/scenes/session-recordings/player/inspector/PlayerInspector.stories.tsx
index fcb63c54c713..2f957ddb7364 100644
--- a/frontend/src/scenes/session-recordings/player/inspector/PlayerInspector.stories.tsx
+++ b/frontend/src/scenes/session-recordings/player/inspector/PlayerInspector.stories.tsx
@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
import { BindLogic, useActions, useValues } from 'kea'
+import { HttpResponse } from 'msw'
import { useEffect } from 'react'
import { FEATURE_FLAGS } from 'lib/constants'
@@ -51,9 +52,9 @@ const meta: Meta = {
],
},
'/api/environments/:team_id/session_recordings/:id': largeRecordingMetaJson,
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(largeRecordingJSONL))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(largeRecordingJSONL)
}
return [
200,
@@ -71,23 +72,23 @@ const meta: Meta = {
},
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === 'HogQLQuery') {
if (body.query.query.includes("event in ['$web_vitals']")) {
- return res(ctx.json(largeRecordingWebVitalsEventsPropertiesJson))
+ return [200, largeRecordingWebVitalsEventsPropertiesJson]
}
- return res(ctx.json(largeRecordingEventsJson))
+ return [200, largeRecordingEventsJson]
}
// default to an empty response or we duplicate information
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
patch: {
- '/api/environments/:team_id/session_recordings/:id': (_, res, ctx) => {
- return res(ctx.json({}))
+ '/api/environments/:team_id/session_recordings/:id': () => {
+ return [200, {}]
},
},
}),
diff --git a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts
index deb5588ec20c..772e37a9da2a 100644
--- a/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/player-meta/playerMetaLogic.test.ts
@@ -1,4 +1,5 @@
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
import { dayjs } from 'lib/dayjs'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
@@ -26,8 +27,8 @@ describe('playerMetaLogic', () => {
useMocks({
get: {
'/api/environments/:team_id/session_recordings/:id': recordingMetaJson,
- '/api/environments/:team_id/session_recordings/:id/snapshots/': (_, res, ctx) =>
- res(ctx.text(snapshotsAsJSONLines())),
+ '/api/environments/:team_id/session_recordings/:id/snapshots/': () =>
+ new HttpResponse(snapshotsAsJSONLines()),
},
post: {
'/api/environments/:team_id/query/:kind': recordingEventsJson,
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.test.ts
index 66059cc028fb..d98f93d1d2ac 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingCommentsLogic.test.ts
@@ -20,8 +20,8 @@ describe('sessionRecordingCommentsLogic', () => {
setupSessionRecordingTest({
getMocks: {
'/api/environments/:team_id/session_recordings/1/': {},
- '/api/projects/:team_id/comments': (req) => {
- capturedCommentsQuery = req.url.searchParams
+ '/api/projects/:team_id/comments': ({ request }) => {
+ capturedCommentsQuery = new URL(request.url).searchParams
return [200, { results: [] }]
},
},
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts
index 711f183ff7f7..3334d6851a57 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.blobv2.test.ts
@@ -2,6 +2,7 @@ import { api } from 'lib/api.mock'
import { readFileSync } from 'fs'
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
import { join } from 'path'
import { sessionRecordingDataCoordinatorLogic } from 'scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic'
@@ -43,20 +44,21 @@ describe('sessionRecordingDataCoordinatorLogic blobby v2', () => {
setupSessionRecordingTest({
snapshotSources: [BLOB_V2_SOURCE_ZERO, BLOB_V2_SOURCE_ONE],
getMocks: {
- '/api/environments/:team_id/session_recordings/:id/snapshots': async (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob') {
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('source') === 'blob') {
throw new Error('not expecting this to be called in this test')
- } else if (req.url.searchParams.get('source') === 'blob_v2') {
- const key = req.url.searchParams.get('blob_key')
- const start_blob_key = req.url.searchParams.get('start_blob_key')
- const end_blob_key = req.url.searchParams.get('end_blob_key')
+ } else if (url.searchParams.get('source') === 'blob_v2') {
+ const key = url.searchParams.get('blob_key')
+ const start_blob_key = url.searchParams.get('start_blob_key')
+ const end_blob_key = url.searchParams.get('end_blob_key')
if (key === '0') {
- return res(ctx.text(keyZero))
+ return new HttpResponse(keyZero)
} else if (key === '1') {
- return res(ctx.text(keyOne))
+ return new HttpResponse(keyOne)
} else if (start_blob_key === '0' && end_blob_key === '1') {
- return res(ctx.text(`${keyZero}\n${keyOne}`))
+ return new HttpResponse(`${keyZero}\n${keyOne}`)
}
throw new Error(`Unexpected blob key: ${key}`)
}
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
index a7e9adfbb713..a8c49f1984a2 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.performance.test.ts
@@ -1,5 +1,6 @@
import { readFileSync } from 'fs'
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
import { join } from 'path'
import { uuid } from 'lib/utils/dom'
@@ -41,11 +42,12 @@ describe('sessionRecordingDataCoordinatorLogic performance', () => {
},
],
getMocks: {
- '/api/environments/:team_id/session_recordings/:id/snapshots': async (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- const key = req.url.searchParams.get('blob_key')
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ const url = new URL(request.url)
+ if (url.searchParams.get('source') === 'blob_v2') {
+ const key = url.searchParams.get('blob_key')
const contents = key === '0' ? keyZero : keyOne
- return res(ctx.text(contents))
+ return new HttpResponse(contents)
}
return [
diff --git a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.test.ts b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.test.ts
index 08d23b4ee471..bd1379061b8c 100644
--- a/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/player/sessionRecordingDataCoordinatorLogic.test.ts
@@ -1,6 +1,7 @@
import { api } from 'lib/api.mock'
import { expectLogic } from 'kea-test-utils'
+import { HttpResponse } from 'msw'
import { processAllSnapshots, SourceKey, ViewportResolution } from '@posthog/replay-shared'
@@ -253,8 +254,8 @@ describe('sessionRecordingDataCoordinatorLogic', () => {
// response used to leave fullyLoaded false with nothing left to re-trigger the report
overrideSessionRecordingMocks({
postMocks: {
- '/api/environments/:team_id/query/:kind': async (req) => {
- const body = await req.json()
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
const query = body.query?.query || ''
if (query.includes('uuid in')) {
await new Promise((resolve) => setTimeout(resolve, 100))
@@ -300,10 +301,10 @@ describe('sessionRecordingDataCoordinatorLogic', () => {
snapshotLogic?.unmount()
setupSessionRecordingTest({
getMocks: {
- '/api/environments/:team_id/session_recordings/:id/snapshots': async (req, res, ctx) => {
- const sourceParam = req.url.searchParams.get('source')
+ '/api/environments/:team_id/session_recordings/:id/snapshots': async ({ request }) => {
+ const sourceParam = new URL(request.url).searchParams.get('source')
if (sourceParam === 'blob_v2' || sourceParam === 'blob') {
- return res(ctx.text(jsonLines))
+ return new HttpResponse(jsonLines)
}
return [200, { sources: [BLOB_SOURCE_V2] }]
},
diff --git a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarOverviewTab.stories.tsx b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarOverviewTab.stories.tsx
index 8f053e385fb7..a743308b5104 100644
--- a/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarOverviewTab.stories.tsx
+++ b/frontend/src/scenes/session-recordings/player/sidebar/PlayerSidebarOverviewTab.stories.tsx
@@ -1,5 +1,6 @@
import type { Meta, StoryObj } from '@storybook/react'
import { BindLogic } from 'kea'
+import { HttpResponse } from 'msw'
import recordingEventsJson from 'scenes/session-recordings/__mocks__/recording_events_query'
import { recordingMetaJson } from 'scenes/session-recordings/__mocks__/recording_meta'
@@ -28,8 +29,8 @@ const meta: Meta<OverviewTabProps> = {
mswDecorator({
get: {
'/api/projects/:team_id/notebooks/recording_comments': { results: [] },
- '/api/environments/:team_id/session_recordings': (req) => {
- const version = req.url.searchParams.get('version')
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const version = new URL(request.url).searchParams.get('version')
return [
200,
{
@@ -40,8 +41,8 @@ const meta: Meta<OverviewTabProps> = {
]
},
'/api/projects/:team_id/session_recording_playlists': recordingPlaylists,
- '/api/projects/:team_id/session_recording_playlists/:playlist_id': (req) => {
- const playlistId = req.params.playlist_id
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': ({ params }) => {
+ const playlistId = params.playlist_id
return [
200,
@@ -88,14 +89,14 @@ const meta: Meta<OverviewTabProps> = {
},
]
},
- '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': (req) => {
- const playlistId = req.params.playlist_id
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id/recordings': ({ params }) => {
+ const playlistId = params.playlist_id
const response = playlistId === '1234567' ? recordings : []
return [200, { has_next: false, results: response, version: 1 }]
},
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -111,18 +112,19 @@ const meta: Meta<OverviewTabProps> = {
},
]
},
- '/api/environments/:team_id/session_recordings/:id': (req, res, ctx) => {
- if (req.params.id === '12345') {
- return res(ctx.json(recordingMetaJson))
- } else if (req.params.id === 'thirty_others') {
- return res(
- ctx.json({
+ '/api/environments/:team_id/session_recordings/:id': ({ params }) => {
+ if (params.id === '12345') {
+ return [200, recordingMetaJson]
+ } else if (params.id === 'thirty_others') {
+ return [
+ 200,
+ {
...recordingMetaJson,
viewers: Array.from({ length: 30 }, (_, i) => `${i}@example.com`),
- })
- )
+ },
+ ]
}
- return res(ctx.json({ ...recordingMetaJson, viewers: ['abcdefg'] }))
+ return [200, { ...recordingMetaJson, viewers: ['abcdefg'] }]
},
'api/projects/:team/notebooks': {
count: 0,
@@ -132,15 +134,16 @@ const meta: Meta<OverviewTabProps> = {
},
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (
body.query.kind === 'HogQLQuery' &&
// very lazy match
body.query.query.includes('any(properties.$geoip_country_code) as $geoip_country_code')
) {
- return res(
- ctx.json({
+ return [
+ 200,
+ {
columns: [
'session_id',
'$geoip_country_code',
@@ -167,16 +170,16 @@ const meta: Meta<OverviewTabProps> = {
'https://hedgehog.io/entry-page',
],
],
- })
- )
+ },
+ ]
}
if (body.query.kind === 'EventsQuery' && body.query.properties.length === 1) {
- return res(ctx.json(recordingEventsJson))
+ return [200, recordingEventsJson]
}
// default to an empty response or we duplicate information
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
}),
diff --git a/frontend/src/scenes/session-recordings/playlist/AddToCollectionModal.stories.tsx b/frontend/src/scenes/session-recordings/playlist/AddToCollectionModal.stories.tsx
index ab64564bce75..5a5a0e8c18e0 100644
--- a/frontend/src/scenes/session-recordings/playlist/AddToCollectionModal.stories.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/AddToCollectionModal.stories.tsx
@@ -76,9 +76,9 @@ export const NoSearchEntered: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/session_recording_playlists': (req, res, ctx) => {
- const search = req.url.searchParams.get('search')
- return res(ctx.json(filterPlaylistsBySearch(search)))
+ '/api/projects/:team_id/session_recording_playlists': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
+ return [200, filterPlaylistsBySearch(search)]
},
},
})
@@ -90,9 +90,9 @@ export const SearchWithResults: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/session_recording_playlists': (req, res, ctx) => {
- const search = req.url.searchParams.get('search')
- return res(ctx.json(filterPlaylistsBySearch(search)))
+ '/api/projects/:team_id/session_recording_playlists': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search')
+ return [200, filterPlaylistsBySearch(search)]
},
},
})
@@ -104,7 +104,7 @@ export const SearchWithNoResults: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/session_recording_playlists': (_req, res, ctx) => res(ctx.json(emptyPlaylists)),
+ '/api/projects/:team_id/session_recording_playlists': () => [200, emptyPlaylists],
},
})
return <StoryWrapper initialSearch="no-match-for-this-term" />
@@ -115,7 +115,7 @@ export const NoCollections: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/session_recording_playlists': (_req, res, ctx) => res(ctx.json(emptyPlaylists)),
+ '/api/projects/:team_id/session_recording_playlists': () => [200, emptyPlaylists],
},
})
return <StoryWrapper />
diff --git a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.stories.tsx b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.stories.tsx
index f9f61a2797f6..3e250722fd9a 100644
--- a/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.stories.tsx
+++ b/frontend/src/scenes/session-recordings/playlist/SessionRecordingsPlaylistScene.stories.tsx
@@ -1,6 +1,7 @@
import { Meta, StoryObj } from '@storybook/react'
import { useActions } from 'kea'
import { combineUrl, router } from 'kea-router'
+import { HttpResponse } from 'msw'
import { useEffect } from 'react'
import { App } from 'scenes/App'
@@ -103,9 +104,9 @@ const meta: Meta = {
200,
{ has_next: false, results: recordings, version: 1 },
],
- '/api/environments/:team_id/session_recordings/:id/snapshots': (req, res, ctx) => {
- if (req.url.searchParams.get('source') === 'blob_v2') {
- return res(ctx.text(snapshotsAsJSONLines()))
+ '/api/environments/:team_id/session_recordings/:id/snapshots': ({ request }) => {
+ if (new URL(request.url).searchParams.get('source') === 'blob_v2') {
+ return new HttpResponse(snapshotsAsJSONLines())
}
return [
200,
@@ -128,8 +129,8 @@ const meta: Meta = {
'api/projects/:team/notebooks': { count: 0, next: null, previous: null, results: [] },
},
patch: {
- '/api/projects/:team_id/session_recording_playlists/:playlist_id': (req) => {
- const body = req.body as Partial<SessionRecordingPlaylistType>
+ '/api/projects/:team_id/session_recording_playlists/:playlist_id': async ({ request }) => {
+ const body = (await request.json()) as Partial<SessionRecordingPlaylistType>
return [200, { ...playlistWithRecordings, ...body }]
},
},
@@ -142,19 +143,20 @@ const meta: Meta = {
200,
{ success: true },
],
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
if (body.query.kind === 'EventsQuery') {
- return res(ctx.json(recordingEventsJson))
+ return [200, recordingEventsJson]
}
if (
body.query.kind === 'HogQLQuery' &&
body.query.query.includes('any(properties.$geoip_country_code) as $geoip_country_code')
) {
- return res(
- ctx.json({
+ return [
+ 200,
+ {
columns: [
'session_id',
'$geoip_country_code',
@@ -179,11 +181,11 @@ const meta: Meta = {
'London',
'https://posthog.com/entry-page',
]),
- })
- )
+ },
+ ]
}
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
}),
diff --git a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
index 07645c4dbe09..677a040bb7f2 100644
--- a/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
+++ b/frontend/src/scenes/session-recordings/playlist/sessionRecordingsPlaylistLogic.test.ts
@@ -83,8 +83,8 @@ describe('sessionRecordingsPlaylistLogic', () => {
'api/projects/:team/property_definitions/seen_together': { $pageview: true },
- '/api/environments/:team_id/session_recordings': (req) => {
- const { searchParams } = req.url
+ '/api/environments/:team_id/session_recordings': ({ request }) => {
+ const { searchParams } = new URL(request.url)
if (
(searchParams.get('events')?.length || 0) > 0 &&
JSON.parse(searchParams.get('events') || '[]')[0]?.['id'] === '$autocapture'
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.stories.tsx
index 78da9573bdbb..2a58791d8115 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.stories.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/SSOSelect.stories.tsx
@@ -1,4 +1,5 @@
import type { Meta, StoryObj } from '@storybook/react'
+import { HttpResponse, delay } from 'msw'
import { useState } from 'react'
import { useStorybookMocks } from '~/mocks/browser'
@@ -15,18 +16,17 @@ const meta: Meta<SSOSelectInterface> = {
const [value, setValue] = useState('google-oauth2' as SSOProvider | '')
useStorybookMocks({
get: {
- '/_preflight': (_, __, ctx) => [
- ctx.delay(10),
- ctx.status(200),
- ctx.json({
+ '/_preflight': async () => {
+ await delay(10)
+ return HttpResponse.json({
...preflightJSON,
available_social_auth_providers: {
github: true,
gitlab: false,
'google-oauth2': true,
},
- }),
- ],
+ })
+ },
},
})
return (
diff --git a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
index 087a8e475039..5c2d45802ece 100644
--- a/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
+++ b/frontend/src/scenes/settings/organization/VerifiedDomains/VerifiedDomains.stories.tsx
@@ -125,9 +125,9 @@ const meta: Meta<typeof App> = {
'/api/user_home_settings/@me/': {},
},
patch: {
- '/api/projects/:id': async (req, res, ctx) => {
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...(await req.json()) }
- return res(ctx.json(newTeamSettings))
+ '/api/projects/:id': async ({ request }) => {
+ const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
+ return [200, newTeamSettings]
},
},
}),
diff --git a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
index a9a73614ebc3..6224636989c3 100644
--- a/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsEnvironment.stories.tsx
@@ -49,10 +49,10 @@ const meta: Meta<StoryProps> = {
},
},
patch: {
- '/api/projects/:id': async (req, res, ctx) => {
+ '/api/projects/:id': async ({ request }) => {
// bounce the setting back as is
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...(await req.json()) }
- return res(ctx.json(newTeamSettings))
+ const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
+ return [200, newTeamSettings]
},
},
}),
diff --git a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
index 599c78cb449a..3e36c19a761a 100644
--- a/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsOrganization.stories.tsx
@@ -51,10 +51,10 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
},
},
patch: {
- '/api/projects/:id': async (req, res, ctx) => {
+ '/api/projects/:id': async ({ request }) => {
// bounce the setting back as is
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...(await req.json()) }
- return res(ctx.json(newTeamSettings))
+ const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
+ return [200, newTeamSettings]
},
},
}),
diff --git a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
index d448a47c1116..b0151918ffe1 100644
--- a/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsProject.stories.tsx
@@ -37,10 +37,10 @@ const meta: Meta<(props: StoryProps) => JSX.Element> = {
'/api/projects/:id/integrations': { results: [] },
},
patch: {
- '/api/projects/:id': async (req, res, ctx) => {
+ '/api/projects/:id': async ({ request }) => {
// bounce the setting back as is
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...(await req.json()) }
- return res(ctx.json(newTeamSettings))
+ const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
+ return [200, newTeamSettings]
},
},
}),
diff --git a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
index d18e00a745d1..f02b8452c357 100644
--- a/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
+++ b/frontend/src/scenes/settings/stories/SettingsUser.stories.tsx
@@ -37,10 +37,10 @@ const meta: Meta<StoryProps> = {
'/api/projects/:id/integrations': { results: [] },
},
patch: {
- '/api/projects/:id': async (req, res, ctx) => {
+ '/api/projects/:id': async ({ request }) => {
// bounce the setting back as is
- const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...(await req.json()) }
- return res(ctx.json(newTeamSettings))
+ const newTeamSettings = { ...MOCK_DEFAULT_TEAM, ...((await request.json()) as object) }
+ return [200, newTeamSettings]
},
},
}),
diff --git a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
index 217a81029374..ff97d7a9fad3 100644
--- a/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
+++ b/frontend/src/scenes/settings/user/personalAPIKeysLogic.test.ts
@@ -1,9 +1,12 @@
import { MOCK_DEFAULT_USER } from 'lib/api.mock'
+import { expectLogic } from 'kea-test-utils'
+
import { FEATURE_FLAGS } from 'lib/constants'
import { featureFlagLogic } from 'lib/logic/featureFlagLogic'
import { userLogic } from 'scenes/userLogic'
+import { themeLogic } from '~/layout/navigation-3000/themeLogic'
import { useMocks } from '~/mocks/jest'
import { initKeaTests } from '~/test/init'
@@ -22,8 +25,8 @@ describe('personalAPIKeysLogic', () => {
'/api/projects/': { results: [], count: 0, next: null, previous: null },
},
post: {
- '/api/personal_api_keys/': async (req) => {
- capturedCreatePayload = await req.json()
+ '/api/personal_api_keys/': async ({ request }) => {
+ capturedCreatePayload = await request.json()
return [
200,
{
@@ -43,6 +46,8 @@ describe('personalAPIKeysLogic', () => {
featureFlagLogic.mount()
userLogic.mount()
userLogic.actions.loadUserSuccess(MOCK_DEFAULT_USER)
+ // createKeySuccess opens a LemonDialog with a CodeSnippet, which reads themeLogic.
+ themeLogic.mount()
logic = personalAPIKeysLogic()
logic.mount()
@@ -59,6 +64,8 @@ describe('personalAPIKeysLogic', () => {
})
await logic.asyncActions.submitEditingKey()
+ // The form submit's API call settles asynchronously under MSW v2 — drain it
+ await expectLogic(logic).toFinishAllListeners()
expect(capturedCreatePayload).not.toBeNull()
expect(capturedCreatePayload.scopes).toEqual(['feature_flag:read', 'insight:write'])
@@ -78,6 +85,8 @@ describe('personalAPIKeysLogic', () => {
})
await logic.asyncActions.submitEditingKey()
+ // The form submit's API call settles asynchronously under MSW v2 — drain it
+ await expectLogic(logic).toFinishAllListeners()
expect(capturedCreatePayload).not.toBeNull()
expect(capturedCreatePayload.scopes).toEqual(['feature_flag:read', 'llm_gateway:read'])
@@ -94,6 +103,8 @@ describe('personalAPIKeysLogic', () => {
})
await logic.asyncActions.submitEditingKey()
+ // The form submit's API call settles asynchronously under MSW v2 — drain it
+ await expectLogic(logic).toFinishAllListeners()
expect(capturedCreatePayload).not.toBeNull()
expect(capturedCreatePayload.scopes).toEqual(['*'])
diff --git a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
index d4c029ad1ec3..0b451d611419 100644
--- a/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
+++ b/frontend/src/scenes/subscriptions/subscriptionSceneLogic.test.ts
@@ -85,8 +85,12 @@ describe('subscriptionSceneLogic', () => {
useMocks({
get: {
[`/api/projects/${MOCK_TEAM_ID}/subscriptions/1/`]: [200, MOCK_SUBSCRIPTION],
- [`/api/projects/${MOCK_TEAM_ID}/subscriptions/1/deliveries/`]: (req) => {
- deliveriesRequestUrls.push(req.url.toString())
+ [`/api/environments/${MOCK_TEAM_ID}/subscriptions/1/deliveries/`]: ({ request }) => {
+ deliveriesRequestUrls.push(request.url)
+ return [200, { results: [], next: null, previous: null }]
+ },
+ [`/api/projects/${MOCK_TEAM_ID}/subscriptions/1/deliveries/`]: ({ request }) => {
+ deliveriesRequestUrls.push(request.url)
return [200, { results: [], next: null, previous: null }]
},
},
diff --git a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
index 98c118075f52..5a49188c0c24 100644
--- a/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
+++ b/frontend/src/scenes/subscriptions/subscriptionsSceneLogic.test.ts
@@ -32,8 +32,8 @@ describe('subscriptionsSceneLogic', () => {
subscriptionRequestUrls = []
useMocks({
get: {
- '/api/projects/:team_id/subscriptions/': (req) => {
- subscriptionRequestUrls.push(req.url.toString())
+ '/api/projects/:team_id/subscriptions/': ({ request }) => {
+ subscriptionRequestUrls.push(request.url)
return [200, EMPTY_SUBSCRIPTIONS]
},
},
diff --git a/frontend/src/scenes/surveys/QuickSurveyModal.test.tsx b/frontend/src/scenes/surveys/QuickSurveyModal.test.tsx
index 4834c0e932a4..2a4a155ce4db 100644
--- a/frontend/src/scenes/surveys/QuickSurveyModal.test.tsx
+++ b/frontend/src/scenes/surveys/QuickSurveyModal.test.tsx
@@ -58,8 +58,8 @@ describe('QuickSurveyForm API payloads', () => {
let capturedRequest: any
useMocks({
post: {
- '/api/projects/:team_id/surveys': async (req) => {
- capturedRequest = await req.json()
+ '/api/projects/:team_id/surveys': async ({ request }) => {
+ capturedRequest = await request.json()
return [200, { id: 'new-survey' }]
},
},
@@ -83,8 +83,8 @@ describe('QuickSurveyForm API payloads', () => {
let capturedRequest: any
useMocks({
post: {
- '/api/projects/:team_id/surveys': async (req) => {
- capturedRequest = await req.json()
+ '/api/projects/:team_id/surveys': async ({ request }) => {
+ capturedRequest = await request.json()
return [200, { id: 'new-survey' }]
},
},
diff --git a/frontend/src/scenes/surveys/Surveys.stories.tsx b/frontend/src/scenes/surveys/Surveys.stories.tsx
index 1e789152304d..8998d96925e8 100644
--- a/frontend/src/scenes/surveys/Surveys.stories.tsx
+++ b/frontend/src/scenes/surveys/Surveys.stories.tsx
@@ -345,12 +345,12 @@ const meta: Meta = {
}`]: toPaginatedResponse([MOCK_SURVEY_WITH_RELEASE_CONS.targeting_flag]),
},
post: {
- '/api/environments/:team_id/query/:kind/': async (req, res, ctx) => {
- const body = await req.json()
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as any
if (body.kind == 'EventsQuery') {
- return res(ctx.json(MOCK_SURVEY_RESULTS))
+ return [200, MOCK_SURVEY_RESULTS]
}
- return res(ctx.json(MOCK_SURVEY_SHOWN))
+ return [200, MOCK_SURVEY_SHOWN]
},
// flag targeting has loaders, make sure they don't keep loading
'/api/projects/:team_id/feature_flags/user_blast_radius/': () => [200, { affected: 120, total: 2000 }],
@@ -561,19 +561,19 @@ export const SurveyResults: Story = {
'/api/environments/:team_id/hog_functions/': { count: 0, results: [], next: null },
},
post: {
- '/api/environments/:team_id/query/:kind/': async (req, res, ctx) => {
- const body = await req.json()
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as any
const sql: string = body?.query?.query ?? ''
if (sql.includes('question_id, label, cnt')) {
- return res(ctx.json(MOCK_SURVEY_AGGREGATE_RESULTS))
+ return MOCK_SURVEY_AGGREGATE_RESULTS
}
if (sql.includes('BASE STATS')) {
- return res(ctx.json(MOCK_SURVEY_BASE_STATS))
+ return MOCK_SURVEY_BASE_STATS
}
if (sql.includes('DISMISSED AND SENT COUNT')) {
- return res(ctx.json({ results: [[60]] }))
+ return { results: [[60]] }
}
- return res(ctx.json({ results: [] }))
+ return { results: [] }
},
},
}),
diff --git a/frontend/src/scenes/surveys/surveysLogic.test.ts b/frontend/src/scenes/surveys/surveysLogic.test.ts
index 9e6aeaffd2a7..8ae87debc5f6 100644
--- a/frontend/src/scenes/surveys/surveysLogic.test.ts
+++ b/frontend/src/scenes/surveys/surveysLogic.test.ts
@@ -148,8 +148,8 @@ describe('surveysLogic', () => {
'/api/projects/:team/surveys/responses_count': () => [200, {}],
},
patch: {
- '/api/environments/:team_id/add_product_intent/': async (req) => {
- const data = await req.json()
+ '/api/environments/:team_id/add_product_intent/': async ({ request }) => {
+ const data = await request.json()
capturedIntentRequests.push(data)
return [200, {}]
},
diff --git a/frontend/src/scenes/surveys/wizard/surveyWizardLogic.test.ts b/frontend/src/scenes/surveys/wizard/surveyWizardLogic.test.ts
index e926a22e8c0b..542bc779705b 100644
--- a/frontend/src/scenes/surveys/wizard/surveyWizardLogic.test.ts
+++ b/frontend/src/scenes/surveys/wizard/surveyWizardLogic.test.ts
@@ -86,8 +86,8 @@ describe('surveyWizardLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/add_product_intent/': async (req) => {
- const data = await req.json()
+ '/api/environments/:team_id/add_product_intent/': async ({ request }) => {
+ const data = await request.json()
capturedIntentRequests.push(data)
return [200, {}]
},
diff --git a/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx b/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx
index 31ca2778d1ac..acbb5b1a246d 100644
--- a/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx
+++ b/frontend/src/scenes/trends/persons-modal/PersonsModal.stories.tsx
@@ -1,4 +1,5 @@
import { Meta, StoryObj } from '@storybook/react'
+import { delay, HttpResponse } from 'msw'
import { RawPropertiesTimelineResult } from 'lib/components/PropertiesTimeline/propertiesTimelineLogic'
@@ -120,14 +121,16 @@ export const TimeoutError: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/persons/trends/*': (_, __, ctx) => [
- ctx.delay(200),
- ctx.status(512),
- ctx.json({
- type: 'server_error',
- detail: 'Estimated query execution time (34.5 seconds) is too long. Try reducing its scope by changing the time range.',
- }),
- ],
+ '/api/projects/:team_id/persons/trends/*': async () => {
+ await delay(200)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ detail: 'Estimated query execution time (34.5 seconds) is too long. Try reducing its scope by changing the time range.',
+ },
+ { status: 512 }
+ )
+ },
},
})
@@ -143,14 +146,16 @@ export const ServerError: Story = {
render: () => {
useStorybookMocks({
get: {
- '/api/projects/:team_id/persons/trends/*': (_, __, ctx) => [
- ctx.delay(200),
- ctx.status(500),
- ctx.json({
- type: 'server_error',
- detail: 'There is nothing you can do to stop the impending catastrophe.',
- }),
- ],
+ '/api/projects/:team_id/persons/trends/*': async () => {
+ await delay(200)
+ return HttpResponse.json(
+ {
+ type: 'server_error',
+ detail: 'There is nothing you can do to stop the impending catastrophe.',
+ },
+ { status: 500 }
+ )
+ },
},
})
diff --git a/frontend/src/scenes/web-analytics/SessionAttributionExplorer/sessionAttributionExplorer.stories.tsx b/frontend/src/scenes/web-analytics/SessionAttributionExplorer/sessionAttributionExplorer.stories.tsx
index be5b285a74d5..e31688bf944f 100644
--- a/frontend/src/scenes/web-analytics/SessionAttributionExplorer/sessionAttributionExplorer.stories.tsx
+++ b/frontend/src/scenes/web-analytics/SessionAttributionExplorer/sessionAttributionExplorer.stories.tsx
@@ -18,15 +18,15 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: {
- '/api/environments/:team_id/query/:id/': async (_, res, ctx) => {
+ '/api/environments/:team_id/query/:id/': () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
- return res(ctx.json(require('./__mocks__/sessionAttributionQueryStatus.json')))
+ return [200, require('./__mocks__/sessionAttributionQueryStatus.json')]
},
},
post: {
- '/api/environments/:team_id/query/:kind/': async (_, res, ctx) => {
+ '/api/environments/:team_id/query/:kind/': () => {
// eslint-disable-next-line @typescript-eslint/no-var-requires
- return res(ctx.json(require('./__mocks__/sessionAttributionQuery.json')))
+ return [200, require('./__mocks__/sessionAttributionQuery.json')]
},
},
}),
diff --git a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx
index 085584db5ea8..6c76b72b3951 100644
--- a/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx
+++ b/frontend/src/scenes/web-analytics/WebAnalyticsDashboard.stories.tsx
@@ -42,8 +42,8 @@ const meta: Meta = {
'/api/projects/:team_id/event_definitions': () => [200, { count: 5 }],
},
post: {
- '/api/environments/:team_id/query/:kind': (req) => {
- const query = (req.body as any).query
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const query = ((await request.json()) as any).query
const queryKind = query.kind
if (queryKind === 'DatabaseSchemaQuery') {
diff --git a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.stories.tsx b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.stories.tsx
index c66d22557013..166d16a3ed96 100644
--- a/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.stories.tsx
+++ b/frontend/src/scenes/web-analytics/tiles/WebAnalyticsTile.stories.tsx
@@ -27,20 +27,21 @@ const meta: Meta<QueryProps<Node>> = {
decorators: [
mswDecorator({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- if ((req.body as any).query.kind === 'WebStatsTableQuery') {
- if ((req.body as any).query.breakdownBy === 'InitialReferringDomain') {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as any
+ if (body.query.kind === 'WebStatsTableQuery') {
+ if (body.query.breakdownBy === 'InitialReferringDomain') {
return [200, referringDomainMock]
- } else if ((req.body as any).query.breakdownBy === 'Page') {
+ } else if (body.query.breakdownBy === 'Page') {
return [200, pathMock]
- } else if ((req.body as any).query.breakdownBy === 'Browser') {
+ } else if (body.query.breakdownBy === 'Browser') {
return [200, browserMock]
}
- } else if ((req.body as any).query.kind === 'TrendsQuery') {
- if ((req.body as any).query.trendsFilter?.display === 'WorldMap') {
+ } else if (body.query.kind === 'TrendsQuery') {
+ if (body.query.trendsFilter?.display === 'WorldMap') {
return [200, worldMapMock]
}
- } else if ((req.body as any).query.kind === 'RetentionQuery') {
+ } else if (body.query.kind === 'RetentionQuery') {
return [200, retentionMock]
}
},
diff --git a/frontend/src/scenes/wizard/wizardLogic.test.tsx b/frontend/src/scenes/wizard/wizardLogic.test.tsx
index 5fea5a140edd..999aed4d7310 100644
--- a/frontend/src/scenes/wizard/wizardLogic.test.tsx
+++ b/frontend/src/scenes/wizard/wizardLogic.test.tsx
@@ -74,6 +74,9 @@ describe('wizardLogic', () => {
view: 'pending',
wizardHash: MOCK_HASH,
})
+ // Drain the auto-triggered authenticate request: its trailing setView would
+ // otherwise dispatch into the next test's store and flip its view.
+ await expectLogic(logic).toFinishAllListeners()
})
})
diff --git a/frontend/src/test/insight-testing/mocks.ts b/frontend/src/test/insight-testing/mocks.ts
index 95dbb5434811..2ebd32bbdebe 100644
--- a/frontend/src/test/insight-testing/mocks.ts
+++ b/frontend/src/test/insight-testing/mocks.ts
@@ -1,5 +1,3 @@
-import { RestRequest } from 'msw'
-
import { useMocks } from '~/mocks/jest'
import { ActorsQueryResponse, NodeKind, TrendsQueryResponse } from '~/queries/schema/schema-general'
import { EventDefinition, PropertyDefinition, RawAnnotationType } from '~/types'
@@ -263,21 +261,21 @@ export function setupInsightMocks({
useMocks({
get: {
- '/api/projects/:team/event_definitions': (req: RestRequest) => {
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/projects/:team/event_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
const results = filterBySearch(eventDefs, search)
return [200, { results, count: results.length }]
},
- '/api/projects/:team/property_definitions': (req: RestRequest) => {
- const search = req.url.searchParams.get('search') ?? ''
+ '/api/projects/:team/property_definitions': ({ request }) => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
const results = filterBySearch(propDefs, search)
return [200, { results, count: results.length }]
},
'/api/projects/:team/actions': { results: actionDefinitions },
'/api/environments/:team/persons/properties': personProperties,
'/api/environments/:team/sessions/property_definitions': { results: sessionPropertyDefinitions },
- '/api/environments/:team/events/values': (req: RestRequest) => {
- const key = req.url.searchParams.get('key') ?? ''
+ '/api/environments/:team/events/values': ({ request }) => {
+ const key = new URL(request.url).searchParams.get('key') ?? ''
const values = (propValues[key] ?? []).map((name) => ({ name }))
return [200, values]
},
@@ -295,8 +293,8 @@ export function setupInsightMocks({
},
},
post: {
- '/api/environments/:team_id/query/:kind': (req: RestRequest) => {
- const queryBody = extractQueryBody(req.body)
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const queryBody = extractQueryBody(await request.json())
for (const mock of responses) {
if (mock.match(queryBody)) {
diff --git a/frontend/src/test/mocks.ts b/frontend/src/test/mocks.ts
index a2ff9832473a..80d6276adf27 100644
--- a/frontend/src/test/mocks.ts
+++ b/frontend/src/test/mocks.ts
@@ -2,6 +2,7 @@ import { TaxonomicFilterGroupType } from 'lib/components/TaxonomicFilter/types'
import { PROPERTY_MATCH_TYPE } from 'lib/constants'
import { BehavioralFilterKey } from 'scenes/cohorts/CohortFilters/types'
+import type { MockResolverInfo } from '~/mocks/utils'
import {
AccessControlLevel,
BehavioralEventType,
@@ -268,14 +269,19 @@ export const mockSlackChannels: SlackChannelType[] = [
},
]
-export const mockGetEventDefinitions = (req: { url: URL }): [number, Record<string, any>] => {
- const search = req.url.searchParams.get('search') ?? ''
- const results = search ? mockEventDefinitions.filter((e) => e.name.includes(search)) : mockEventDefinitions
+export const mockGetEventDefinitions = ({ request }: MockResolverInfo): [number, Record<string, any>] => {
+ const searchParams = new URL(request.url).searchParams
+ const search = searchParams.get('search') ?? ''
+ // The real endpoint filters excluded_properties server-side
+ const excluded: string[] = JSON.parse(searchParams.get('excluded_properties') ?? '[]')
+ const results = mockEventDefinitions.filter(
+ (e) => (!search || e.name.includes(search)) && !excluded.includes(e.name)
+ )
return [200, { results, count: results.length }]
}
-export const mockGetPropertyDefinitions = (req: { url: URL }): [number, Record<string, any>] => {
- const search = req.url.searchParams.get('search') ?? ''
+export const mockGetPropertyDefinitions = ({ request }: MockResolverInfo): [number, Record<string, any>] => {
+ const search = new URL(request.url).searchParams.get('search') ?? ''
const results = search
? mockEventPropertyDefinitions.filter((p) => p.name.includes(search))
: mockEventPropertyDefinitions
diff --git a/frontend/src/toolbar/actions/actionsLogic.test.ts b/frontend/src/toolbar/actions/actionsLogic.test.ts
index 870edc698a6b..6ac5c0182c09 100644
--- a/frontend/src/toolbar/actions/actionsLogic.test.ts
+++ b/frontend/src/toolbar/actions/actionsLogic.test.ts
@@ -33,17 +33,23 @@ const unsortedActions: ActionType[] = [
]
const apiJson = { results: unsortedActions }
-global.fetch = jest.fn(() =>
- Promise.resolve({
- ok: true,
- json: () => Promise.resolve(apiJson),
- } as any as Response)
-)
+// The toolbar calls `global.fetch` directly (not the app api client / MSW). Reassign the mock per
+// test in beforeEach — the MSW jest harness installs its own `global.fetch` in a global beforeAll,
+// which runs after this module loads and would otherwise clobber a top-level assignment.
+const installFetchMock = (): void => {
+ global.fetch = jest.fn(() =>
+ Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve(apiJson),
+ } as any as Response)
+ )
+}
describe('toolbar actionsLogic', () => {
let logic: ReturnType<typeof actionsLogic.build>
beforeEach(() => {
+ installFetchMock()
initKeaTests()
toolbarConfigLogic.build({ apiURL: 'http://localhost', accessToken: 'test-token' }).mount()
logic = actionsLogic()
diff --git a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
index b2bc11dc7aa1..d09229487360 100644
--- a/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
+++ b/frontend/src/toolbar/experiments/experimentsTabLogic.test.ts
@@ -52,12 +52,17 @@ const web_experiments = [
},
]
-global.fetch = jest.fn(() =>
- Promise.resolve({
- ok: true,
- json: () => Promise.resolve({ results: web_experiments }),
- } as any as Response)
-)
+// The toolbar calls `global.fetch` directly (not the app api client / MSW). Reassign the mock per
+// test in beforeEach — the MSW jest harness installs its own `global.fetch` in a global beforeAll,
+// which runs after this module loads and would otherwise clobber a top-level assignment.
+const installFetchMock = (): void => {
+ global.fetch = jest.fn(() =>
+ Promise.resolve({
+ ok: true,
+ json: () => Promise.resolve({ results: web_experiments }),
+ } as any as Response)
+ )
+}
describe('experimentsTabLogic', () => {
let theExperimentsTabLogic: ReturnType<typeof experimentsTabLogic.build>
let theExperimentsLogic: ReturnType<typeof experimentsLogic.build>
@@ -65,6 +70,7 @@ describe('experimentsTabLogic', () => {
let theToolbarConfigLogic: ReturnType<typeof toolbarConfigLogic.build>
beforeEach(() => {
+ installFetchMock()
const { lemonToast } = jest.requireMock('lib/lemon-ui/LemonToast/LemonToast')
;(lemonToast.success as jest.Mock).mockClear()
;(lemonToast.error as jest.Mock).mockClear()
diff --git a/frontend/src/toolbar/index.test.ts b/frontend/src/toolbar/index.test.ts
index c3144584d198..67e10da3818d 100644
--- a/frontend/src/toolbar/index.test.ts
+++ b/frontend/src/toolbar/index.test.ts
@@ -2,10 +2,12 @@ import { ToolbarParams } from '~/types'
// Mock window and fetch
const mockFetch = jest.fn()
-global.fetch = mockFetch
describe('Toolbar flag loading', () => {
beforeEach(() => {
+ // Assigned per-test: the MSW harness's beforeAll (src/mocks/jest.ts) replaces
+ // global.fetch after module evaluation, so a module-level assignment is clobbered.
+ global.fetch = mockFetch
jest.clearAllMocks()
mockFetch.mockClear()
jest.resetModules()
diff --git a/frontend/src/toolbar/toolbarConfigLogic.test.ts b/frontend/src/toolbar/toolbarConfigLogic.test.ts
index 1dbfc61b7270..6e090bebeda3 100644
--- a/frontend/src/toolbar/toolbarConfigLogic.test.ts
+++ b/frontend/src/toolbar/toolbarConfigLogic.test.ts
@@ -10,13 +10,18 @@ import {
} from '~/toolbar/toolbarConfigLogic'
import { cleanToolbarAuthHash, OAUTH_LOCALSTORAGE_KEY, PKCE_STORAGE_KEY, readToolbarAuthHash } from '~/toolbar/utils'
-global.fetch = jest.fn(() =>
- Promise.resolve({
- ok: true,
- status: 200,
- json: () => Promise.resolve([]),
- } as any as Response)
-)
+// The toolbar calls `global.fetch` directly (not the app api client / MSW). Reassign the mock per
+// test in beforeEach — the MSW jest harness installs its own `global.fetch` in a global beforeAll,
+// which runs after this module loads and would otherwise clobber a top-level assignment.
+const installFetchMock = (): void => {
+ global.fetch = jest.fn(() =>
+ Promise.resolve({
+ ok: true,
+ status: 200,
+ json: () => Promise.resolve([]),
+ } as any as Response)
+ )
+}
/** Mock fetch so the HEAD check succeeds and then the token exchange succeeds. */
function mockTokenExchangeSuccess(): void {
@@ -39,7 +44,9 @@ describe('toolbar toolbarConfigLogic', () => {
initKeaTests()
localStorage.clear()
sessionStorage.clear()
- ;(global.fetch as jest.Mock).mockClear()
+ // Install the fetch mock after initKeaTests so its mount-time /_preflight/ call isn't
+ // counted by tests that assert on global.fetch.mock.calls.
+ installFetchMock()
mockOpen = jest.spyOn(window, 'open').mockReturnValue({} as Window)
})
diff --git a/pnpm-lock.yaml b/pnpm-lock.yaml
index a629abfd7dff..3b4da0e14803 100644
--- a/pnpm-lock.yaml
+++ b/pnpm-lock.yaml
@@ -1341,8 +1341,8 @@ importers:
specifier: ^3.0.5
version: 3.0.5
msw:
- specifier: ^0.49.0
+ specifier: ^2.14.6
+ version: 2.14.6(@types/[email protected])([email protected])
safe-stable-stringify:
specifier: ^2.4.3
version: 2.5.0
@@ -1376,12 +1376,12 @@ importers:
typescript:
specifier: 6.0.3
version: 6.0.3
+ undici:
+ specifier: ^6.25.0
+ version: 6.25.0
vite:
specifier: ^7.3.3
- whatwg-fetch:
- specifier: ^3.6.2
- version: 3.6.2
optionalDependencies:
fsevents:
specifier: ^2.3.2
@@ -3979,7 +3979,7 @@ importers:
devDependencies:
'@cloudflare/vitest-pool-workers':
specifier: ^0.16.13
'@cloudflare/workers-types':
specifier: ^4.20260603.1
version: 4.20260608.1
@@ -4017,8 +4017,8 @@ importers:
specifier: ^16.4.7
version: 16.4.7
msw:
- specifier: ^2.12.14
- version: 2.12.14(@types/[email protected])([email protected])
+ specifier: ^2.14.6
+ version: 2.14.6(@types/[email protected])([email protected])
oxfmt:
specifier: ^0.33.0
version: 0.33.0
@@ -4051,7 +4051,7 @@ importers:
vitest:
specifier: ^4.1.0
wrangler:
specifier: ^4.98.0
version: 4.98.0(@cloudflare/[email protected])
@@ -4069,7 +4069,7 @@ importers:
vitest:
specifier: ^4.1.0
wrangler:
specifier: ^4.98.0
version: 4.98.0(@cloudflare/[email protected])
@@ -4101,7 +4101,7 @@ importers:
devDependencies:
vitest:
specifier: ^4.1.0
packages:
@@ -6902,44 +6902,35 @@ packages:
cpu: [x64]
os: [win32]
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-S8qNSZiYzFd0wAcyG5AXCvUHC5Sr7xpZ9wZ2py9XR88jUz8wooStVx5M6dRzczbBWjic9NP7+rY0Xi7qqK/aMQ==}
- engines: {node: '>=18'}
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-3eTuUO1vH2cZm2ZKHeQxnOqlTi9EfZDGgIe3BL3I4u+rJHocr9Fz86M4fjYABPvFnQG/gGK551HqDiIcETwU6Q==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-KR8edRkIsUayMXV+o3Gv+q4jlhENF9nMYUZs9PA2HzrXeHI8M5uDag70U7RJn9yyiMZSbtF5/UexBtAVtZGSbQ==}
- engines: {node: '>=18'}
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-eb8DBZcz/2qHWQda4rk2JiQk5h9QV/cVHi1yjt0f69WFZMRFn0sJTye3EAP8icut8UDMjQPsaH5KbcOogefrFQ==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-43RTuEbfP8MbKzedNqBrlhhNKVwoK//vUFNW3Q3vZ88BLcrs4kYpGg+B2mm5p2K/HfygoCxuKwJJiv8PbGmE0A==}
- engines: {node: '>=18'}
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-Qd6GJT1yVyrZZCfN8W2qKF5ApmqryXRhRKCuip8h01x2w/esJQ2XIYc6f9abMIHgKQdBfFTSOdbHRLAhuM09UA==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
'@types/node':
optional: true
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-RWbSrDiYmO4LbejWY7ttpxczuwQyZLBUyygsA9Nsv95hpzUWwnNTVQmAq3xuh7vNwCp07UTmE5i11XAEExx4RA==}
- engines: {node: '>=18'}
- peerDependencies:
- '@types/node': '>=18'
- peerDependenciesMeta:
- '@types/node':
- optional: true
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-aJ8TBPOGB6f/2qziPfElISTCEd5XOYTFckA2SGjhNmiKzfK/u4ot3v0DUzGVdUnKjN10EqnnEPck36BkyfLnJw==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-t2IEY+unGHOzAaVM5Xx6DEWKeXlDDcNPeDyUpsRc6CUhBfU3VQOEl+Vssh7VNp1dR8MdUJBWhuObjXCsVpjN5g==}
- engines: {node: '>=18'}
-
- '@inquirer/[email protected]':
- resolution: {integrity: sha512-BvziSRxfz5Ov8ch0z/n3oijRSEcEsHnhggm4xFZe93DHcUCTlutlq9Ox4SVENAfcRD22UQq7T/atg9Wr3k09eA==}
- engines: {node: '>=18'}
+ '@inquirer/[email protected]':
+ resolution: {integrity: sha512-t28inv14nMQ1PhKpsJPY+kEs/c00qzeCOS2gTNRyTjG5d6qsVA2fItxW4hkvGZ5lvanGLdtCzVIx5dwdRpN1+g==}
+ engines: {node: '>=23.5.0 || ^22.13.0 || ^20.17.0'}
peerDependencies:
'@types/node': '>=18'
peerDependenciesMeta:
@@ -7562,14 +7553,6 @@ packages:
cpu: [x64]
os: [win32]
- '@mswjs/[email protected]':
- resolution: {integrity: sha512-mlN83YSrcFgk7Dm1Mys40DLssI1KdJji2CMKN8eOlBqsTADYzj2+jWzsANsUTFbxDMWPD5e9bfA1RGqBpS3O1g==}
- engines: {node: '>=14'}
-
- '@mswjs/[email protected]':
- resolution: {integrity: sha512-N8x7eSLGcmUFNWZRxT1vsHvypzIRgQYdG0rJey/rZCy6zT/30qDt8Joj7FxzGNLSwXbeZqJOMqDurp7ra4hgbw==}
- engines: {node: '>=14'}
-
resolution: {integrity: sha512-cXu86tF4VQVfwz8W1SPbhoRyHJkti6mjH/XJIxp40jhO4j2k1m4KYrEykxqWPkFF3vrK4rgQppBh//AwyGSXPA==}
engines: {node: '>=18'}
@@ -7688,12 +7671,12 @@ packages:
'@open-draft/[email protected]':
resolution: {integrity: sha512-CecwLWx3rhxVQF6V4bAgPS5t+So2sTbPgAzafKkVizyi7tlwpcFpdFqq+wqF2OwNBmqFuu6tOyouTuxgpMfzmA==}
+ '@open-draft/[email protected]':
+ resolution: {integrity: sha512-XW375UK8/9SqUVNVa6M0yEy8+iTi4QN5VZ7aZuRFQmy76LRwI9wy5F4YIBU6T+eTe2/DNDo8tqu8RHlwLHM6RA==}
+
'@open-draft/[email protected]':
resolution: {integrity: sha512-X2g45fzhxH238HKO4xbSr7+wBS8Fvw6ixhTDuvLd5mqh6bJJCFAPwU9mPDxbcrRtfxv4u5IHCEH77BmxvXmmxQ==}
- '@open-draft/[email protected]':
- resolution: {integrity: sha512-Aq58f5HiWdyDlFffbbSjAlv596h/cOnt2DO1w3DOC7OJ5EHs0hd/nycJfiu9RJbT6Yk6F1knnRRXNSpxoIVZ9Q==}
-
'@open-draft/[email protected]':
resolution: {integrity: sha512-U69T3ItWHvLwGg5eJ0n3I62nWuE6ilHlmz7zM0npLBRvPRd7e6NYmg54vvRtP5mZG7kZqZCFVdsTWo7BPtBujg==}
@@ -11548,9 +11531,6 @@ packages:
resolution: {integrity: sha512-K6uROf1LD88uDQqJCktA4yzL1YYAK6NgfsI0v/mTgyPKWsX1CnJ0XPSDhViejru1GcRkLWb8RlzFYJRqGUbaug==}
- '@types/[email protected]':
- resolution: {integrity: sha512-XW/Aa8APYr6jSVVA1y/DEIZX0/GMKLEVekNG727R8cs56ahETkRAy/3DR7+fJyh7oUgGwNQaRfXCun0+KbWY7Q==}
-
resolution: {integrity: sha512-he+DHOWReW0nghN24E1WUqM0efK4kI9oTqDm6XmK8ZPe2djZ90BSNdGnIyCLzCPw7/pogPlGbzI2wHGGmi4O/Q==}
@@ -11791,9 +11771,6 @@ packages:
resolution: {integrity: sha512-XTYugzhuwqWjws0CVz8QpM36+T+Dz5mTEBKhNs/esGLnCIlGdRy+Dq78NRjd7ls7r8BC8ZRMOrKlkO1hU0JOwA==}
- '@types/[email protected]':
- resolution: {integrity: sha512-qC4bCqYGy1y/NP7dDVr7KJarn+PbX1nSpwA7JXdu0HxT3QYjO8MJ+cntENtHFVy2dRAyBV23OZ6MxsW1AM1L8g==}
-
resolution: {integrity: sha512-d0r18sZPmMQr1eG35u12FZfhIXNrnsPU/g5wvRKCUf/tOGilKKwYMYGqh33BNR6ba+2gkHw1EUiHoN3mn7E5IQ==}
@@ -11999,8 +11976,8 @@ packages:
resolution: {integrity: sha512-tRs1dB+g8Itk72rlSI2ZrW6vZg0YrLI81iQSTkMmOqnqCaNr/8Ek4VwWcN5vZgCYWbg/JJSGBlUaYGAOP73qBw==}
- '@types/[email protected]':
- resolution: {integrity: sha512-fBZgytwhYAUkj/jC/FAV4RQ5EerRup1YQsXQCh8rZfiHkc4UahC192oH0smGwsXol3cL3A5oETuAHeQHmhXM4w==}
+ '@types/[email protected]':
+ resolution: {integrity: sha512-GGmQVGpQWUe5qglJozEjZV/5dyxbOOZ0LHe/lqyWssB88Y4svNfst0uqBVscdDeIKl5Jy5+aPSvy7mI9tYRguw==}
resolution: {integrity: sha512-Ndz6x750TkuvHvdRBH8Cb7T8et2anyyY1j8kFChJ+s8FtURNRKut7DWaq9YdseKXZvqwA3ZYZxKaQRwtSq67eg==}
@@ -12547,9 +12524,6 @@ packages:
'@xyflow/[email protected]':
resolution: {integrity: sha512-1YpBo0WgmZLR5wQw9Jvk3Tu0gISi/oYc4uSimrDuAsA/G2rGleulLrKkM59uuT/QU5m6DYC2VdBDAzjSNMGuBA==}
- '@zxing/[email protected]':
- resolution: {integrity: sha512-U/4aVJ2mxI0aDNI8Uq0wEhMgY+u4CNtEb0om3+y3+niDAsoTCOB33UF0sxpzqzdqXLqmvc+vZyAt4O8pPdfkwA==}
-
resolution: {integrity: sha512-j2afSsaIENvHZN2B8GOpF566vZ5WVk5opAiMTvWgaQT8DkbOqsTfvNAvHoRGU2zzP8cPoqys+xHTRDWW8L+/BA==}
deprecated: Use your platform's native atob() and btoa() methods instead
@@ -13323,10 +13297,6 @@ packages:
resolution: {integrity: sha512-4D3B6Wf41KOYRFdszmDqMCGq5VV/uMAB273JILmO+3jAlh8X4qDtdtgCR3fxtbLEMzSx22QdhnDcJvu2u1fVwg==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-diHzdDKxcU+bAsUboHLPEDQiw0qEe0qd7SYUn3HgcFlWgbDcfLGswOHYeGrHKzG9z6UYf01d9VFMfZxPM1xZSg==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA==}
engines: {node: '>=10'}
@@ -13358,9 +13328,6 @@ packages:
resolution: {integrity: sha512-iBZ4F4wRbyORVsu0jPV7gXkOsGYjGHPmAyv+HiHG8gi5PtC9KI2j1+v8/tlibRvjoWX027ypmG/n0HtO5t7unw==}
- resolution: {integrity: sha512-PsezH1rqdV9VvyNhxxOW32/d75r01NY7TQCmOqomRo15ZSOKbpTFVsfjghxo6JloQUCGnH4k1LGu0R4yCLlWQQ==}
-
resolution: {integrity: sha512-yrLQ/yVUFXkzg7EDQsPieE/53+0RlaWTs+wBrvW36cyilJ2SaDWfl4Yj7MtLTXleV9uEKefbAGUPv2/iWSooRA==}
@@ -13479,26 +13446,14 @@ packages:
resolution: {integrity: sha512-4diC9HaTE+KRAMWhDhrGOECgWZxoevMc5TlkObMqNSsVU62PYzXZ/SMTjzyGAFF1YusgxGcSWTEXBhp0CPwQ1A==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-I/zHAwsKf9FqGoXM4WWRACob9+SNukZTd94DWF57E4toouRulbCxcUh6RKUEOQlYTHJnzkPMySvPNaaSLNfLZw==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-aCj4O5wKyszjMmDT4tZj93kxyydN/K5zPWSCe6/0AV/AA1pqe5ZBIw0a2ZfPQV7lL5/yb5HsUreJ6UFAF1tEQw==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-ywqV+5MmyL4E7ybXgKys4DugZbX0FC6LnwrhjuykIjnK9k8OQacQ7axGKnjDXWNhns0xot3bZI5h55H8yo9cJg==}
- engines: {node: '>=6'}
-
resolution: {integrity: sha512-nPdaFdQ0h/GEigbPClz11D0v/ZJEwxmeVZGeMo3Z5StPtUTkA9o1lD6QwoirYiSDzbcwn2XcjwmCp68W1IS4TA==}
engines: {node: '>=18'}
- resolution: {integrity: sha512-FxqpkPPwu1HjuN93Omfm4h8uIanXofW0RxVEW3k5RKx+mJJYSthzNhp32Kzxxy3YAEZ/Dc/EWN1vZRY0+kOhbw==}
- engines: {node: '>= 10'}
-
resolution: {integrity: sha512-ouuZd4/dm2Sw5Gmqy6bGyNNNe1qt9RpmxveLSO7KcgsTnU7RXfsw+/bukWGo1abgBiMAic068rclZsO4IWmmxQ==}
engines: {node: '>= 12'}
@@ -13520,10 +13475,6 @@ packages:
resolution: {integrity: sha512-neHB9xuzh/wk0dIHweyAXv2aPGZIVk3pLMe+/RNzINf17fe0OG96QroktYAUm7SM1PBnzTabaLboqqxDyMU+SQ==}
engines: {node: '>=6'}
- resolution: {integrity: sha512-JQHZ2QMW6l3aH/j6xCqQThY/9OH4D/9ls34cgkUBiEeocRTU04tHfKPBsUK1PqZCUQM7GiA0IIXJSuXHI64Kbg==}
- engines: {node: '>=0.8'}
-
resolution: {integrity: sha512-3Pe/CF1Nn94hyhIYpjtiLhdCoEoz0DqQ+988E9gmeEdQZlojxnOb74wctFyuwWQHzqyf9X7C7MG8juUpqBJT8w==}
engines: {node: '>=0.8'}
@@ -13707,10 +13658,6 @@ packages:
resolution: {integrity: sha512-D76uU73ulSXrD1UXF4KE2TMxVVwhsnCgfAyTg9k8P6KGZjlXKrOLe4dJQKI3Bxi5wjesZoFXJWElNWBjPZMbhg==}
engines: {node: '>=6.6.0'}
- resolution: {integrity: sha512-aSWTXFzaKWkvHO1Ny/s+ePFpvKsPnjc551iI41v3ny/ow6tBG5Vd+FuqGNhh1LxOmVzOlGUriIlOaokOvhaStA==}
- engines: {node: '>= 0.6'}
-
resolution: {integrity: sha512-yki5XnKuf750l50uGTllt6kKILY4nQ1eNIQatoXEByZ5dWgnKqbnqmTrBE5B4N7lrMJKQ2ytWMiTO2o0v6Ew/w==}
engines: {node: '>= 0.6'}
@@ -14257,9 +14204,6 @@ packages:
resolution: {integrity: sha512-eXTJmRbm2TIt9MgWTsOH1wEuhew6XGZcMeGKCtLedIg/NCsg1iBePXkceTdK4Fii7pzmN9tGsZhKzZ4h7O/fxw==}
engines: {node: '>=8'}
- resolution: {integrity: sha512-eFuaLoy/Rxalv2kr+lqMlUnrDWV+3j4pljOIJgLIhI058IQfWJ7vXhyEIHu+HtC738klGALYxOKDO0bQP3tg8A==}
-
resolution: {integrity: sha512-rBMvIzlpA8v6E+SJZoo++HAYqsLrkg7MSfIinMPFhmkorw7X+dOXVJQs+QT69zGkzMyfDnIMN2Wid1+NbL3T+A==}
engines: {node: '>= 0.4'}
@@ -14995,12 +14939,21 @@ packages:
resolution: {integrity: sha512-W+KJc2dmILlPplD/H4K9l9LcAHAfPtP6BY84uVLXQ6Evcz9Lcg33Y2z1IVblT6xdY54PXYVHEv+0Wpq8Io6zkA==}
+ resolution: {integrity: sha512-0jjjIEL6+0jag3l2XWWizO64/aZVtpiGE3t0Zgqxv0DPuxiMjvB3M24fCyhZUO4KomJQPj3LTSUnDP3GpdwC0g==}
+
+ resolution: {integrity: sha512-gX8LrtNEI5hq8DVUfRQMbr5lpaS4nMIWV+7XEbXk2b8kiQIizgnlr12B4dA3ZEx3308ze0O4Q1R+cHts8kyUJg==}
+
resolution: {integrity: sha512-VhXlQgj9ioXCqGstD37E/HBeqEGV/qOD/kmbVG8h5xKBYvM1L3lR1Zn4555cQ8GkYbJa8aJSipLPndE1k6zK2w==}
resolution: {integrity: sha512-rVjf7ArG3LTk+FS6Yw81V1DLuZl1bRbNrev6Tmd/9RaroeeRRJhAt7jg/6YFxbvAQXUCavSoZhPPj6oOx+5KjQ==}
+ resolution: {integrity: sha512-7F2Fl+TjRSenLqlU3UjSH0iyqopqoZIu7eZVpEirP2g1GtWa2G/ecEmBdgz31+Mxr+ELclgg6sokpSFIQiZ02Q==}
+
resolution: {integrity: sha512-00aAWieqff+ZJhsXA4g1g7M8k+7AYoMUUHF+/zFb5U6Uv/P0Vl4QZo84/IcufzYalLuEj9928bXN9PbbFzMF0Q==}
@@ -15053,10 +15006,6 @@ packages:
resolution: {integrity: sha512-H+K6sW6TiIX6VGend0KQwthe+kaceeH/luE8dIZyOP35ik7ahYojDuqlTV1bOrtEwl01sy2HFNGQfi5IDJvotg==}
engines: {node: '>=16'}
- resolution: {integrity: sha512-yaduQFRKLXYOGgEn6AZau90j3ggSOyiqXU0F9JZfeXYhNa+Jk4X+s45A2zg5jns87GAFa34BBm2kXw4XpNcbdg==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-d+l3qxjSesT4V7v2fh+QnmFnUWv9lSpjarhShNTgBOfA0ttejbQUAlHLitbjkoRiDulW0OPoQPYIGhIC8ohejg==}
engines: {node: '>=18'}
@@ -15543,10 +15492,6 @@ packages:
resolution: {integrity: sha512-5bJ+nf/UCpAjHM8i06fl7eLyVC9iuNAjm9qzkiu2ZGhM0VscSvS6WDPfAwkdkBuoXGM9FJSbKl6wylMwP9Ktig==}
engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
- resolution: {integrity: sha512-59LZHPdGZVh695Ud9lRzPBVTtlX9ZCV150Er2W43ro37wVof0ctenSaskPPjN7lVTIN8mSZt8PHUNKZuNQUuxw==}
- engines: {node: ^12.22.0 || ^14.16.0 || ^16.0.0 || >=17.0.0}
-
resolution: {integrity: sha512-P8/mMxVLU7o4+55+1TCnQrPmgjPKnwkzkXOK1asnR9Jg2lna4tEY5qBJjMmAaOBDDZWtlRjBXjLa0w53G/uBLA==}
@@ -15647,11 +15592,8 @@ packages:
resolution: {integrity: sha512-F/1DnUGPopORZi0ni+CvrCgHQ5FyEAHRLSApuYWMmrbSwoN2Mn/7k+Gl38gJnR7yyDZk6WLXwiGod1JOWNDKGw==}
hasBin: true
- resolution: {integrity: sha512-tUCGvt191vNSQgttSyJoibR+VO+I6+iCHIUdhzEMJKE+EAL8BwCN7fUOZlY4ofOelNHsK+gEjxB/B+9N3EWtdA==}
-
- resolution: {integrity: sha512-IScLbePpkvO846sIwOtOTDjutRMWdXdJmXdMvk6gCBHxFO8d+QKOQedyZSxFTTFYRSmlgSTDtXqqq4pcenBXLQ==}
+ resolution: {integrity: sha512-1TJ6Fih/b8h5TIcv+1+Hw0PDQWJTKDKzFZzcKOiW1wJza3XoAQlkCuXLbymPYB8+ZQyw8mHvdw560e8zVFIWyA==}
resolution: {integrity: sha512-trFMIq3PATiFRiQmNNeHtsrkwYRByIXUbYNbotiY9RLVfMkdwZdd2eQ38mGt7BRiCKBaj1DyBAIHmm7mmXPuuw==}
@@ -15920,10 +15862,6 @@ packages:
resolution: {integrity: sha512-Nb2ctOyNR8DqQoR0OwRG95uNWIC0C1lCgf5Naz5H6Ji72KZ8OcFZLz2P5sNgwlyoJ8Yif11oMuYs5pBQa86csA==}
- resolution: {integrity: sha512-UjOaSel/iddGZJ5xP/Eixh6dY1XghiBw4XK13rCCIJcJfyhhoul/7KhLLUGtebEj6GDYM6Vnx/mVsjx2L/mFIA==}
- engines: {node: '>=12.0.0'}
-
resolution: {integrity: sha512-+y6WywKZREw5rq7U2jvr2nmZpT7cbWbQQ0N/qfcseYnzHFz2cZz1Et52oY+XttYuYeTkI8Y+R2JNWj68MpQFSg==}
hasBin: true
@@ -16090,10 +16028,6 @@ packages:
resolution: {integrity: sha512-DgZQp241c8oO6cA1SbTEWiXeoxV42vlcJxgH+B3hi1AiqqKruZR3ZGF8In3fj4+/y/7rHvlOZLZtgJ/4ttYGZg==}
- resolution: {integrity: sha512-2HvIEKRoqS62guEC+qBjpvRubdX910WCMuJTZ+I9yvqKU2/12eSL549HMwtabb4oupdj2sMP50k+XJfB/8JE6w==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-1Qed0/Hr2m+YqxnM09CjA2d/i6YZNfF6R2oRAOj36eUdS6qIV/huPJNSEpKbupewFs+ZsJlxsjjPbc0/afW6Lw==}
engines: {node: '>= 0.4'}
@@ -16196,10 +16130,6 @@ packages:
resolution: {integrity: sha512-cyA56iCMHAh5CdzjJIa4aohJyeO1YbwLi3Jc35MmRU6poroFjIGZzUzupGiRPOjgHg9TLu43xbpwXk523fMxKA==}
- resolution: {integrity: sha512-knxG2q4UC3u8stRGyAVJCOdxFmv5DZiRcdlIaAQXAbSfJya+OhopNotLQrstBhququ4ZpuKbDc/8S6mgXgPFPw==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-mE00Gnza5EEB3Ds0HfMyllZzbBrmLOX3vfWoj9A9PEnTfratQ/BcaJOuMhnkhjXvb2+FkY3VuHqtAGpTPmglFQ==}
engines: {node: '>=18'}
@@ -16800,10 +16730,6 @@ packages:
resolution: {integrity: sha512-xezGJmOb4lk/M1ZZLTR/jaBHQ4gG/lqQnJqdIv4721DMggsa1bDVlHXNeHYogaIEHD9vCRv0fcL4hMA+Coarkg==}
- resolution: {integrity: sha512-X2BB11YZtrRqY4EnQcLX5Rh373zbK4alC1FW7D7MBhL2gtcC17cTnr6DmfHZeS0s2rTHjUTMMHfG7gO8SSdw+g==}
- engines: {node: '>=0.10.0'}
-
resolution: {integrity: sha512-RdJUflcE3cUzKiMqQgsCu06FPu9UdIJO0beYbPhHN4k6apgJtifcoCtT9bcxOpYBtpD2kCM6Sbzg4CausW/PKQ==}
@@ -17356,10 +17282,6 @@ packages:
resolution: {integrity: sha512-dMInicTPVE8d1e5otfwmmjlxkZoUpiVLwyeTdUsi/Caj/gfzzblBcCE5sRHV/AsjuCmxWrte2TNGSYuCeCq+0Q==}
- resolution: {integrity: sha512-8XPvpAA8uyhfteu8pIvQxpJZ7SYYdpUivZpGy6sFsBuKRY/7rQGavedeB8aK+Zkyq6upMFVL/9AW6vOYzfRyLg==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-9ie8ItPR6tjY5uYJh8K/Zrv/RMZ5VOlOWvtZdEHYSTFKZfIBPQa9tOAEeAWhd+AnIneLJ22w5fjOYtoutpWq5w==}
engines: {node: '>=18'}
@@ -17940,18 +17862,8 @@ packages:
resolution: {integrity: sha512-F9UngXRlPyWCDEASDpTf6c9uNhGPTqnTeLVt7bN+bU1eajoR/8V9ys2BRaV5C/e5ihE6sJ9uPIKaYt6bFuO32g==}
- resolution: {integrity: sha512-xX5RMSMjN58j8G/V26Uaf5LP464VltuWyd66TQimLueVYfG47RKydGsd4JW165Jb/gjoaQxh5Tdvv31wdZAOlA==}
- engines: {node: '>=14'}
- hasBin: true
- peerDependencies:
- typescript: 6.0.3
- peerDependenciesMeta:
- typescript:
- optional: true
-
- resolution: {integrity: sha512-4KXa4nVBIBjbDbd7vfQNuQ25eFxug0aropCQFoI0JdOBuJWamkT1yLVIWReFI8SiTRc+H1hKzaNk+cLk2N9rtQ==}
+ resolution: {integrity: sha512-ALe+N10S72cyx94cMcy3Zs4HhXCj35sgeAL4c+WTvKi0zWnbd8/h0lcFqv0mb2P+aSgAdD7p9HzvA0DiUPxsyg==}
engines: {node: '>=18'}
hasBin: true
peerDependencies:
@@ -17969,12 +17881,9 @@ packages:
resolution: {integrity: sha512-TvmkNhkv8yct0SVBSy+o8wYzXjE4Zz3PCesbfs8HiCXXdcTuocApFv11UWlNFWKYsP2okqrhb7JNlSm9InBhIw==}
- resolution: {integrity: sha512-nnbWWOkoWyUsTjKrhgD0dcz22mdkSnpYqbEjIm2nhwhuxlSkpywJmBo8h0ZqJdkp73mb90SssHkN4rsRaBAfAA==}
-
- resolution: {integrity: sha512-WWdIxpyjEn+FhQJQQv9aQAYlHoNVdzIzUySNV1gHUPDSdZJ3yZn7pAAbQcV7B56Mvu881q9FZV+0Vx2xC44VWA==}
- engines: {node: ^18.17.0 || >=20.5.0}
+ resolution: {integrity: sha512-dkEJPVvun4FryqBmZ5KhDo0K9iDXAwn08tMLDinNdRBNPcYEDiWYysLcc6k3mjTMlbP9KyylvRpd4wFtwrT9rw==}
+ engines: {node: ^20.17.0 || >=22.9.0}
resolution: {integrity: sha512-+MrqnJRtxdF+xngFfUUkIMQrUUL0KsxbADUkn23Z/4ibGg192Q+z+CQyiYwvWTsYjJygmMR8+w3ZDa98Zh6ESg==}
@@ -18289,10 +18198,6 @@ packages:
resolution: {integrity: sha512-JjCoypp+jKn1ttEFExxhetCKeJt9zhAgAve5FXHixTvFDW/5aEktX9bufBKLRRMdU7bNtpLfcGu94B3cdEJgjg==}
engines: {node: '>= 0.8.0'}
- resolution: {integrity: sha512-5b6Y85tPxZZ7QytO+BQzysW31HJku27cRIlkbAXaNx+BdcVi+LlRFmVXzeF6a7JCwJpyw5c4b+YSVImQIrBpuQ==}
- engines: {node: '>=10'}
-
resolution: {integrity: sha512-oGFr3T+pYdTGJ+YFEILMpS3es+GiIbs9h/XQrclBXUtd44ey7XwfsMzM31f64I1SQOawDoDr/D823kNCADI8TA==}
@@ -18313,9 +18218,6 @@ packages:
resolution: {integrity: sha512-B5JU3cabzk8c67mRRd3ECmROafjYMXbuzlwtqdM8IbS8ktlTix8aFGb2bAGKrSRIlnfKwovGUUr72JUPyOb6kQ==}
engines: {node: '>=0.10.0'}
- resolution: {integrity: sha512-AlWY719RF02ujitly7Kk/0QlV+pXGFDHrHf9O2OKqyqgBieaPOIeuSkL8sRK6j2WK+/ZAURq2kZsY0d8JapUiw==}
-
resolution: {integrity: sha512-+Sl2UErvtsoajRDKCE5/dBz4DIvHXQQnAxtQTF04OJxY0+DyZXSo5P5Bb7XYWOh81syohlYL24hbDwxedPUJCA==}
@@ -20083,10 +19985,6 @@ packages:
engines: {node: '>= 0.4'}
hasBin: true
- resolution: {integrity: sha512-l+sSefzHpj5qimhFSE5a8nufZYAM3sBSVMAPtYkmC+4EH2anSGaEMXSD0izRQbu9nfyQ9y5JrVmp7E8oZrUjvA==}
- engines: {node: '>=8'}
-
resolution: {integrity: sha512-oMA2dcrw6u0YfxJQXm342bFKX/E4sG9rbTzO9ptUcR/e8A33cHuvStiYOwH7fszkZlZ1z/ta9AAoPk2F4qIOHA==}
engines: {node: '>=18'}
@@ -20107,8 +20005,8 @@ packages:
resolution: {integrity: sha512-XQBQ3I8W1Cge0Seh+6gjj03LbmRFWuoszgK9ooCpwYIrhhoO80pfq4cUkU5DkknwfOfFteRwlZ56PYOGYyFWdg==}
engines: {node: '>= 4'}
- resolution: {integrity: sha512-uyDrIlUEH37cinabq0AX4QbgV4HbFZ/gqoiunWQ1UqBtRvTTytwhNYjE++pO/MjPTZL5KQCf2bEoJ/BJNVQ5Kw==}
+ resolution: {integrity: sha512-ILJRqVWBCTlg9r42fFgwVZx1gnFAcQF8mRoMkbgQfIrjEDf9nbBFDFx00oloOa+Q869FUtaYDXZvEfnecQSCoQ==}
resolution: {integrity: sha512-U9nH88a3fc/ekCF1l0/UP1IosiuIjyTh7hBvXVMHYgVcfGvt897Xguj2UOLDeI5BG2m7/uwyaLVT6fbtCwTyzw==}
@@ -20157,10 +20055,6 @@ packages:
resolution: {integrity: sha512-hM3dHSBMeaJ0Ktp7W38BJZ7O1zOgaFEsn41PDk+yHoEtfLV+PoJt9E9xAlZiWgf/iqEqionN0ebHFZIDAp+iGw==}
- resolution: {integrity: sha512-tvVnVv01b8c1RrA6Ep7JkStj85Guv/YrMcwqYQnwjsAS2cTmmPGBBjAjpCW7RrSodNSoE2/qg9O4bceNvUuDgQ==}
- engines: {node: '>=0.12.0'}
-
resolution: {integrity: sha512-5l4VyZR86LZ/lDxZTR6jqL8AFE2S0IFLMP26AbjsLVADxHdhB/c0GUsH+y39UfCi3dzz8OlQuPmnaJOMoDHQBA==}
@@ -20437,8 +20331,8 @@ packages:
resolution: {integrity: sha512-KiKBS8AnWGEyLzofFfmvKwpdPzqiy16LvQfK3yv/fVH7Bj13/wl3JSR1J+rfgRE9q7xUJK4qvgS8raSOeLUehw==}
- resolution: {integrity: sha512-1jeBGaKNGdEq4FgIrORu/N570dwoPYio8lSoYLWmX7sQ//0JY08Xh9o5pBcgmHQ/MbsYp/aZnOe1s1lIsbLprQ==}
+ resolution: {integrity: sha512-kjnC1DXBHcxaOaOXBHBeRtltsDG2nUiUni+jP92M9gYdW12rsmx92UsfpH7o5tDRs7I1ZZPSQJQGv3UaRfCiuw==}
resolution: {integrity: sha512-pgRc4hJ4/sNjWCSS9AmnS40x3bNMDTknHgL5UaMBTMyJnU90EgWh1Rz+MC9eFu4BuN/UwZjKQuY/1v3rM7HMfg==}
@@ -20719,9 +20613,6 @@ packages:
resolution: {integrity: sha512-0nQuG6jf1w+wddNEEXCF4nTg3LtufWINB5eFEN+5TNZW7KWJp6x87+JFL43vaAUPyCfH1wID+mNVyW6OHtFamg==}
- resolution: {integrity: sha512-KDf/ujU8Zud3YaLtMCcTI4xkZlZVIYxTLr+XIULexP+77EEVWixeXroLUXQXiVtH4XH2W7jr/3PT1v3zBuvc3A==}
-
resolution: {integrity: sha512-vMgjE/GGEPEFnhFub6pa4FmJBRBVOLpIII2hvCZ8Kzb7K0hlHo7mQv6xYrBvCL2LtAIBwFUK8wvuJgTVSQ5MFQ==}
@@ -22187,15 +22078,9 @@ packages:
resolution: {integrity: sha512-Zn5uXdcFNIA1+1Ei5McRd+iRzfhENPCe7LeABkJtNulSxjma+l7ltNx55BWZkRlwRnpOgHqxnjyaDgJnNXnqzg==}
engines: {node: '>=10.13.0'}
- resolution: {integrity: sha512-XHPEwS0q6TaxcvG85+8EYkbiCux2XtWG2mkc47Ng2A77BQu9+DqIOJldST4HgPkuea7dvKSj5VgX3P1d4rW8Tg==}
-
resolution: {integrity: sha512-DEAoo25RfSYMuTGc9vPJzZcZullwIqRDSI9LOy+fkCJPi6hykCnfKaXTuPBDuXAUcqHXyOgFtHNp/kB2FjYHbw==}
- resolution: {integrity: sha512-HYLeVCdJ0+lBYV2FvNZmv3HJ2Nt0QYXqZojk3d9FJOLkwnuhzM9tmamh8d7HPM8QqjKH8DeHkFTx+CFlWpZZDA==}
-
resolution: {integrity: sha512-d2JWLCivmZYTSIoge9MsgFCZrt571BikcWGYkjC1khllbTeDlGqZ2D8vD8E/lJa8WGWbb7Plm8/XJYV7IJHZZw==}
engines: {node: '>= 8'}
@@ -22295,9 +22180,6 @@ packages:
engines: {node: '>=18'}
deprecated: Use @exodus/bytes instead for a more spec-conformant and faster implementation
- resolution: {integrity: sha512-bJlen0FcuU/0EMLrdbJ7zOnW6ITZLrZMIarMUVmdKtsGvZna8vxKYaexICWPfZ8qwf9fzNq+UEIZrnSaApt6RA==}
-
resolution: {integrity: sha512-M4yMwr6mAnQz76TbJm914+gPpB/nCwvZbJU28cUD6dR004SAxDLOOSUaB1JDRqLtaOV/vi0IC5lEAGFgrjGv/g==}
@@ -22582,10 +22464,6 @@ packages:
resolution: {integrity: sha512-4LCcse/U2MHZ63HAJVE+v71o7yOdIe4cZ70Wpf8D/IyjDKYQLV5GD46B+hSTjJsvV5PztjvHoU580EftxjDZFQ==}
engines: {node: '>=12.20'}
- resolution: {integrity: sha512-U/PBtDf35ff0D8X8D0jfdzHYEPFxAI7jJlxZXwCSez5M3190m+QobIfh+sWDWSHMCWWJN2AWamkegn6vr6YBTw==}
- engines: {node: '>=18'}
-
resolution: {integrity: sha512-CzhO+pFNo8ajLM2d2IW/R93ipy99LWjtwblvC1RsoSUMZgyLbYFr221TnSNT7GjGdYui6P459mw9JH/g/zW2ug==}
engines: {node: '>=18'}
@@ -25008,14 +24886,14 @@ snapshots:
optionalDependencies:
workerd: 1.20260603.1
dependencies:
'@vitest/runner': 4.1.8
'@vitest/snapshot': 4.1.8
cjs-module-lexer: 1.2.3
esbuild: 0.27.3
miniflare: 4.20260603.0
wrangler: 4.98.0(@cloudflare/[email protected])
zod: 3.25.76
transitivePeerDependencies:
@@ -26108,64 +25986,55 @@ snapshots:
optional: true
- '@inquirer/[email protected]': {}
+ '@inquirer/[email protected]': {}
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
- '@inquirer/core': 10.3.2(@types/[email protected])
- '@inquirer/type': 3.0.10(@types/[email protected])
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
optionalDependencies:
'@types/node': 22.18.8
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
- '@inquirer/core': 10.3.2(@types/[email protected])
- '@inquirer/type': 3.0.10(@types/[email protected])
+ '@inquirer/core': 11.2.1(@types/[email protected])
+ '@inquirer/type': 4.0.7(@types/[email protected])
optionalDependencies:
'@types/node': 25.8.0
optional: true
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
- '@inquirer/ansi': 1.0.2
- '@inquirer/figures': 1.0.15
- '@inquirer/type': 3.0.10(@types/[email protected])
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
cli-width: 4.1.0
- mute-stream: 2.0.0
+ fast-wrap-ansi: 0.2.2
+ mute-stream: 3.0.0
signal-exit: 4.1.0
- wrap-ansi: 6.2.0
- yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 22.18.8
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
dependencies:
- '@inquirer/ansi': 1.0.2
- '@inquirer/figures': 1.0.15
- '@inquirer/type': 3.0.10(@types/[email protected])
+ '@inquirer/ansi': 2.0.7
+ '@inquirer/figures': 2.0.7
+ '@inquirer/type': 4.0.7(@types/[email protected])
cli-width: 4.1.0
- mute-stream: 2.0.0
+ fast-wrap-ansi: 0.2.2
+ mute-stream: 3.0.0
signal-exit: 4.1.0
- wrap-ansi: 6.2.0
- yoctocolors-cjs: 2.1.3
optionalDependencies:
'@types/node': 25.8.0
optional: true
- '@inquirer/[email protected](@types/[email protected])':
- dependencies:
- chardet: 2.1.1
- iconv-lite: 0.7.2
- optionalDependencies:
- '@types/node': 22.18.8
-
- '@inquirer/[email protected]': {}
+ '@inquirer/[email protected]': {}
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
optionalDependencies:
'@types/node': 22.18.8
- '@inquirer/[email protected](@types/[email protected])':
+ '@inquirer/[email protected](@types/[email protected])':
optionalDependencies:
'@types/node': 25.8.0
optional: true
@@ -27185,24 +27054,6 @@ snapshots:
'@msgpackr-extract/[email protected]':
optional: true
- '@mswjs/[email protected]':
- dependencies:
- '@types/set-cookie-parser': 2.4.2
- set-cookie-parser: 2.5.1
-
- '@mswjs/[email protected]':
- dependencies:
- '@open-draft/until': 1.0.3
- '@types/debug': 4.1.7
- '@xmldom/xmldom': 0.8.13
- debug: 4.4.3
- headers-polyfill: 3.2.5
- outvariant: 1.4.3
- strict-event-emitter: 0.2.8
- web-encoding: 1.1.5
- transitivePeerDependencies:
- - supports-color
-
dependencies:
'@open-draft/deferred-promise': 2.2.0
@@ -27298,13 +27149,13 @@ snapshots:
'@open-draft/[email protected]': {}
+ '@open-draft/[email protected]': {}
+
'@open-draft/[email protected]':
dependencies:
is-node-process: 1.2.0
outvariant: 1.4.3
- '@open-draft/[email protected]': {}
-
'@open-draft/[email protected]': {}
'@opentelemetry/[email protected]':
@@ -31968,8 +31819,6 @@ snapshots:
dependencies:
'@types/node': 22.18.8
- '@types/[email protected]': {}
-
'@types/[email protected]': {}
@@ -32263,8 +32112,6 @@ snapshots:
expect: 30.0.5
pretty-format: 30.0.5
- '@types/[email protected]': {}
-
dependencies:
'@types/node': 22.18.8
@@ -32498,7 +32345,7 @@ snapshots:
'@types/node': 22.18.8
'@types/send': 0.17.6
- '@types/[email protected]':
+ '@types/[email protected]':
dependencies:
'@types/node': 22.18.8
@@ -32939,22 +32786,22 @@ snapshots:
chai: 6.2.2
tinyrainbow: 3.1.0
dependencies:
'@vitest/spy': 4.1.8
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- msw: 2.12.14(@types/[email protected])([email protected])
+ msw: 2.14.6(@types/[email protected])([email protected])
dependencies:
'@vitest/spy': 4.1.8
estree-walker: 3.0.3
magic-string: 0.30.21
optionalDependencies:
- msw: 2.12.14(@types/[email protected])([email protected])
+ msw: 2.14.6(@types/[email protected])([email protected])
'@vitest/[email protected]':
@@ -33173,9 +33020,6 @@ snapshots:
d3-selection: 3.0.0
d3-zoom: 3.0.0
- '@zxing/[email protected]':
- optional: true
-
@@ -34136,11 +33980,6 @@ snapshots:
ansi-styles: 4.3.0
supports-color: 7.2.0
- dependencies:
- ansi-styles: 4.3.0
- supports-color: 7.2.0
-
dependencies:
ansi-styles: 4.3.0
@@ -34162,8 +34001,6 @@ snapshots:
-
@@ -34283,23 +34120,15 @@ snapshots:
- dependencies:
- restore-cursor: 3.1.0
-
dependencies:
restore-cursor: 5.1.0
-
dependencies:
slice-ansi: 5.0.0
string-width: 7.2.0
-
@@ -34332,8 +34161,6 @@ snapshots:
kind-of: 6.0.3
shallow-clone: 3.0.1
-
@@ -34480,8 +34307,6 @@ snapshots:
-
@@ -35143,10 +34968,6 @@ snapshots:
dependencies:
strip-bom: 4.0.0
- dependencies:
- clone: 1.0.4
-
dependencies:
es-define-property: 1.0.1
@@ -36216,10 +36037,20 @@ snapshots:
+
+ dependencies:
+ fast-string-truncated-width: 3.0.3
+
+ dependencies:
+ fast-string-width: 3.0.2
+
dependencies:
path-expression-matcher: 1.5.0
@@ -36274,10 +36105,6 @@ snapshots:
- supports-color
optional: true
- dependencies:
- escape-string-regexp: 1.0.5
-
dependencies:
is-unicode-supported: 2.1.0
@@ -36849,8 +36676,6 @@ snapshots:
-
@@ -36991,9 +36816,10 @@ snapshots:
-
+ dependencies:
+ '@types/set-cookie-parser': 2.4.10
+ set-cookie-parser: 3.1.0
@@ -37285,26 +37111,6 @@ snapshots:
- dependencies:
- '@inquirer/external-editor': 1.0.3(@types/[email protected])
- ansi-escapes: 4.3.2
- chalk: 4.1.2
- cli-cursor: 3.1.0
- cli-width: 3.0.0
- figures: 3.2.0
- lodash: 4.18.1
- mute-stream: 0.0.8
- ora: 5.4.1
- run-async: 2.4.1
- rxjs: 7.8.1
- string-width: 4.2.3
- strip-ansi: 6.0.1
- through: 2.3.8
- wrap-ansi: 6.2.0
- transitivePeerDependencies:
- - '@types/node'
-
@@ -37471,8 +37277,6 @@ snapshots:
-
@@ -37553,8 +37357,6 @@ snapshots:
-
@@ -39030,8 +38832,6 @@ snapshots:
-
@@ -39606,11 +39406,6 @@ snapshots:
- dependencies:
- chalk: 4.1.2
- is-unicode-supported: 0.1.0
-
dependencies:
ansi-escapes: 7.0.0
@@ -40475,48 +40270,20 @@ snapshots:
optionalDependencies:
msgpackr-extract: 3.0.3
dependencies:
- '@mswjs/cookies': 0.2.2
- '@mswjs/interceptors': 0.17.10
- '@open-draft/until': 1.0.3
- '@types/cookie': 0.4.1
- '@types/js-levenshtein': 1.1.1
- chalk: 4.1.1
- chokidar: 3.6.0
- cookie: 0.4.2
- graphql: 16.8.1
- headers-polyfill: 3.2.5
- inquirer: 8.2.7(@types/[email protected])
- is-node-process: 1.2.0
- js-levenshtein: 1.1.6
- node-fetch: 2.6.9([email protected])
- outvariant: 1.4.0
- path-to-regexp: 6.3.0
- strict-event-emitter: 0.2.8
- type-fest: 2.19.0
- yargs: 17.7.1
- optionalDependencies:
- typescript: 6.0.3
- transitivePeerDependencies:
- - '@types/node'
- - encoding
- - supports-color
-
- dependencies:
- '@inquirer/confirm': 5.1.21(@types/[email protected])
+ '@inquirer/confirm': 6.1.1(@types/[email protected])
'@mswjs/interceptors': 0.41.3
- '@open-draft/deferred-promise': 2.2.0
+ '@open-draft/deferred-promise': 3.0.0
'@types/statuses': 2.0.6
cookie: 1.1.1
graphql: 16.13.2
- headers-polyfill: 4.0.3
+ headers-polyfill: 5.0.1
is-node-process: 1.2.0
outvariant: 1.4.3
path-to-regexp: 6.3.0
picocolors: 1.1.1
- rettime: 0.10.1
+ rettime: 0.11.11
statuses: 2.0.2
strict-event-emitter: 0.5.1
tough-cookie: 6.0.1
@@ -40528,20 +40295,20 @@ snapshots:
transitivePeerDependencies:
- '@types/node'
dependencies:
- '@inquirer/confirm': 5.1.21(@types/[email protected])
+ '@inquirer/confirm': 6.1.1(@types/[email protected])
'@mswjs/interceptors': 0.41.3
- '@open-draft/deferred-promise': 2.2.0
+ '@open-draft/deferred-promise': 3.0.0
'@types/statuses': 2.0.6
cookie: 1.1.1
graphql: 16.13.2
- headers-polyfill: 4.0.3
+ headers-polyfill: 5.0.1
is-node-process: 1.2.0
outvariant: 1.4.3
path-to-regexp: 6.3.0
picocolors: 1.1.1
- rettime: 0.10.1
+ rettime: 0.11.11
statuses: 2.0.2
strict-event-emitter: 0.5.1
tough-cookie: 6.0.1
@@ -40563,9 +40330,7 @@ snapshots:
-
@@ -40895,18 +40660,6 @@ snapshots:
prelude-ls: 1.2.1
type-check: 0.4.0
- dependencies:
- bl: 4.1.0
- chalk: 4.1.2
- cli-cursor: 3.1.0
- cli-spinners: 2.9.2
- is-interactive: 1.0.0
- is-unicode-supported: 0.1.0
- log-symbols: 4.1.0
- strip-ansi: 6.0.1
- wcwidth: 1.0.1
-
@@ -40952,8 +40705,6 @@ snapshots:
-
@@ -43168,11 +42919,6 @@ snapshots:
path-parse: 1.0.7
supports-preserve-symlinks-flag: 1.0.0
- dependencies:
- onetime: 5.1.2
- signal-exit: 3.0.7
-
dependencies:
onetime: 7.0.0
@@ -43198,7 +42944,7 @@ snapshots:
@@ -43278,8 +43024,6 @@ snapshots:
dependencies:
tslib: 2.8.1
-
dependencies:
queue-microtask: 1.2.3
@@ -43538,7 +43282,7 @@ snapshots:
dependencies:
@@ -43904,10 +43648,6 @@ snapshots:
- bare-abort-controller
- react-native-b4a
- dependencies:
- events: 3.3.0
-
@@ -45394,10 +45134,10 @@ snapshots:
tsx: 4.20.5
yaml: 2.9.0
dependencies:
'@vitest/expect': 4.1.8
'@vitest/pretty-format': 4.1.8
'@vitest/runner': 4.1.8
'@vitest/snapshot': 4.1.8
@@ -45424,10 +45164,10 @@ snapshots:
transitivePeerDependencies:
- msw
dependencies:
'@vitest/expect': 4.1.8
'@vitest/pretty-format': 4.1.8
'@vitest/runner': 4.1.8
'@vitest/snapshot': 4.1.8
@@ -45508,18 +45248,8 @@ snapshots:
glob-to-regexp: 0.4.1
graceful-fs: 4.2.11
- dependencies:
- defaults: 1.0.4
-
- dependencies:
- util: 0.12.5
- optionalDependencies:
- '@zxing/text-encoding': 0.9.0
-
@@ -45680,8 +45410,6 @@ snapshots:
dependencies:
iconv-lite: 0.6.3
-
@@ -46005,8 +45733,6 @@ snapshots:
-
diff --git a/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx b/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
index d2613b26efa1..03808155c883 100644
--- a/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
+++ b/products/ai_observability/frontend/AIObservabilityTraceScene.stories.tsx
@@ -30,8 +30,11 @@ const meta: Meta<AIObservabilityTraceSceneProps> = {
render: ({ trace, eventId }) => {
useStorybookMocks({
post: {
- '/api/environments/:team_id/query/:kind/': (req) => {
- if (getEffectiveQueryKind(req) === 'TraceQuery') {
+ '/api/environments/:team_id/query/:kind/': async ({ request }) => {
+ const body = (await request.json()) as {
+ query?: { kind?: string; source?: { kind?: string } }
+ }
+ if (getEffectiveQueryKind({ body }) === 'TraceQuery') {
return [200, { results: [trace] }]
}
},
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
index 7c994243816a..78cdcc6f08b9 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationLogic.test.ts
@@ -844,11 +844,11 @@ describe('llmEvaluationLogic', () => {
'/api/environments/:teamId/evaluations/:id/': mockEvaluation,
},
patch: {
- '/api/environments/:teamId/evaluations/:id/': (_, __, ctx) => [
- ctx.status(400),
- ctx.json({
+ '/api/environments/:teamId/evaluations/:id/': () => [
+ 400,
+ {
enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],
- }),
+ },
],
},
})
diff --git a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
index 98ef033b878e..1806dc9ee618 100644
--- a/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
+++ b/products/ai_observability/frontend/evaluations/llmEvaluationsLogic.test.ts
@@ -143,11 +143,11 @@ describe('llmEvaluationsLogic', () => {
it('dispatches toggleEvaluationEnabledFailure when the API rejects the toggle', async () => {
useMocks({
patch: {
- '/api/environments/:teamId/evaluations/:id/': (_, __, ctx) => [
- ctx.status(400),
- ctx.json({
+ '/api/environments/:teamId/evaluations/:id/': () => [
+ 400,
+ {
enabled: ['Trial evaluation limit reached. Add a provider API key to re-enable.'],
- }),
+ },
],
},
})
diff --git a/products/ai_observability/frontend/modelPickerLogic.test.ts b/products/ai_observability/frontend/modelPickerLogic.test.ts
index 43d6a3b961ee..605955c5c08e 100644
--- a/products/ai_observability/frontend/modelPickerLogic.test.ts
+++ b/products/ai_observability/frontend/modelPickerLogic.test.ts
@@ -54,8 +54,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'key-1') {
return [200, BYOK_OPENAI_MODELS]
}
return [200, []]
@@ -88,8 +88,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'key-1') {
return [200, BYOK_OPENAI_MODELS_MIXED]
}
return [200, []]
@@ -142,8 +142,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- const keyId = req.url.searchParams.get('provider_key_id')
+ '/api/llm_proxy/models/': ({ request }) => {
+ const keyId = new URL(request.url).searchParams.get('provider_key_id')
if (keyId === 'key-1') {
return [200, BYOK_OPENAI_MODELS]
}
@@ -177,8 +177,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- const keyId = req.url.searchParams.get('provider_key_id')
+ '/api/llm_proxy/models/': ({ request }) => {
+ const keyId = new URL(request.url).searchParams.get('provider_key_id')
if (keyId === 'key-1') {
return [500, { error: 'Internal error' }]
}
@@ -287,8 +287,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- const keyId = req.url.searchParams.get('provider_key_id')
+ '/api/llm_proxy/models/': ({ request }) => {
+ const keyId = new URL(request.url).searchParams.get('provider_key_id')
if (keyId === 'key-1') {
return [200, BYOK_OPENAI_MODELS]
}
@@ -327,8 +327,8 @@ describe('modelPickerLogic', () => {
'/api/environments/:team_id/llm_analytics/evaluation_config/': {
active_provider_key: null,
},
- '/api/llm_proxy/models/': (req: any) => {
- const keyId = req.url.searchParams.get('provider_key_id')
+ '/api/llm_proxy/models/': ({ request }) => {
+ const keyId = new URL(request.url).searchParams.get('provider_key_id')
if (keyId === 'key-1' || keyId === 'key-2') {
return [200, BYOK_OPENAI_MODELS]
}
diff --git a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
index f07082181e62..342e51e740e1 100644
--- a/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
+++ b/products/ai_observability/frontend/playground/llmPlaygroundLogic.test.ts
@@ -234,8 +234,8 @@ describe('llmPlaygroundLogic', () => {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [{ id: 'openrouter-key-1', provider: 'openrouter', state: 'ok' }],
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'openrouter-key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'openrouter-key-1') {
return [200, byokModels]
}
return [200, MOCK_MODEL_OPTIONS]
@@ -279,8 +279,8 @@ describe('llmPlaygroundLogic', () => {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [{ id: 'openrouter-key-1', provider: 'openrouter', state: 'ok' }],
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'openrouter-key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'openrouter-key-1') {
return [200, byokModels]
}
return [200, MOCK_MODEL_OPTIONS]
@@ -325,8 +325,8 @@ describe('llmPlaygroundLogic', () => {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [{ id: 'openrouter-key-1', provider: 'openrouter', state: 'ok' }],
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'openrouter-key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'openrouter-key-1') {
return [200, byokModels]
}
return [200, MOCK_MODEL_OPTIONS]
@@ -367,8 +367,8 @@ describe('llmPlaygroundLogic', () => {
{ id: 'openrouter-key-a', provider: 'openrouter', name: 'A key', state: 'ok' },
],
},
- '/api/llm_proxy/models/': (req: any) => {
- const providerKeyId = req.url.searchParams.get('provider_key_id')
+ '/api/llm_proxy/models/': ({ request }) => {
+ const providerKeyId = new URL(request.url).searchParams.get('provider_key_id')
if (providerKeyId === 'openrouter-key-z' || providerKeyId === 'openrouter-key-a') {
return [
200,
@@ -423,8 +423,8 @@ describe('llmPlaygroundLogic', () => {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [{ id: 'openrouter-key-1', provider: 'openrouter', state: 'ok' }],
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'openrouter-key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'openrouter-key-1') {
return [200, byokModels]
}
return [200, MOCK_MODEL_OPTIONS]
@@ -725,8 +725,8 @@ describe('llmPlaygroundLogic', () => {
'/api/environments/:team_id/llm_analytics/provider_keys/': {
results: [{ id: 'key-1', provider: 'openai', state: 'ok' }],
},
- '/api/llm_proxy/models/': (req: any) => {
- if (req.url.searchParams.get('provider_key_id') === 'key-1') {
+ '/api/llm_proxy/models/': ({ request }) => {
+ if (new URL(request.url).searchParams.get('provider_key_id') === 'key-1') {
return [200, byokModels]
}
return [200, MOCK_MODEL_OPTIONS]
@@ -1819,9 +1819,10 @@ describe('llmPlaygroundLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/llm_prompts/name/:name/': (req: any) => {
- updatedPrompt = req.body.prompt
- return [200, { id: 'prompt-linked', name: 'linked', prompt: req.body.prompt }]
+ '/api/environments/:team_id/llm_prompts/name/:name/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ updatedPrompt = body.prompt
+ return [200, { id: 'prompt-linked', name: 'linked', prompt: body.prompt }]
},
},
})
diff --git a/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts b/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts
index 1e358974c405..2048d9c34adb 100644
--- a/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts
+++ b/products/ai_observability/frontend/tags/llmTaggerLogic.test.ts
@@ -376,7 +376,8 @@ describe('llmTaggerLogic', () => {
},
})
const errors = await submitAndGetErrors()
- expect(errors.tagger_config.tags).toBeUndefined()
+ // A valid form submits successfully, so errors may be cleared entirely
+ expect(errors?.tagger_config?.tags).toBeUndefined()
})
it('reports error when every tag row is blank', async () => {
@@ -402,9 +403,9 @@ describe('llmTaggerLogic', () => {
})
const errors = await submitAndGetErrors()
- expect(errors.name).toBeUndefined()
- expect(errors.tagger_config.prompt).toBeUndefined()
- expect(errors.tagger_config.tags).toBeUndefined()
+ expect(errors?.name).toBeUndefined()
+ expect(errors?.tagger_config?.prompt).toBeUndefined()
+ expect(errors?.tagger_config?.tags).toBeUndefined()
})
})
@@ -429,10 +430,10 @@ describe('llmTaggerLogic', () => {
tagger_config: { source: 'return []', tags: [] },
})
const errors = await submitAndGetErrors()
- expect(errors.name).toBeUndefined()
- expect(errors.tagger_config.source).toBeUndefined()
- expect(errors.tagger_config).not.toHaveProperty('prompt')
- expect(errors.tagger_config).not.toHaveProperty('tags')
+ expect(errors?.name).toBeUndefined()
+ expect(errors?.tagger_config?.source).toBeUndefined()
+ expect(errors?.tagger_config ?? {}).not.toHaveProperty('prompt')
+ expect(errors?.tagger_config ?? {}).not.toHaveProperty('tags')
})
})
})
@@ -560,15 +561,15 @@ describe('llmTaggerLogic', () => {
[`/api/environments/:team_id/taggers/${taggerId}/`]: mockTagger,
},
post: {
- '/api/environments/:team_id/query/:kind': async (req, res, ctx) => {
- const body = (await req.json()) as { query?: { query?: string; values?: unknown } }
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as { query?: { query?: string; values?: unknown } }
if (body.query?.query?.includes('$ai_tagger_id')) {
capturedQueries.push({
query: body.query.query,
values: body.query.values,
})
}
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
})
diff --git a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts b/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts
index 38287e20255e..a4f0b2dd4725 100644
--- a/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts
+++ b/products/ai_observability/frontend/tags/llmTaggersLogic.test.ts
@@ -115,9 +115,10 @@ describe('llmTaggersLogic', () => {
},
},
post: {
- '/api/environments/:team_id/taggers/': (req: any) => {
- createCalls.push(req.body)
- return [200, { id: `new-${createCalls.length}`, ...req.body }]
+ '/api/environments/:team_id/taggers/': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
+ createCalls.push(body)
+ return [200, { id: `new-${createCalls.length}`, ...body }]
},
},
})
diff --git a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
index 7d6a2c7c6021..c23e464ded65 100644
--- a/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
+++ b/products/conversations/frontend/scenes/settings/supportSettingsLogic.test.ts
@@ -15,7 +15,7 @@ describe('supportSettingsLogic', () => {
'api/conversations/v1/email/status': { configs: [] },
},
post: {
- 'api/environments/:team_id/': (req: any) => [200, req.body],
+ 'api/environments/:team_id/': async ({ request }) => [200, await request.json()],
},
})
initKeaTests()
diff --git a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
index dd59607bd0a7..27a1f8df3f7f 100644
--- a/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
+++ b/products/customer_analytics/frontend/components/Accounts/AccountsTab.stories.tsx
@@ -7,6 +7,7 @@ import { App } from 'scenes/App'
import { urls } from 'scenes/urls'
import { mswDecorator } from '~/mocks/browser'
+import type { MockResolverInfo } from '~/mocks/utils'
const QUERY_ENDPOINT = '/api/environments/:team_id/query/:kind/'
const ACCOUNT_RETRIEVE_ENDPOINT = 'api/projects/:team_id/accounts/:account_id/'
@@ -145,9 +146,10 @@ const USAGE_QUERY_RESPONSE = {
function mockAccountsAndBillingQuery(
rows: AccountRow[],
billingResponse: Record<string, unknown>
-): (req: { body: unknown }) => [number, unknown] | undefined {
- return (req) => {
- const kind = (req.body as { query?: { kind?: string } })?.query?.kind
+): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
+ return async ({ request }) => {
+ const body = (await request.json()) as { query?: { kind?: string } }
+ const kind = body?.query?.kind
if (kind === 'AccountsQuery') {
return [200, buildAccountsQueryResponse(rows)]
}
@@ -161,7 +163,7 @@ function mockAccountsAndBillingQuery(
// Billing tab stories share the same account + notebooks mocks; they differ only in the insight and query responses.
function billingTabDecorators(
insightsGet: Record<string, unknown>,
- queryPost: (req: { body: unknown }) => [number, unknown] | undefined
+ queryPost: (info: MockResolverInfo) => Promise<[number, unknown] | undefined>
): ReturnType<typeof mswDecorator>[] {
return [
mswDecorator({
@@ -199,9 +201,10 @@ async function expandAndOpenTab(canvasElement: HTMLElement, tab: 'Usage' | 'Spen
await userEvent.click(await canvas.findByRole('tab', { name: tab }))
}
-function mockAccountsQuery(rows: AccountRow[]): (req: { body: unknown }) => [number, unknown] | undefined {
- return (req) => {
- const kind = (req.body as { query?: { kind?: string } })?.query?.kind
+function mockAccountsQuery(rows: AccountRow[]): (info: MockResolverInfo) => Promise<[number, unknown] | undefined> {
+ return async ({ request }) => {
+ const body = (await request.json()) as { query?: { kind?: string } }
+ const kind = body?.query?.kind
if (kind === 'AccountsQuery') {
return [200, buildAccountsQueryResponse(rows)]
}
diff --git a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
index 687d0684b6e6..022314543d32 100644
--- a/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
+++ b/products/customer_analytics/frontend/components/Accounts/accountsViewsLogic.test.ts
@@ -134,8 +134,8 @@ describe('accountsViewsLogic', () => {
useMocks({
get: { '/api/environments/:team_id/column_configurations/': { count: 1, results: [buildView()] } },
patch: {
- '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {
- patchedBody = await req.json()
+ '/api/environments/:team_id/column_configurations/:id/': async ({ request }) => {
+ patchedBody = await request.json()
return [200, buildView({ name: patchedBody.name })]
},
},
@@ -165,8 +165,8 @@ describe('accountsViewsLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {
- patchedBody = await req.json()
+ '/api/environments/:team_id/column_configurations/:id/': async ({ request }) => {
+ patchedBody = await request.json()
return [200, buildView({ properties: patchedBody.properties })]
},
},
@@ -240,8 +240,8 @@ describe('accountsViewsLogic', () => {
},
},
patch: {
- '/api/environments/:team_id/column_configurations/:id/': async (req: any) => {
- const body = await req.json()
+ '/api/environments/:team_id/column_configurations/:id/': async ({ request }) => {
+ const body = (await request.json()) as any
return [200, buildView({ properties: body.properties })]
},
},
diff --git a/products/error_tracking/frontend/ErrorTracking.stories.tsx b/products/error_tracking/frontend/ErrorTracking.stories.tsx
index 79c71832dae5..e7675086c107 100644
--- a/products/error_tracking/frontend/ErrorTracking.stories.tsx
+++ b/products/error_tracking/frontend/ErrorTracking.stories.tsx
@@ -23,15 +23,11 @@ const meta: Meta = {
decorators: [
mswDecorator({
get: {
- 'api/projects/:team_id/error_tracking/issue/:id': async (_, res, ctx) => {
- return res(ctx.json(errorTrackingTypeIssue))
- },
+ 'api/projects/:team_id/error_tracking/issue/:id': () => [200, errorTrackingTypeIssue],
},
post: {
- '/api/environments/:team_id/query/ErrorTrackingQuery': async (_, res, ctx) =>
- res(ctx.json(errorTrackingQueryResponse)),
- '/api/environments/:team_id/query/EventsQuery': async (_, res, ctx) =>
- res(ctx.json(errorTrackingEventsQueryResponse)),
+ '/api/environments/:team_id/query/ErrorTrackingQuery': () => [200, errorTrackingQueryResponse],
+ '/api/environments/:team_id/query/EventsQuery': () => [200, errorTrackingEventsQueryResponse],
},
}),
],
diff --git a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
index 99acb0d0ed3f..82abd5720e16 100644
--- a/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
+++ b/products/error_tracking/frontend/components/ExceptionCard/ExceptionCard.stories.tsx
@@ -407,9 +407,9 @@ function sessionTimelineParameters(event: ErrorEventType): Record<string, unknow
.slice(0, limit)
}
- const queryHandler = async (req: any, res: any, ctx: any): Promise<unknown> => {
- const body = await req.clone().json()
- const query = body.query as TimelineQueryLike
+ const queryHandler = async ({ request }: { request: Request }): Promise<unknown> => {
+ const body = (await request.json()) as { query: TimelineQueryLike }
+ const query = body.query
if (query.kind === NodeKind.EventsQuery) {
const isCombinedEventLoaderQuery =
@@ -418,7 +418,7 @@ function sessionTimelineParameters(event: ErrorEventType): Record<string, unknow
query.select?.includes('properties.$exception_list')
if (isCombinedEventLoaderQuery) {
- return res(ctx.json({ results: filterRows(combinedEventRows, 2, query) }))
+ return [200, { results: filterRows(combinedEventRows, 2, query) }]
}
const isEventDetailsQuery =
@@ -433,29 +433,29 @@ function sessionTimelineParameters(event: ErrorEventType): Record<string, unknow
const uuidMatch =
typeof uuidClause === 'string' ? uuidClause.match(/equals\(uuid,\s*'([^']+)'\)/) : null
const eventRow = uuidMatch ? eventDetailsRowsByUuid[uuidMatch[1]] : null
- return res(ctx.json({ results: eventRow ? [eventRow] : [] }))
+ return [200, { results: eventRow ? [eventRow] : [] }]
}
if (query.select?.includes('properties.$current_url')) {
- return res(ctx.json({ results: filterRows(pageRows, 1, query) }))
+ return [200, { results: filterRows(pageRows, 1, query) }]
}
if (query.select?.includes('event')) {
- return res(ctx.json({ results: filterRows(customRows, 2, query) }))
+ return [200, { results: filterRows(customRows, 2, query) }]
}
if (query.select?.includes('properties')) {
- return res(ctx.json({ results: filterRows(exceptionRows, 1, query) }))
+ return [200, { results: filterRows(exceptionRows, 1, query) }]
}
- return res(ctx.json({ results: filterRows(combinedEventRows, 2, query) }))
+ return [200, { results: filterRows(combinedEventRows, 2, query) }]
}
if (query.kind === NodeKind.HogQLQuery) {
- return res(ctx.json({ results: filterLogRowsFromHogQL(logRows, query) }))
+ return [200, { results: filterLogRowsFromHogQL(logRows, query) }]
}
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
}
return {
diff --git a/products/logs/frontend/LogsScene.stories.tsx b/products/logs/frontend/LogsScene.stories.tsx
index 64f89f409fa7..c40d2f90166a 100644
--- a/products/logs/frontend/LogsScene.stories.tsx
+++ b/products/logs/frontend/LogsScene.stories.tsx
@@ -223,10 +223,10 @@ const getLogs = async (
}
}
-const queryMock: MockSignature = async (req, res, ctx) => {
+const queryMock: MockSignature = async ({ request }) => {
await delayIfNotTestRunner()
- const body = await req.json()
+ const body = (await request.json()) as Record<string, any>
const { logs } = await getLogs(body)
const limit = body.query?.limit ?? 100
@@ -234,12 +234,12 @@ const queryMock: MockSignature = async (req, res, ctx) => {
const results = logs.slice(offset, offset + limit)
- return res(ctx.json({ results: results, maxExportableLogs: 5000 }))
+ return [200, { results: results, maxExportableLogs: 5000 }]
}
-const sparklineMock: MockSignature = async (req, res, ctx) => {
+const sparklineMock: MockSignature = async ({ request }) => {
await delayIfNotTestRunner()
- const body = await req.json()
+ const body = (await request.json()) as Record<string, any>
const { startTime, endTime, logs } = await getLogs(body)
// Interval selection
@@ -307,12 +307,12 @@ const sparklineMock: MockSignature = async (req, res, ctx) => {
})
)
- return res(ctx.json(results))
+ return [200, results]
}
-const attributesMock: MockSignature = async (req, res, ctx) => {
+const attributesMock: MockSignature = async ({ request }) => {
await delayIfNotTestRunner()
- const type = (req.url.searchParams.get('attribute_type') ?? 'log_attribute') as
+ const type = (new URL(request.url).searchParams.get('attribute_type') ?? 'log_attribute') as
| PropertyFilterType.LogAttribute
| PropertyFilterType.LogResourceAttribute
const results = Object.keys(attributeExamples[type]).map((key) => ({
@@ -320,20 +320,21 @@ const attributesMock: MockSignature = async (req, res, ctx) => {
name: key,
type: type,
}))
- return res(ctx.json(results))
+ return [200, results]
}
-const valuesMock: MockSignature = async (req, res, ctx) => {
+const valuesMock: MockSignature = async ({ request }) => {
await delayIfNotTestRunner()
- const key = req.url.searchParams.get('key') ?? ''
- const type = (req.url.searchParams.get('attribute_type') ?? 'log_attribute') as
+ const url = new URL(request.url)
+ const key = url.searchParams.get('key') ?? ''
+ const type = (url.searchParams.get('attribute_type') ?? 'log_attribute') as
| PropertyFilterType.LogAttribute
| PropertyFilterType.LogResourceAttribute
const results = (attributeExamples[type][key] ?? []).map((value) => ({
id: value,
name: value,
}))
- return res(ctx.json(results))
+ return [200, results]
}
export default {
@@ -344,7 +345,7 @@ export default {
get: {
'/api/environments/:team_id/logs/attributes': attributesMock,
'/api/environments/:team_id/logs/values': valuesMock,
- '/api/environments/:team_id/logs/has_logs': (_, res, ctx) => res(ctx.json({ hasLogs: true })),
+ '/api/environments/:team_id/logs/has_logs': () => [200, { hasLogs: true }],
},
post: {
'/api/environments/:team_id/logs/query': queryMock,
diff --git a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
index 915880063289..737a9461e9b9 100644
--- a/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
+++ b/products/mcp_analytics/frontend/MCPAnalyticsDashboard.stories.tsx
@@ -153,22 +153,22 @@ const meta: Meta = {
'/api/environments/:team_id/mcp_analytics/sessions/:session_id/tool_calls/': TOOL_CALL_LIST,
},
post: {
- '/api/environments/:team_id/query/:kind': (req, res, ctx) => {
- const body = req.body as Record<string, any>
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as Record<string, any>
const query: string = body?.query?.query ?? ''
if (query.includes('$mcp_client_name')) {
- return res(ctx.json({ results: HARNESS_RESULTS }))
+ return [200, { results: HARNESS_RESULTS }]
}
if (query.includes('AS session_id')) {
- return res(ctx.json({ results: SESSION_RESULTS }))
+ return [200, { results: SESSION_RESULTS }]
}
if (query.includes('p95_duration_ms')) {
- return res(ctx.json({ results: TOOL_RESULTS }))
+ return [200, { results: TOOL_RESULTS }]
}
if (query.includes('AS bucket')) {
- return res(ctx.json({ results: KPI_RESULTS }))
+ return [200, { results: KPI_RESULTS }]
}
- return res(ctx.json({ results: [] }))
+ return [200, { results: [] }]
},
},
}),
diff --git a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx
index cd0e08050c70..36176ffefd8b 100644
--- a/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx
+++ b/products/product_analytics/frontend/insights/stickiness/StickinessLineChart/StickinessLineChart.test.tsx
@@ -10,6 +10,9 @@ import { NodeKind } from '~/queries/schema/schema-general'
import { buildStickinessQuery, chart, getHogChart, personsModal, renderInsight } from '~/test/insight-testing'
configure({ asyncUtilTimeout: 5000 })
+// With asyncUtilTimeout at 5s, a single legitimate waitFor can exhaust Jest's default
+// 5s per-test budget on a contended CI shard.
+jest.setTimeout(15000)
let cleanupJsdom: () => void
let cleanupRaf: () => void
diff --git a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
index 4aad1a4879ee..754f93d750d0 100644
--- a/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
+++ b/products/product_analytics/frontend/insights/trends/TrendsLineChart/TrendsLineChart.test.tsx
@@ -22,6 +22,9 @@ import { AnnotationScope, ChartDisplayType } from '~/types'
// The full InsightViz tree is heavy to mount under jsdom; on contended CI shards
// the default 1s waitFor / findBy timeout is too tight and flakes randomly.
configure({ asyncUtilTimeout: 5000 })
+// With asyncUtilTimeout at 5s, a single legitimate waitFor can exhaust Jest's default
+// 5s per-test budget — the first test in the file (which also pays chart init) hits this.
+jest.setTimeout(15000)
let cleanupJsdom: () => void
let cleanupRaf: () => void
diff --git a/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx b/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
index 8f54c15c4aef..312acdc68192 100644
--- a/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
+++ b/products/revenue_analytics/frontend/RevenueAnalyticsScene.stories.tsx
@@ -51,8 +51,11 @@ const meta: Meta = {
},
},
post: {
- '/api/environments/:team_id/query/:kind': (req) => {
- const queryKind = getEffectiveQueryKind(req)
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as {
+ query?: { kind?: string; source?: { kind?: string } }
+ }
+ const queryKind = getEffectiveQueryKind({ body })
if (queryKind === 'DatabaseSchemaQuery') {
return [200, databaseSchemaMock]
diff --git a/products/revenue_analytics/frontend/settings/RevenueAnalyticsSettings.stories.tsx b/products/revenue_analytics/frontend/settings/RevenueAnalyticsSettings.stories.tsx
index 59707ad8d006..15a968432b7a 100644
--- a/products/revenue_analytics/frontend/settings/RevenueAnalyticsSettings.stories.tsx
+++ b/products/revenue_analytics/frontend/settings/RevenueAnalyticsSettings.stories.tsx
@@ -66,8 +66,11 @@ const meta: Meta = {
},
},
post: {
- '/api/environments/:team_id/query/:kind': (req) => {
- const queryKind = getEffectiveQueryKind(req)
+ '/api/environments/:team_id/query/:kind': async ({ request }) => {
+ const body = (await request.json()) as {
+ query?: { kind?: string; source?: { kind?: string } }
+ }
+ const queryKind = getEffectiveQueryKind({ body })
if (queryKind === 'DatabaseSchemaQuery') {
return [200, DatabaseSchemaQuery]
diff --git a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
index 57ff80e5d1e2..ffac986b40ee 100644
--- a/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
+++ b/products/workflows/frontend/Workflows/hogflows/registry/triggers/surveyTriggerLogic.test.ts
@@ -33,11 +33,11 @@ describe('surveyTriggerLogic', () => {
let loadMoreCalled = false
useMocks({
get: {
- '/api/projects/:team_id/surveys/': (req) => {
+ '/api/projects/:team_id/surveys/': ({ request }) => {
if (listError) {
return [500, { detail: 'Server error' }]
}
- const offset = Number(req.url.searchParams.get('offset') || 0)
+ const offset = Number(new URL(request.url).searchParams.get('offset') || 0)
if (offset > 0) {
if (moreListError && !loadMoreCalled) {
loadMoreCalled = true
diff --git a/services/mcp/package.json b/services/mcp/package.json
index 3407de9a8af2..63ae1b032acb 100644
--- a/services/mcp/package.json
+++ b/services/mcp/package.json
@@ -80,7 +80,7 @@
"ajv-formats": "^3.0.1",
"chokidar": "^3.6.0",
"dotenv": "^16.4.7",
- "msw": "^2.12.14",
+ "msw": "^2.14.6",
"oxfmt": "^0.33.0",
"oxlint": "^1.8.0",
"react": "^18.2.0",