Skip to content

Commit 8fa0a5c

Browse files
committed
test: added tests for checking correct error codes are thrown on request timeout and connection closed scenarios
1 parent d77cd0d commit 8fa0a5c

File tree

1 file changed

+63
-0
lines changed

1 file changed

+63
-0
lines changed

src/shared/protocol.test.ts

Lines changed: 63 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,63 @@
1+
import { Protocol } from "./protocol.js";
2+
import { Transport } from "./transport.js";
3+
import {
4+
McpError,
5+
ErrorCode,
6+
Request,
7+
Result,
8+
Notification,
9+
} from "../types.js";
10+
import { ZodType, z } from "zod";
11+
12+
// Mock Transport class
13+
class MockTransport implements Transport {
14+
onclose?: () => void;
15+
onerror?: (error: Error) => void;
16+
onmessage?: (message: unknown) => void;
17+
18+
async start(): Promise<void> {}
19+
async close(): Promise<void> {
20+
this.onclose?.();
21+
}
22+
async send(_message: unknown): Promise<void> {}
23+
}
24+
25+
describe("protocol tests", () => {
26+
let protocol: Protocol<Request, Notification, Result>;
27+
let transport: MockTransport;
28+
29+
beforeEach(() => {
30+
transport = new MockTransport();
31+
protocol = new (class extends Protocol<Request, Notification, Result> {
32+
protected assertCapabilityForMethod(): void {}
33+
protected assertNotificationCapability(): void {}
34+
protected assertRequestHandlerCapability(): void {}
35+
})();
36+
});
37+
38+
test("should throw a timeout error if the request exceeds the timeout", async () => {
39+
await protocol.connect(transport);
40+
const request = { method: "example", params: {} };
41+
try {
42+
const mockSchema: ZodType<{ result: string }> = z.object({
43+
result: z.string(),
44+
});
45+
await protocol.request(request, mockSchema, {
46+
timeout: 100,
47+
}); // Short timeout for test
48+
} catch (error) {
49+
expect(error).toBeInstanceOf(McpError);
50+
if (error instanceof McpError) {
51+
expect(error.code).toBe(ErrorCode.RequestTimeout);
52+
}
53+
}
54+
});
55+
56+
test("should invoke onclose when the connection is closed", async () => {
57+
const oncloseMock = jest.fn();
58+
protocol.onclose = oncloseMock;
59+
await protocol.connect(transport);
60+
await transport.close();
61+
expect(oncloseMock).toHaveBeenCalled();
62+
});
63+
});

0 commit comments

Comments
 (0)