|
| 1 | +import { describe, it, expect, beforeEach, afterEach, vi } from "vitest" |
1 | 2 | import { hasConsent, dispatchConsentEvent, onConsentChange, CONSENT_EVENT } from "../consent-manager" |
2 | 3 |
|
3 | 4 | describe("Consent Manager", () => { |
4 | | - // Store the original document.cookie |
5 | | - let originalCookie: PropertyDescriptor | undefined |
| 5 | + let cookieSpy: vi.SpyInstance |
6 | 6 |
|
7 | 7 | beforeEach(() => { |
8 | | - // Clear cookies before each test |
9 | | - originalCookie = Object.getOwnPropertyDescriptor(Document.prototype, "cookie") |
10 | | - Object.defineProperty(document, "cookie", { |
11 | | - writable: true, |
12 | | - value: "", |
13 | | - }) |
14 | | - // Clear any event listeners |
| 8 | + // Mock document.cookie to control its value in tests |
| 9 | + cookieSpy = vi.spyOn(document, "cookie", "get") |
| 10 | + |
| 11 | + // Clear mock history before each test |
15 | 12 | vi.clearAllMocks() |
16 | 13 | }) |
17 | 14 |
|
18 | 15 | afterEach(() => { |
19 | | - // Restore original cookie property |
20 | | - if (originalCookie) { |
21 | | - Object.defineProperty(Document.prototype, "cookie", originalCookie) |
22 | | - } |
| 16 | + // Restore the original document.cookie property |
| 17 | + vi.restoreAllMocks() |
23 | 18 | }) |
24 | 19 |
|
25 | 20 | describe("hasConsent", () => { |
26 | 21 | it("should return false when no consent cookie exists", () => { |
27 | | - document.cookie = "" |
| 22 | + cookieSpy.mockReturnValue("") |
28 | 23 | expect(hasConsent()).toBe(false) |
29 | 24 | }) |
30 | 25 |
|
31 | 26 | it('should return false when consent cookie is not "true"', () => { |
32 | | - document.cookie = "roo-code-cookie-consent=false" |
| 27 | + cookieSpy.mockReturnValue("roo-code-cookie-consent=false") |
33 | 28 | expect(hasConsent()).toBe(false) |
34 | 29 | }) |
35 | 30 |
|
36 | 31 | it('should return true when consent cookie is "true"', () => { |
37 | | - document.cookie = "roo-code-cookie-consent=true" |
| 32 | + cookieSpy.mockReturnValue("roo-code-cookie-consent=true") |
38 | 33 | expect(hasConsent()).toBe(true) |
39 | 34 | }) |
40 | 35 |
|
41 | 36 | it("should handle multiple cookies correctly", () => { |
42 | | - document.cookie = "other-cookie=value; roo-code-cookie-consent=true; another-cookie=value2" |
| 37 | + cookieSpy.mockReturnValue("other-cookie=value; roo-code-cookie-consent=true; another-cookie=value2") |
43 | 38 | expect(hasConsent()).toBe(true) |
44 | 39 | }) |
45 | 40 |
|
46 | 41 | it("should handle cookies with spaces correctly", () => { |
47 | | - document.cookie = "other-cookie=value; roo-code-cookie-consent=true ; another-cookie=value2" |
| 42 | + cookieSpy.mockReturnValue("other-cookie=value; roo-code-cookie-consent=true ; another-cookie=value2") |
48 | 43 | expect(hasConsent()).toBe(true) |
49 | 44 | }) |
50 | 45 | }) |
|
0 commit comments