-
Notifications
You must be signed in to change notification settings - Fork 46
Expand file tree
/
Copy pathWebBluetoothTransport.test.ts
More file actions
277 lines (236 loc) · 8.76 KB
/
WebBluetoothTransport.test.ts
File metadata and controls
277 lines (236 loc) · 8.76 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
import "./setup/webBluetooth.setup";
import { BLUETOOTH_PRIMARY_SERVICE_UUID_HEX } from "@neurosity/ipk";
import { BLUETOOTH_DEVICE_NAME_PREFIXES } from "@neurosity/ipk";
import { BLUETOOTH_COMPANY_IDENTIFIER_HEX } from "@neurosity/ipk";
import { NEVER } from "rxjs";
import { WebBluetoothTransport } from "../api/bluetooth/web/WebBluetoothTransport";
import { BLUETOOTH_CONNECTION, TRANSPORT_TYPE } from "../api/bluetooth/types";
import { DeviceInfo } from "../types/deviceInfo";
import { isWebBluetoothSupported } from "../api/bluetooth/web/isWebBluetoothSupported";
// Get the mock function for isWebBluetoothSupported
const mockIsWebBluetoothSupported = jest.requireMock(
"../api/bluetooth/web/isWebBluetoothSupported"
).isWebBluetoothSupported;
describe("WebBluetoothTransport", () => {
let transport: WebBluetoothTransport;
let mockDevice: BluetoothDevice;
let mockServer: BluetoothRemoteGATTServer;
let mockService: BluetoothRemoteGATTService;
let mockCharacteristic: BluetoothRemoteGATTCharacteristic;
beforeEach(() => {
// Mock device and GATT objects
mockCharacteristic = {
uuid: "characteristic-uuid",
properties: {
write: true,
notify: true
},
startNotifications: jest.fn().mockResolvedValue(undefined),
addEventListener: jest.fn(),
removeEventListener: jest.fn(),
writeValue: jest.fn().mockResolvedValue(undefined)
} as unknown as BluetoothRemoteGATTCharacteristic;
mockService = {
uuid: BLUETOOTH_PRIMARY_SERVICE_UUID_HEX,
getCharacteristics: jest.fn().mockResolvedValue([mockCharacteristic])
} as unknown as BluetoothRemoteGATTService;
mockServer = {
connected: true,
getPrimaryService: jest.fn().mockResolvedValue(mockService),
connect: jest.fn().mockResolvedValue(undefined),
disconnect: jest.fn()
} as unknown as BluetoothRemoteGATTServer;
mockDevice = {
id: "test-device",
name: "Test Device",
gatt: mockServer,
watchAdvertisements: jest.fn().mockResolvedValue(undefined),
addEventListener: jest.fn(),
removeEventListener: jest.fn()
} as unknown as BluetoothDevice;
// Mock navigator.bluetooth methods
(window.navigator.bluetooth.getDevices as jest.Mock).mockResolvedValue([]);
(window.navigator.bluetooth.requestDevice as jest.Mock).mockResolvedValue(
mockDevice
);
transport = new WebBluetoothTransport();
});
afterEach(() => {
jest.clearAllMocks();
});
it("should initialize with correct type and default options", () => {
expect(transport.type).toBe(TRANSPORT_TYPE.WEB);
expect(transport.options.autoConnect).toBe(true);
});
it("should throw error if Web Bluetooth is not supported", () => {
mockIsWebBluetoothSupported.mockReturnValueOnce(false);
expect(() => new WebBluetoothTransport()).toThrow(
"Web Bluetooth is not supported"
);
});
it("should enable/disable auto connect", (done) => {
transport.enableAutoConnect(false);
transport.connection().subscribe((connection) => {
expect(connection).toBe(BLUETOOTH_CONNECTION.DISCONNECTED);
done();
});
});
it("should handle connection state changes", (done) => {
// Set device before changing connection state to avoid unhandled error
// when _onDisconnected() tries to attach listener to device
transport.device = mockDevice;
const states: BLUETOOTH_CONNECTION[] = [];
transport.connection().subscribe((state) => {
states.push(state);
if (states.length === 2) {
expect(states).toEqual([
BLUETOOTH_CONNECTION.DISCONNECTED,
BLUETOOTH_CONNECTION.CONNECTED
]);
done();
}
});
transport.connection$.next(BLUETOOTH_CONNECTION.CONNECTED);
});
it("should request device with correct options", async () => {
const deviceNickname = "Test Device";
await transport.requestDevice(deviceNickname);
expect(window.navigator.bluetooth.requestDevice).toHaveBeenCalledWith({
filters: [
{
name: deviceNickname
},
{
manufacturerData: [
{
companyIdentifier: BLUETOOTH_COMPANY_IDENTIFIER_HEX
}
]
}
],
optionalServices: [BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]
});
});
it("should request device with prefixes when no nickname provided", async () => {
await transport.requestDevice();
expect(window.navigator.bluetooth.requestDevice).toHaveBeenCalledWith({
filters: [
...BLUETOOTH_DEVICE_NAME_PREFIXES.map((namePrefix) => ({
namePrefix
})),
{
manufacturerData: [
{
companyIdentifier: BLUETOOTH_COMPANY_IDENTIFIER_HEX
}
]
}
],
optionalServices: [BLUETOOTH_PRIMARY_SERVICE_UUID_HEX]
});
});
it("should connect to device and setup GATT server", async () => {
(mockServer.connect as jest.Mock).mockResolvedValueOnce(mockServer);
await transport.getServerServiceAndCharacteristics(mockDevice);
expect(mockServer.connect).toHaveBeenCalled();
expect(mockServer.getPrimaryService).toHaveBeenCalledWith(
BLUETOOTH_PRIMARY_SERVICE_UUID_HEX
);
expect(mockService.getCharacteristics).toHaveBeenCalled();
expect(transport.connection$.getValue()).toBe(
BLUETOOTH_CONNECTION.CONNECTED
);
});
it("should handle disconnection", (done) => {
(mockServer.connect as jest.Mock).mockResolvedValueOnce(mockServer);
transport.device = mockDevice;
transport.server = mockServer;
transport.connection$.next(BLUETOOTH_CONNECTION.CONNECTED);
transport.connection().subscribe((connection) => {
if (connection === BLUETOOTH_CONNECTION.DISCONNECTED) {
done();
}
});
// Simulate disconnection
const disconnectCallback = (
mockDevice.addEventListener as jest.Mock
).mock.calls.find(
([eventName]: [string]) => eventName === "gattserverdisconnected"
)[1];
disconnectCallback();
});
it("should auto connect when enabled", async () => {
const selectedDevice$ = NEVER;
const autoConnect$ = transport._autoConnect(selectedDevice$);
// Subscribe to auto connect observable
autoConnect$.subscribe();
// Verify auto connect is enabled
expect(transport.options.autoConnect).toBe(true);
});
it("should get paired devices", async () => {
const devices = [mockDevice];
(window.navigator.bluetooth.getDevices as jest.Mock).mockResolvedValueOnce(
devices
);
const result = await transport._getPairedDevices();
expect(result).toEqual(devices);
});
it("should check connection status", () => {
// Set device before changing connection state to avoid unhandled error
transport.device = mockDevice;
transport.connection$.next(BLUETOOTH_CONNECTION.CONNECTED);
expect(transport.isConnected()).toBe(true);
transport.connection$.next(BLUETOOTH_CONNECTION.DISCONNECTED);
expect(transport.isConnected()).toBe(false);
});
it("should add logs", (done) => {
const testLog = "Test log message";
transport.addLog(testLog);
// logs$ is a ReplaySubject, so we need to check if our log was added
const logs: string[] = [];
transport.logs$.subscribe((log) => {
logs.push(log);
if (log === testLog) {
expect(logs).toContain(testLog);
done();
}
});
});
it("should handle connection errors", async () => {
const error = new Error("Connection failed");
(mockServer.connect as jest.Mock).mockRejectedValueOnce(error);
await expect(
transport.getServerServiceAndCharacteristics(mockDevice)
).rejects.toThrow("Connection failed");
expect(transport.connection$.getValue()).not.toBe(
BLUETOOTH_CONNECTION.CONNECTED
);
});
it("should handle service discovery errors", async () => {
(mockServer.connect as jest.Mock).mockResolvedValueOnce(mockServer);
(mockServer.getPrimaryService as jest.Mock).mockRejectedValueOnce(
new Error("Service not found")
);
await expect(
transport.getServerServiceAndCharacteristics(mockDevice)
).rejects.toThrow("Service not found");
expect(transport.connection$.getValue()).not.toBe(
BLUETOOTH_CONNECTION.CONNECTED
);
});
it("should handle characteristic discovery errors", async () => {
(mockServer.connect as jest.Mock).mockResolvedValueOnce(mockServer);
(mockServer.getPrimaryService as jest.Mock).mockResolvedValueOnce(
mockService
);
(mockService.getCharacteristics as jest.Mock).mockRejectedValueOnce(
new Error("Characteristics not found")
);
await expect(
transport.getServerServiceAndCharacteristics(mockDevice)
).rejects.toThrow("Characteristics not found");
expect(transport.connection$.getValue()).not.toBe(
BLUETOOTH_CONNECTION.CONNECTED
);
});
});