// __tests__/unit/utils/recaptchaHelper.test.js const { verifyRecaptchaV2 } = require("../../../src/utils/recaptchaHelper"); // Adjust path // Mock global fetch global.fetch = jest.fn(); describe("reCAPTCHA Helper", () => { const RECAPTCHA_V2_SECRET_KEY_ORIG = process.env.RECAPTCHA_V2_SECRET_KEY; beforeEach(() => { fetch.mockClear(); // Ensure a secret key is set for these tests process.env.RECAPTCHA_V2_SECRET_KEY = "test-secret-key"; }); afterAll(() => { process.env.RECAPTCHA_V2_SECRET_KEY = RECAPTCHA_V2_SECRET_KEY_ORIG; // Restore original }); it("should return true for a successful verification", async () => { fetch.mockResolvedValueOnce({ json: async () => ({ success: true }), }); const result = await verifyRecaptchaV2("valid-token", "127.0.0.1"); expect(result).toBe(true); expect(fetch).toHaveBeenCalledTimes(1); expect(fetch).toHaveBeenCalledWith( expect.stringContaining("response=valid-token"), { method: "POST" } ); }); it("should return false for a failed verification", async () => { fetch.mockResolvedValueOnce({ json: async () => ({ success: false, "error-codes": ["invalid-input-response"], }), }); const result = await verifyRecaptchaV2("invalid-token"); expect(result).toBe(false); }); it("should return false if reCAPTCHA secret key is not set", async () => { delete process.env.RECAPTCHA_V2_SECRET_KEY; // Temporarily remove for this test const consoleWarnSpy = jest .spyOn(console, "warn") .mockImplementation(() => {}); const result = await verifyRecaptchaV2("any-token"); expect(result).toBe(false); expect(consoleWarnSpy).toHaveBeenCalledWith( expect.stringContaining("RECAPTCHA_V2_SECRET_KEY is not set") ); process.env.RECAPTCHA_V2_SECRET_KEY = "test-secret-key"; // Restore for other tests consoleWarnSpy.mockRestore(); }); it("should return false if no token is provided", async () => { const consoleWarnSpy = jest .spyOn(console, "warn") .mockImplementation(() => {}); const result = await verifyRecaptchaV2(""); expect(result).toBe(false); expect(consoleWarnSpy).toHaveBeenCalledWith( "No reCAPTCHA token provided by client." ); consoleWarnSpy.mockRestore(); }); it("should return false if fetch throws an error", async () => { fetch.mockRejectedValueOnce(new Error("Network error")); const consoleErrorSpy = jest .spyOn(console, "error") .mockImplementation(() => {}); const result = await verifyRecaptchaV2("any-token"); expect(result).toBe(false); expect(consoleErrorSpy).toHaveBeenCalledWith( "Error during reCAPTCHA verification request:", expect.any(Error) ); consoleErrorSpy.mockRestore(); }); });