getBlockNumber.test.ts•3.25 kB
import { getBlockNumber } from "../../../tools/ethereum/getBlockNumber";
import { INFURA_CHAIN_URLS } from "../../../config/chains";
global.fetch = jest.fn();
describe("getBlockNumber", () => {
afterEach(() => {
jest.clearAllMocks();
});
it("fetches block number successfully", async () => {
const mockResponse = {
json: async () => ({ result: "0x65a8db" }), // hex block number
} as Response;
(fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(
mockResponse
);
const result = await getBlockNumber.handler({ chainid: 1 });
expect(result.content?.[0]?.text).toContain("Latest block number");
expect(result.content?.[0]?.text).toContain("hex: 0x65a8db");
expect(result.content?.[0]?.text).toContain(
String(parseInt("0x65a8db", 16))
);
expect(fetch).toHaveBeenCalledWith(
INFURA_CHAIN_URLS[1],
expect.any(Object)
);
});
it("handles unsupported chain ID", async () => {
const result = await getBlockNumber.handler({ chainid: 9999 });
expect(result.content?.[0]?.text).toContain(
"Unsupported or missing URL for chain ID 9999"
);
});
it("handles RPC error response", async () => {
const mockResponse = {
json: async () => ({ error: { message: "Some RPC error" } }),
} as Response;
(fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(
mockResponse
);
const result = await getBlockNumber.handler({ chainid: 1 });
expect(result.content?.[0]?.text).toContain(
"Error fetching block number: Some RPC error"
);
});
it("handles unknown RPC error when result is missing", async () => {
const mockResponse = {
json: async () => ({}), // No result, no error
} as Response;
(fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(
mockResponse
);
const result = await getBlockNumber.handler({ chainid: 1 });
expect(result.content?.[0]?.text).toContain(
"Error fetching block number: Unknown error"
);
});
it("handles network errors", async () => {
(fetch as jest.MockedFunction<typeof fetch>).mockRejectedValueOnce(
new Error("Network failure")
);
const result = await getBlockNumber.handler({ chainid: 1 });
expect(result.content?.[0]?.text).toContain("Error fetching block number");
expect(result.content?.[0]?.text).toContain("Network failure");
});
it("handles non-Error exceptions gracefully", async () => {
// Force a non-Error rejection
(fetch as jest.MockedFunction<typeof fetch>).mockRejectedValueOnce(
"strange failure"
);
const result = await getBlockNumber.handler({ chainid: 1 });
expect(result.content?.[0]?.text).toContain(
"Error fetching block number: strange failure"
);
});
it("defaults to chain ID 1 when none is provided", async () => {
const mockResponse = {
json: async () => ({ result: "0x10" }),
} as Response;
(fetch as jest.MockedFunction<typeof fetch>).mockResolvedValueOnce(
mockResponse
);
await getBlockNumber.handler({}); // no chainid provided
expect(fetch).toHaveBeenCalledWith(
INFURA_CHAIN_URLS[1],
expect.any(Object)
);
});
});