|
| 1 | +// eslint-disable-next-line @typescript-eslint/no-restricted-imports |
| 2 | +import Cookies from "js-cookie" |
| 3 | + |
| 4 | +import ExpressCookies from "./cookies" |
| 5 | + |
| 6 | +function testCookie( |
| 7 | + value: any, |
| 8 | + { |
| 9 | + name = "name", |
| 10 | + path = "/", |
| 11 | + setValue, |
| 12 | + getValue, |
| 13 | + }: { |
| 14 | + name?: string |
| 15 | + path?: string |
| 16 | + setValue?: string |
| 17 | + getValue?: any |
| 18 | + } = {}, |
| 19 | +) { |
| 20 | + const cookieValue = ExpressCookies.set(name, value) |
| 21 | + setValue = setValue ?? String(value) |
| 22 | + setValue = Cookies.converter.write(setValue, name) |
| 23 | + expect(cookieValue).toBe(`${name}=${setValue}; path=${path}`) |
| 24 | + |
| 25 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment |
| 26 | + const actualValue = ExpressCookies.get(name) |
| 27 | + // eslint-disable-next-line @typescript-eslint/no-unsafe-assignment |
| 28 | + getValue = getValue ?? value |
| 29 | + expect(typeof actualValue).toEqual(typeof getValue) |
| 30 | +} |
| 31 | + |
| 32 | +test("round-trips an object as a Express JSON cookie", () => { |
| 33 | + const value = { key: "value" } |
| 34 | + testCookie(value, { setValue: `j:${JSON.stringify(value)}` }) |
| 35 | +}) |
| 36 | + |
| 37 | +test("round-trips an array as a Express JSON cookie", () => { |
| 38 | + const value = [1, 2, 3] |
| 39 | + testCookie(value, { setValue: `j:${JSON.stringify(value)}` }) |
| 40 | +}) |
| 41 | + |
| 42 | +test("returns plain string cookies as-is", () => { |
| 43 | + testCookie("plain-text") |
| 44 | +}) |
| 45 | + |
| 46 | +test("does not mark JSON primitives as Express JSON cookies", () => { |
| 47 | + testCookie(42, { getValue: "42" }) |
| 48 | +}) |
0 commit comments