Skip to content

test(node): Replace express v5 integration tests with E2E test #17147

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 3 commits into from
Jul 24, 2025
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
dist
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
@sentry:registry=http://127.0.0.1:4873
@sentry-internal:registry=http://127.0.0.1:4873
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "node-express-v5-app",
"version": "1.0.0",
"private": true,
"scripts": {
"build": "tsc",
"start": "node dist/app.js",
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install && pnpm build",
"test:assert": "pnpm test"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.10.2",
"@sentry/node": "latest || *",
"@trpc/server": "10.45.2",
"@trpc/client": "10.45.2",
"@types/express": "^4.17.21",
"@types/node": "^18.19.1",
"express": "^5.1.0",
"typescript": "~5.0.0",
"zod": "~3.24.3"
},
"devDependencies": {
"@playwright/test": "~1.53.2",
"@sentry-internal/test-utils": "link:../../../test-utils",
"@sentry/core": "latest || *"
},
"resolutions": {
"@types/qs": "6.9.17"
},
"volta": {
"extends": "../../package.json"
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
import { getPlaywrightConfig } from '@sentry-internal/test-utils';

const config = getPlaywrightConfig({
startCommand: `pnpm start`,
});

export default config;
152 changes: 152 additions & 0 deletions dev-packages/e2e-tests/test-applications/node-express-v5/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,152 @@
import * as Sentry from '@sentry/node';

declare global {
namespace globalThis {
var transactionIds: string[];
}
}

Sentry.init({
environment: 'qa', // dynamic sampling bias to keep transactions
dsn: process.env.E2E_TEST_DSN,
includeLocalVariables: true,
debug: !!process.env.DEBUG,
tunnel: `http://localhost:3031/`, // proxy server
tracesSampleRate: 1,
enableLogs: true,
});

import { TRPCError, initTRPC } from '@trpc/server';
import * as trpcExpress from '@trpc/server/adapters/express';
import express from 'express';
import { z } from 'zod';
import { mcpRouter } from './mcp';

const app = express();
const port = 3030;

app.use(mcpRouter);

app.get('/crash-in-with-monitor/:id', async (req, res) => {
try {
await Sentry.withMonitor('express-crash', async () => {
throw new Error(`This is an exception withMonitor: ${req.params.id}`);
});
res.sendStatus(200);
} catch (error: any) {
res.status(500);
res.send({ message: error.message, pid: process.pid });
}
});

app.get('/test-success', function (req, res) {
res.send({ version: 'v1' });
});

app.get('/test-log', function (req, res) {
Sentry.logger.debug('Accessed /test-log route');
res.send({ message: 'Log sent' });
});

app.get('/test-param/:param', function (req, res) {
res.send({ paramWas: req.params.param });
});

app.get('/test-transaction', function (_req, res) {
Sentry.startSpan({ name: 'test-span' }, () => undefined);

res.send({ status: 'ok' });
});

app.get('/test-error', async function (req, res) {
const exceptionId = Sentry.captureException(new Error('This is an error'));

await Sentry.flush(2000);

res.send({ exceptionId });
});

app.get('/test-exception/:id', function (req, _res) {
throw new Error(`This is an exception with id ${req.params.id}`);
});

app.get('/test-local-variables-uncaught', function (req, res) {
const randomVariableToRecord = Math.random();
throw new Error(`Uncaught Local Variable Error - ${JSON.stringify({ randomVariableToRecord })}`);
});

app.get('/test-local-variables-caught', function (req, res) {
const randomVariableToRecord = Math.random();

let exceptionId: string;
try {
throw new Error('Local Variable Error');
} catch (e) {
exceptionId = Sentry.captureException(e);
}

res.send({ exceptionId, randomVariableToRecord });
});

Sentry.setupExpressErrorHandler(app);

// @ts-ignore
app.use(function onError(err, req, res, next) {
// The error id is attached to `res.sentry` to be returned
// and optionally displayed to the user for support.
res.statusCode = 500;
res.end(res.sentry + '\n');
});

app.listen(port, () => {
console.log(`Example app listening on port ${port}`);
});

Sentry.addEventProcessor(event => {
global.transactionIds = global.transactionIds || [];

if (event.type === 'transaction') {
const eventId = event.event_id;

if (eventId) {
global.transactionIds.push(eventId);
}
}

return event;
});

export const t = initTRPC.context<Context>().create();

const procedure = t.procedure.use(Sentry.trpcMiddleware({ attachRpcInput: true }));

export const appRouter = t.router({
getSomething: procedure.input(z.string()).query(opts => {
return { id: opts.input, name: 'Bilbo' };
}),
createSomething: procedure.mutation(async () => {
await new Promise(resolve => setTimeout(resolve, 400));
return { success: true };
}),
crashSomething: procedure
.input(z.object({ nested: z.object({ nested: z.object({ nested: z.string() }) }) }))
.mutation(() => {
throw new Error('I crashed in a trpc handler');
}),
badRequest: procedure.mutation(() => {
throw new TRPCError({ code: 'BAD_REQUEST', cause: new Error('Bad Request') });
}),
});

export type AppRouter = typeof appRouter;

const createContext = () => ({ someStaticValue: 'asdf' });
type Context = Awaited<ReturnType<typeof createContext>>;

app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
}),
);
Original file line number Diff line number Diff line change
@@ -0,0 +1,64 @@
import express from 'express';
import { McpServer, ResourceTemplate } from '@modelcontextprotocol/sdk/server/mcp.js';
import { SSEServerTransport } from '@modelcontextprotocol/sdk/server/sse.js';
import { z } from 'zod';
import { wrapMcpServerWithSentry } from '@sentry/node';

