UNPKG

precious-metal-mcp

Version:

An MCP tool to get precious metal prices.

65 lines (64 loc) 2.92 kB
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); const vitest_1 = require("vitest"); const index_js_1 = require("./index.js"); // Set a dummy API key for tests to avoid the check in main code index_js_1.finnhubClient.defaults.params = { token: "test_key" }; (0, vitest_1.describe)("getPreciousMetalPriceLogic", () => { let getSpy; (0, vitest_1.beforeEach)(() => { // Spy on the 'get' method of the real finnhubClient getSpy = vitest_1.vi.spyOn(index_js_1.finnhubClient, "get"); }); (0, vitest_1.afterEach)(() => { // Restore the spy after each test getSpy.mockRestore(); }); (0, vitest_1.it)("should calculate the price for gold in New York correctly", async () => { // Arrange: Set up the mock responses from the API getSpy.mockImplementation((endpoint, { params }) => { if (params.symbol === "OANDA:XAU_USD") { return Promise.resolve({ data: { c: 2000 } }); // Gold price: $2000/oz } if (params.symbol === "OANDA:USD_CNY") { return Promise.resolve({ data: { c: 7.2 } }); // Exchange rate: 7.2 CNY/USD } return Promise.reject(new Error("Unexpected API call")); }); const args = { market: "new_york", metal: "gold", type: "spot", }; // Act: Call the function const result = await (0, index_js_1.getPreciousMetalPriceLogic)(args); // Assert: Check if the result is correct const expectedPrice = (2000 * 7.2) / index_js_1.TROY_OUNCE_TO_GRAMS; (0, vitest_1.expect)(result.converted_price.value).toBeCloseTo(expectedPrice, 2); (0, vitest_1.expect)(result.original_price.value).toBe(2000); (0, vitest_1.expect)(result.exchange_rate.rate).toBe(7.2); (0, vitest_1.expect)(result.converted_price.unit).toBe("CNY/gram"); }); (0, vitest_1.it)("should handle API failure gracefully", async () => { // Arrange: Mock a failed API call getSpy.mockRejectedValue(new Error("API is down")); const args = { market: "london", metal: "silver", type: "spot", }; // Act & Assert: Expect the function to throw an error await (0, vitest_1.expect)((0, index_js_1.getPreciousMetalPriceLogic)(args)).rejects.toThrow("API is down"); }); (0, vitest_1.it)("should handle invalid price from API", async () => { // Arrange: Mock a response with a zero price getSpy.mockResolvedValue({ data: { c: 0 } }); const args = { market: "new_york", metal: "gold", type: "spot", }; // Act & Assert await (0, vitest_1.expect)((0, index_js_1.getPreciousMetalPriceLogic)(args)).rejects.toThrow("Could not fetch a valid price for symbol OANDA:XAU_USD"); }); });