diff --git a/dev-packages/node-integration-tests/suites/tracing/mongodb/test.ts b/dev-packages/node-integration-tests/suites/tracing/mongodb/test.ts index f3c82988b679..bbd38e4aed28 100644 --- a/dev-packages/node-integration-tests/suites/tracing/mongodb/test.ts +++ b/dev-packages/node-integration-tests/suites/tracing/mongodb/test.ts @@ -4,7 +4,7 @@ import { afterAll, beforeAll, describe, expect } from 'vitest'; import { assertSentryTransaction } from '../../../utils/assertions'; import { cleanupChildProcesses, createEsmAndCjsTests } from '../../../utils/runner'; -describe('MongoDB experimental Test', () => { +describe('MongoDB auto-instrumentation', () => { let mongoServer: MongoMemoryServer; beforeAll(async () => { @@ -122,20 +122,43 @@ describe('MongoDB experimental Test', () => { transaction: (txn: TransactionEvent) => { assertSentryTransaction(txn, { transaction: 'Test Transaction' }); const spans = txn.spans || []; - expect(spans).toHaveLength(8); + + // Assert the per-operation breakdown rather than just a total span + // count. When the driver occasionally emits an extra command + // (e.g. a stray `isMaster` from a reconnect, a `ping`, or a + // heartbeat), `toEqual` shows a clear per-operation diff like + // "isMaster: 2 → 3" instead of an opaque "8 vs 9" length + // mismatch — making future flakes self-diagnosing. + // + // `db.operation` isn't set on every span — the `endSessions` + // command exposes its name only via `db.statement` — so derive + // the operation by parsing the leading command name out of + // `db.statement` as a fallback. + const operationCounts = spans.reduce>((acc, span) => { + const data = (span.data ?? {}) as Record; + let op = typeof data['db.operation'] === 'string' ? (data['db.operation'] as string) : undefined; + if (!op) { + const stmt = data['db.statement']; + const match = typeof stmt === 'string' ? stmt.match(/^\{"(\w+)"/) : null; + op = match ? match[1] : 'unknown'; + } + acc[op] = (acc[op] || 0) + 1; + return acc; + }, {}); + + expect(operationCounts).toEqual({ + find: 3, + isMaster: 2, + insert: 1, + update: 1, + endSessions: 1, + }); expect(spans).toContainEqual(SPAN_FIND_MATCHER); expect(spans).toContainEqual(SPAN_INSERT_MATCHER); expect(spans).toContainEqual(SPAN_ISMASTER_MATCHER); expect(spans).toContainEqual(SPAN_UPDATE_MATCHER); expect(spans).toContainEqual(SPAN_ENDSESSIONS_MATCHER); - - // Ensure duplicate spans are correctly there - const findSpans = spans.filter(span => span.data['db.operation'] === 'find'); - expect(findSpans).toHaveLength(3); - - const isMasterSpans = spans.filter(span => span.data['db.operation'] === 'isMaster'); - expect(isMasterSpans).toHaveLength(2); }, }) .start()