Skip to content

Commit cbb6f16

Browse files
committed
test: add useSee test
1 parent 21d50a5 commit cbb6f16

File tree

1 file changed

+103
-0
lines changed

1 file changed

+103
-0
lines changed

src/hooks/__tests__/useSee.test.ts

+103
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,103 @@
1+
import { renderHook, act } from "@testing-library/react";
2+
import { vi } from "vitest";
3+
import { useSse } from "../useSse";
4+
5+
const mockSendNotification = vi.fn();
6+
vi.mock("../useBrowserNotification", () => ({
7+
useBrowserNotification: vi.fn(() => {
8+
return { sendNotification: mockSendNotification };
9+
}),
10+
}));
11+
12+
class MockEventSource {
13+
static instances: MockEventSource[] = [];
14+
private _onmessage: ((event: MessageEvent) => void) | null = null;
15+
16+
constructor() {
17+
MockEventSource.instances.push(this);
18+
}
19+
20+
get onmessage() {
21+
return this._onmessage;
22+
}
23+
24+
set onmessage(handler: ((event: MessageEvent) => void) | null) {
25+
this._onmessage = handler;
26+
}
27+
28+
close() {}
29+
30+
static triggerMessage(data: string) {
31+
MockEventSource.instances.forEach((instance) => {
32+
if (instance.onmessage) {
33+
instance.onmessage({ data } as MessageEvent);
34+
}
35+
});
36+
}
37+
}
38+
39+
let originalEventSource: typeof EventSource;
40+
41+
describe("useSse", () => {
42+
beforeAll(() => {
43+
vi.mock("react-router-dom", () => ({
44+
useLocation: vi.fn(() => ({ pathname: "/" })),
45+
}));
46+
47+
vi.useFakeTimers();
48+
originalEventSource = global.EventSource;
49+
global.EventSource = MockEventSource as unknown as typeof EventSource;
50+
51+
Object.defineProperty(global, "location", {
52+
value: {
53+
reload: vi.fn(),
54+
},
55+
writable: true,
56+
});
57+
});
58+
59+
afterAll(() => {
60+
vi.clearAllMocks();
61+
vi.useRealTimers();
62+
global.EventSource = originalEventSource;
63+
});
64+
65+
it("should send notification if new alert is detected", () => {
66+
renderHook(() => useSse());
67+
68+
expect(MockEventSource.instances.length).toBe(1);
69+
const instance = MockEventSource.instances[0];
70+
expect(instance).toBeDefined();
71+
72+
expect(instance.onmessage).toBeDefined();
73+
74+
act(() => {
75+
MockEventSource.triggerMessage("new alert detected");
76+
});
77+
78+
expect(mockSendNotification).toHaveBeenCalledWith("CodeGate Dashboard", {
79+
body: "New Alert detected!",
80+
});
81+
82+
act(() => {
83+
vi.advanceTimersByTime(2000);
84+
});
85+
86+
expect(global.location.reload).toHaveBeenCalled();
87+
});
88+
89+
it("should send notification if new alert is detected", () => {
90+
renderHook(() => useSse());
91+
92+
act(() => {
93+
MockEventSource.triggerMessage("other message");
94+
});
95+
96+
expect(mockSendNotification).not.toHaveBeenCalledWith(
97+
"CodeGate Dashboard",
98+
{
99+
body: "New Alert detected!",
100+
},
101+
);
102+
});
103+
});

0 commit comments

Comments
 (0)