Skip to content

Commit cfdaf72

Browse files
committed
fix mocks to use constructable functions
1 parent 7389e04 commit cfdaf72

2 files changed

Lines changed: 26 additions & 11 deletions

File tree

src/components/MapillaryViewer/MapillaryViewer.test.jsx

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -4,10 +4,15 @@ import MapillaryViewer from "./MapillaryViewer";
44

55
vitest.mock("mapillary-js", () => {
66
return {
7-
Viewer: vitest.fn().mockImplementation(() => ({
8-
setImageId: vitest.fn(),
9-
remove: vitest.fn(),
10-
})),
7+
// Use a regular (constructable) function rather than an arrow function:
8+
// the component invokes `new Viewer(...)`, and vitest constructs the mock
9+
// via its implementation, which arrow functions cannot satisfy.
10+
Viewer: vitest.fn(function () {
11+
return {
12+
setImageId: vitest.fn(),
13+
remove: vitest.fn(),
14+
};
15+
}),
1116
};
1217
});
1318

src/services/Server/WebSocketClient.test.js

Lines changed: 17 additions & 7 deletions
Original file line numberDiff line numberDiff line change
@@ -20,8 +20,11 @@ describe("WebSocketClient", () => {
2020
// Clear any previous mocks
2121
vi.clearAllMocks();
2222

23-
// Mock the global WebSocket
24-
global.WebSocket = vi.fn(() => {
23+
// Mock the global WebSocket. Use a regular (constructable) function rather
24+
// than an arrow function: the client invokes `new WebSocket(...)`, which
25+
// vitest satisfies by constructing the mock's implementation — and arrow
26+
// functions cannot be constructed.
27+
global.WebSocket = vi.fn(function () {
2528
// Set up the mock WebSocket and return it
2629
setTimeout(() => {
2730
if (mockWebSocket.onopen) {
@@ -47,7 +50,9 @@ describe("WebSocketClient", () => {
4750
describe("connection management", () => {
4851
it("establishes connection on instantiation", () => {
4952
// Mock the WebSocket constructor before creating the client
50-
const wsConstructorSpy = vi.fn(() => mockWebSocket);
53+
const wsConstructorSpy = vi.fn(function () {
54+
return mockWebSocket;
55+
});
5156
global.WebSocket = wsConstructorSpy;
5257

5358
client = new WebSocketClient();
@@ -78,10 +83,15 @@ describe("WebSocketClient", () => {
7883
onclose: null,
7984
};
8085

81-
const wsConstructorSpy = vi
82-
.fn()
83-
.mockReturnValueOnce(firstMockWebSocket)
84-
.mockReturnValueOnce(secondMockWebSocket);
86+
// Regular (constructable) function returning a different socket per call:
87+
// the client constructs the WebSocket via `new`, which arrow functions and
88+
// bare mockReturnValue mocks cannot satisfy. The call counter lives outside
89+
// the spy so it survives the mockClear() below.
90+
let constructCount = 0;
91+
const sockets = [firstMockWebSocket, secondMockWebSocket];
92+
const wsConstructorSpy = vi.fn(function () {
93+
return sockets[constructCount++] ?? secondMockWebSocket;
94+
});
8595

8696
global.WebSocket = wsConstructorSpy;
8797

0 commit comments

Comments
 (0)