const mcpRouter = express.Router();

const server = wrapMcpServerWithSentry(
new McpServer({
name: 'Echo',
version: '1.0.0',
}),
);

server.resource('echo', new ResourceTemplate('echo://{message}', { list: undefined }), async (uri, { message }) => ({
contents: [
{
uri: uri.href,
text: `Resource echo: ${message}`,
},
],
}));

server.tool('echo', { message: z.string() }, async ({ message }, rest) => {
return {
content: [{ type: 'text', text: `Tool echo: ${message}` }],
};
});

server.prompt('echo', { message: z.string() }, ({ message }, extra) => ({
messages: [
{
role: 'user',
content: {
type: 'text',
text: `Please process this message: ${message}`,
},
},
],
}));

const transports: Record<string, SSEServerTransport> = {};

mcpRouter.get('/sse', async (_, res) => {
const transport = new SSEServerTransport('/messages', res);
transports[transport.sessionId] = transport;
res.on('close', () => {
delete transports[transport.sessionId];
});
await server.connect(transport);
});

mcpRouter.post('/messages', async (req, res) => {
const sessionId = req.query.sessionId;
const transport = transports[sessionId as string];
if (transport) {
await transport.handlePostMessage(req, res);
} else {
res.status(400).send('No transport found for sessionId');
}
});

export { mcpRouter };
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { startEventProxyServer } from '@sentry-internal/test-utils';

startEventProxyServer({
port: 3031,
proxyServerName: 'node-express-v5',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,53 @@
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/test-utils';

test('Sends correct error event', async ({ baseURL }) => {
const errorEventPromise = waitForError('node-express-v5', event => {
return !event.type && event.exception?.values?.[0]?.value === 'This is an exception with id 123';
});

await fetch(`${baseURL}/test-exception/123`);

const errorEvent = await errorEventPromise;

expect(errorEvent.exception?.values).toHaveLength(1);
expect(errorEvent.exception?.values?.[0]?.value).toBe('This is an exception with id 123');

expect(errorEvent.request).toEqual({
method: 'GET',
cookies: {},
headers: expect.any(Object),
url: 'http://localhost:3030/test-exception/123',
});

expect(errorEvent.transaction).toEqual('GET /test-exception/:id');

expect(errorEvent.contexts?.trace).toEqual({
trace_id: expect.stringMatching(/[a-f0-9]{32}/),
span_id: expect.stringMatching(/[a-f0-9]{16}/),
});
});

test('Should record caught exceptions with local variable', async ({ baseURL }) => {
const errorEventPromise = waitForError('node-express-v5', event => {
return event.transaction === 'GET /test-local-variables-caught';
});

await fetch(`${baseURL}/test-local-variables-caught`);

const errorEvent = await errorEventPromise;

const frames = errorEvent.exception?.values?.[0]?.stacktrace?.frames;
expect(frames?.[frames.length - 1]?.vars?.randomVariableToRecord).toBeDefined();
});

test('To not crash app from withMonitor', async ({ baseURL }) => {
const doRequest = async (id: number) => {
const response = await fetch(`${baseURL}/crash-in-with-monitor/${id}`)
return response.json();
}
const [response1, response2] = await Promise.all([doRequest(1), doRequest(2)])
expect(response1.message).toBe('This is an exception withMonitor: 1')
expect(response2.message).toBe('This is an exception withMonitor: 2')
expect(response1.pid).toBe(response2.pid) //Just to double-check, TBS
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { expect, test } from '@playwright/test';
import { waitForEnvelopeItem } from '@sentry-internal/test-utils';
import type { SerializedLogContainer } from '@sentry/core';

test('should send logs', async ({ baseURL }) => {
const logEnvelopePromise = waitForEnvelopeItem('node-express-v5', envelope => {
return envelope[0].type === 'log' && (envelope[1] as SerializedLogContainer).items[0]?.level === 'debug';
});

await fetch(`${baseURL}/test-log`);

const logEnvelope = await logEnvelopePromise;
const log = (logEnvelope[1] as SerializedLogContainer).items[0];
expect(log?.level).toBe('debug');
expect(log?.body).toBe('Accessed /test-log route');
});
Loading
Loading