From 7db6de5bb6e8c48c512b27a4df3e78f3c23e9841 Mon Sep 17 00:00:00 2001 From: Louis Grasset Date: Wed, 22 Nov 2023 23:52:19 +0100 Subject: [PATCH] test(cache): cover restorePreviousSession --- .../restore-previous-session.spec.ts | 69 +++++++++++++++++++ 1 file changed, 69 insertions(+) create mode 100644 src/helpers/auth/__tests__/restore-previous-session.spec.ts diff --git a/src/helpers/auth/__tests__/restore-previous-session.spec.ts b/src/helpers/auth/__tests__/restore-previous-session.spec.ts new file mode 100644 index 0000000..1a7b872 --- /dev/null +++ b/src/helpers/auth/__tests__/restore-previous-session.spec.ts @@ -0,0 +1,69 @@ +import { Scraper } from "@the-convocation/twitter-scraper"; +import { Cookie } from "tough-cookie"; + +import * as cookies from "../../cookies/get-cookies.js"; +import { restorePreviousSession } from "../restore-previous-session.js"; + +const getCookiesMock = jest.spyOn(cookies, "getCookies"); +const setCookiesMock = jest.fn(); + +jest.mock("../../../constants.js", () => { + return {}; +}); + +const cookieMock = { + key: "cookie_id", + value: "value", + expires: new Date("2024-09-14T12:39:32.000Z"), + maxAge: 34214400, + domain: "twitter.com", + path: "/", + secure: true, + hostOnly: false, + creation: new Date("2023-11-04T11:15:28.230Z"), + lastAccessed: new Date("2023-11-04T11:15:29.203Z"), + sameSite: "none", +} as Cookie; + +describe("restorePreviousSession", () => { + beforeEach(() => { + jest.clearAllMocks(); + }); + + describe("when cookies are available", () => { + beforeEach(() => { + getCookiesMock.mockResolvedValueOnce([cookieMock]); + }); + + it("should restore previous session", async () => { + await restorePreviousSession({ + setCookies: setCookiesMock, + } as unknown as Scraper); + + expect(setCookiesMock).toHaveBeenCalledTimes(1); + expect(setCookiesMock).toHaveBeenCalledWith([cookieMock]); + }); + }); + + describe("when cookies are not available", () => { + const originalConsole = console.log; + const consoleMock = jest.fn(); + beforeEach(() => { + getCookiesMock.mockResolvedValueOnce(null); + console.log = consoleMock; + }); + + afterAll(() => { + console.log = originalConsole; + }); + + it("should not restore previous session", async () => { + await restorePreviousSession({ + setCookies: setCookiesMock, + } as unknown as Scraper); + + expect(setCookiesMock).not.toHaveBeenCalled(); + expect(consoleMock).toHaveBeenCalledTimes(1); + }); + }); +});