Skip to content

test(e2e): Add tsx + express e2e test app #16578

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

Open
wants to merge 2 commits into
base: develop
Choose a base branch
from
Open
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
2 changes: 2 additions & 0 deletions dev-packages/e2e-tests/test-applications/tsx-express/.npmrc
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,13 @@
import * as Sentry from '@sentry/node';

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,
_experiments: {
enableLogs: true,
},
});
35 changes: 35 additions & 0 deletions dev-packages/e2e-tests/test-applications/tsx-express/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,35 @@
{
"name": "tsx-express-app",
"version": "1.0.0",
"private": true,
"scripts": {
"start": "tsx --import ./instrument.mjs ./src/app.ts",
"test": "playwright test",
"clean": "npx rimraf node_modules pnpm-lock.yaml",
"test:build": "pnpm install",
"test:assert": "pnpm test"
},
"dependencies": {
"@modelcontextprotocol/sdk": "^1.10.2",
"@sentry/core": "latest || *",
"@sentry/node": "latest || *",
"@trpc/server": "10.45.2",
"@trpc/client": "10.45.2",
"@types/express": "^4.17.21",
"@types/node": "^18.19.1",
"express": "^4.21.2",
"typescript": "~5.0.0",
"zod": "~3.24.3"
},
"devDependencies": {
"@playwright/test": "~1.50.0",
"@sentry-internal/test-utils": "link:../../../test-utils",
"tsx": "^4.20.3"
},
"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;
138 changes: 138 additions & 0 deletions dev-packages/e2e-tests/test-applications/tsx-express/src/app.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,138 @@
import * as Sentry from '@sentry/node';

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

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('/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.withActiveSpan(null, async () => {
Sentry.startSpan({ name: 'test-transaction', op: 'e2e-test' }, () => {
Sentry.startSpan({ name: 'test-span' }, () => undefined);
});

await Sentry.flush();

res.send({
transactionIds: global.transactionIds || [],
});
});
});

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');
}),
unauthorized: procedure.mutation(() => {
throw new TRPCError({ code: 'UNAUTHORIZED', cause: new Error('Unauthorized') });
}),
});

export type AppRouter = typeof appRouter;

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

app.use(
'/trpc',
trpcExpress.createExpressMiddleware({
router: appRouter,
createContext,
}),
);
64 changes: 64 additions & 0 deletions dev-packages/e2e-tests/test-applications/tsx-express/src/mcp.ts
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/core';

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: 'tsx-express',
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import { expect, test } from '@playwright/test';
import { waitForError } from '@sentry-internal/test-utils';

test('Sends correct error event', async ({ baseURL }) => {
const errorEventPromise = waitForError('tsx-express', 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('tsx-express', 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();
});
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 { SerializedLog, SerializedLogContainer } from '@sentry/core';

test('should send logs', async ({ baseURL }) => {
const logEnvelopePromise = waitForEnvelopeItem('tsx-express', 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