test: consolidate MCP client/fetch-stub setup into useTestClient helper (#333)

This commit is contained in:
Sampson authored and GitHub committed 2026-08-11 15:13:10 -05:00
1 parent ad288a4ef9
commit 937e85a61f
9 files changed
+211 -351

No files matched your search

+24
View File
@@ -1,5 +1,6 @@
import { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { Client } from '@modelcontextprotocol/sdk/client/index.js';
import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js'; import { InMemoryTransport } from '@modelcontextprotocol/sdk/inMemory.js';
import { after, before } from 'node:test';
import createMcpServer from '../server.js'; import createMcpServer from '../server.js';
/** /**
@@ -45,3 +46,26 @@ export function stubFetch(handler: (url: URL) => unknown): () => void {
globalThis.fetch = originalFetch; globalThis.fetch = originalFetch;
}; };
} }
/**
* Registers before/after hooks on the enclosing `describe` block that stub
* the Brave API via `responder` and connect a fresh test client, tearing
* both down afterward. Returns a getter for the connected client.
*/
export function useTestClient(responder: (url: URL) => unknown): () => Client {
let client: Client;
let close: () => Promise<void>;
let restoreFetch: () => void;
before(async () => {
restoreFetch = stubFetch(responder);
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
});
return () => client;
}
+36 -63
View File
@@ -1,49 +1,35 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/images/search') {
let restoreFetch: () => void; return {
type: 'images',
before(async () => { query: { original: 'brave browser' },
restoreFetch = stubFetch((url) => { results: [
if (url.pathname === '/res/v1/images/search') { {
return { type: 'image_result',
type: 'images', title: 'Brave Browser Logo',
query: { original: 'brave browser' }, url: 'https://example.com/logo.png',
results: [ page_fetched: '2024-01-01T00:00:00Z',
{ confidence: 'high',
type: 'image_result', properties: {
title: 'Brave Browser Logo', url: 'https://example.com/logo-full.png',
url: 'https://example.com/logo.png', width: 512,
page_fetched: '2024-01-01T00:00:00Z', height: 512,
confidence: 'high',
properties: {
url: 'https://example.com/logo-full.png',
width: 512,
height: 512,
},
}, },
], },
extra: { might_be_offensive: false }, ],
}; extra: { might_be_offensive: false },
} };
}); }
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns image results for a simple query', async () => { it('returns image results for a simple query', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.deepEqual(result.structuredContent, { assert.deepEqual(result.structuredContent, {
@@ -68,34 +54,21 @@ describe(name, () => {
}); });
describe(`${name} (malformed upstream response)`, () => { describe(`${name} (malformed upstream response)`, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/images/search') {
let restoreFetch: () => void; return {
type: 'images',
before(async () => { query: { original: 'brave browser' },
restoreFetch = stubFetch((url) => { results: [],
if (url.pathname === '/res/v1/images/search') { // `might_be_offensive` is required by the output schema; omitting it
return { // simulates an upstream response that fails validation.
type: 'images', extra: {},
query: { original: 'brave browser' }, };
results: [], }
// `might_be_offensive` is required by the output schema; omitting it
// simulates an upstream response that fails validation.
extra: {},
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('surfaces the validation failure as an error result', async () => { it('surfaces the validation failure as an error result', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError, true); assert.equal(result.isError, true);
assert.ok( assert.ok(
+30 -57
View File
@@ -1,45 +1,31 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/llm/context') {
let restoreFetch: () => void; return {
grounding: {
before(async () => { generic: [
restoreFetch = stubFetch((url) => { {
if (url.pathname === '/res/v1/llm/context') { url: 'https://search.brave.com/',
return { title: 'Brave Search',
grounding: { snippets: ['Brave is a privacy-focused browser and search engine.'],
generic: [ },
{ ],
url: 'https://search.brave.com/', map: [],
title: 'Brave Search', },
snippets: ['Brave is a privacy-focused browser and search engine.'], sources: {
}, 'https://search.brave.com/': { title: 'Brave Search' },
], },
map: [], };
}, }
sources: {
'https://search.brave.com/': { title: 'Brave Search' },
},
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns grounding content for a simple query', async () => { it('returns grounding content for a simple query', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.deepEqual(result.structuredContent, { assert.deepEqual(result.structuredContent, {
@@ -61,31 +47,18 @@ describe(name, () => {
}); });
describe(`${name} (malformed upstream response)`, () => { describe(`${name} (malformed upstream response)`, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/llm/context') {
let restoreFetch: () => void; // `sources` is required by the output schema; omitting it simulates
// an upstream response that fails validation.
before(async () => { return {
restoreFetch = stubFetch((url) => { grounding: { generic: [], map: [] },
if (url.pathname === '/res/v1/llm/context') { };
// `sources` is required by the output schema; omitting it simulates }
// an upstream response that fails validation.
return {
grounding: { generic: [], map: [] },
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('surfaces the validation failure as an error result', async () => { it('surfaces the validation failure as an error result', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError, true); assert.equal(result.isError, true);
assert.ok(JSON.stringify(result.content).includes('sources'), JSON.stringify(result.content)); assert.ok(JSON.stringify(result.content).includes('sources'), JSON.stringify(result.content));
+40 -80
View File
@@ -1,43 +1,29 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/web/search') {
let restoreFetch: () => void; return {
type: 'search',
locations: {
results: [{ id: 'poi-1', title: 'Brave Coffee Shop' }],
},
};
}
before(async () => { if (url.pathname === '/res/v1/local/descriptions') {
restoreFetch = stubFetch((url) => { return {
if (url.pathname === '/res/v1/web/search') { type: 'local_descriptions',
return { results: [{ type: 'local_description', id: 'poi-1', description: 'A cozy coffee shop.' }],
type: 'search', };
locations: { }
results: [{ id: 'poi-1', title: 'Brave Coffee Shop' }],
},
};
}
if (url.pathname === '/res/v1/local/descriptions') {
return {
type: 'local_descriptions',
results: [{ type: 'local_description', id: 'poi-1', description: 'A cozy coffee shop.' }],
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns enriched location results for a simple query', async () => { it('returns enriched location results for a simple query', async () => {
const result = await client.callTool({ const result = await getClient().callTool({
name, name,
arguments: { query: 'coffee shops in san francisco' }, arguments: { query: 'coffee shops in san francisco' },
}); });
@@ -48,39 +34,26 @@ describe(name, () => {
}); });
describe(`${name} (no locations, web fallback available)`, () => { describe(`${name} (no locations, web fallback available)`, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/web/search') {
let restoreFetch: () => void; return {
type: 'search',
before(async () => { web: {
restoreFetch = stubFetch((url) => { results: [
if (url.pathname === '/res/v1/web/search') { {
return { url: 'https://example.com/cafe',
type: 'search', title: 'Local Cafe',
web: { description: 'A nice cafe.',
results: [ extra_snippets: [],
{ },
url: 'https://example.com/cafe', ],
title: 'Local Cafe', },
description: 'A nice cafe.', };
extra_snippets: [], }
},
],
},
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('falls back to formatted web results', async () => { it('falls back to formatted web results', async () => {
const result = await client.callTool({ const result = await getClient().callTool({
name, name,
arguments: { query: 'coffee shops in san francisco' }, arguments: { query: 'coffee shops in san francisco' },
}); });
@@ -95,27 +68,14 @@ describe(`${name} (no locations, web fallback available)`, () => {
}); });
describe(`${name} (no locations, no web results)`, () => { describe(`${name} (no locations, no web results)`, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/web/search') {
let restoreFetch: () => void; return { type: 'search' };
}
before(async () => {
restoreFetch = stubFetch((url) => {
if (url.pathname === '/res/v1/web/search') {
return { type: 'search' };
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('reports that no location data was found', async () => { it('reports that no location data was found', async () => {
const result = await client.callTool({ const result = await getClient().callTool({
name, name,
arguments: { query: 'coffee shops in san francisco' }, arguments: { query: 'coffee shops in san francisco' },
}); });
+21 -35
View File
@@ -1,45 +1,31 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/news/search') {
let restoreFetch: () => void; return {
results: [
before(async () => { {
restoreFetch = stubFetch((url) => { url: 'https://example.com/news',
if (url.pathname === '/res/v1/news/search') { title: 'Brave ships a new release',
return { description: 'News about Brave.',
results: [ age: '1 hour ago',
{ page_age: '2024-01-01T00:00:00Z',
url: 'https://example.com/news', breaking: false,
title: 'Brave ships a new release', is_live: false,
description: 'News about Brave.', extra_snippets: [],
age: '1 hour ago', thumbnail: { src: 'https://example.com/news-thumb.jpg' },
page_age: '2024-01-01T00:00:00Z', },
breaking: false, ],
is_live: false, };
extra_snippets: [], }
thumbnail: { src: 'https://example.com/news-thumb.jpg' },
},
],
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns news results for a simple query', async () => { it('returns news results for a simple query', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.ok(Array.isArray(result.content) && result.content.length > 0); assert.ok(Array.isArray(result.content) && result.content.length > 0);
+7 -21
View File
@@ -1,31 +1,17 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/local/place_search') {
let restoreFetch: () => void; return { type: 'locations' };
}
before(async () => {
restoreFetch = stubFetch((url) => {
if (url.pathname === '/res/v1/local/place_search') {
return { type: 'locations' };
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns a locations response for a simple location query', async () => { it('returns a locations response for a simple location query', async () => {
const result = await client.callTool({ const result = await getClient().callTool({
name, name,
arguments: { location: 'san francisco ca united states' }, arguments: { location: 'san francisco ca united states' },
}); });
+11 -25
View File
@@ -1,35 +1,21 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/summarizer/search') {
let restoreFetch: () => void; return {
type: 'summarizer',
before(async () => { status: 'complete',
restoreFetch = stubFetch((url) => { summary: [{ type: 'token', data: 'Brave is a privacy-focused browser.' }],
if (url.pathname === '/res/v1/summarizer/search') { };
return { }
type: 'summarizer',
status: 'complete',
summary: [{ type: 'token', data: 'Brave is a privacy-focused browser.' }],
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns a summary for a completed key', async () => { it('returns a summary for a completed key', async () => {
const result = await client.callTool({ name, arguments: { key: 'test-key' } }); const result = await getClient().callTool({ name, arguments: { key: 'test-key' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.ok(Array.isArray(result.content) && result.content.length > 0); assert.ok(Array.isArray(result.content) && result.content.length > 0);
+23 -37
View File
@@ -1,48 +1,34 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/videos/search') {
let restoreFetch: () => void; return {
results: [
before(async () => { {
restoreFetch = stubFetch((url) => { url: 'https://example.com/video',
if (url.pathname === '/res/v1/videos/search') { title: 'Introducing Brave',
return { description: 'A video about the Brave browser.',
results: [ age: '1 day ago',
{ video: {
url: 'https://example.com/video', duration: '5:00',
title: 'Introducing Brave', views: '1000',
description: 'A video about the Brave browser.', creator: 'Brave Software',
age: '1 day ago', publisher: 'Brave Software',
video: { tags: ['browser'],
duration: '5:00',
views: '1000',
creator: 'Brave Software',
publisher: 'Brave Software',
tags: ['browser'],
},
thumbnail: { src: 'https://example.com/thumb.jpg' },
}, },
], thumbnail: { src: 'https://example.com/thumb.jpg' },
}; },
} ],
}); };
}
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns video results for a simple query', async () => { it('returns video results for a simple query', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.ok(Array.isArray(result.content) && result.content.length > 0); assert.ok(Array.isArray(result.content) && result.content.length > 0);
+19 -33
View File
@@ -1,43 +1,29 @@
import assert from 'node:assert/strict'; import assert from 'node:assert/strict';
import { after, before, describe, it } from 'node:test'; import { describe, it } from 'node:test';
import type { Client } from '@modelcontextprotocol/sdk/client/index.js'; import { useTestClient } from '../../testUtils/mcpTestHarness.js';
import { connectTestClient, stubFetch } from '../../testUtils/mcpTestHarness.js';
import { name } from './index.js'; import { name } from './index.js';
describe(name, () => { describe(name, () => {
let client: Client; const getClient = useTestClient((url) => {
let close: () => Promise<void>; if (url.pathname === '/res/v1/web/search') {
let restoreFetch: () => void; return {
type: 'search',
before(async () => { web: {
restoreFetch = stubFetch((url) => { results: [
if (url.pathname === '/res/v1/web/search') { {
return { url: 'https://search.brave.com/',
type: 'search', title: 'Brave Search',
web: { description: 'A privacy-focused search engine.',
results: [ extra_snippets: [],
{ },
url: 'https://search.brave.com/', ],
title: 'Brave Search', },
description: 'A privacy-focused search engine.', };
extra_snippets: [], }
},
],
},
};
}
});
({ client, close } = await connectTestClient());
});
after(async () => {
restoreFetch();
await close();
}); });
it('returns web results for a simple query', async () => { it('returns web results for a simple query', async () => {
const result = await client.callTool({ name, arguments: { query: 'brave browser' } }); const result = await getClient().callTool({ name, arguments: { query: 'brave browser' } });
assert.equal(result.isError ?? false, false, JSON.stringify(result.content)); assert.equal(result.isError ?? false, false, JSON.stringify(result.content));
assert.ok(Array.isArray(result.content) && result.content.length > 0); assert.ok(Array.isArray(result.content) && result.content.length > 0);