-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbackground.test.js
450 lines (394 loc) · 14.6 KB
/
background.test.js
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
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
// Mock chrome API
global.chrome = {
storage: {
sync: {
get: jest.fn(),
set: jest.fn(),
},
local: {
get: jest.fn(),
set: jest.fn(),
},
},
tabs: {
query: jest.fn(),
group: jest.fn(),
onUpdated: {
addListener: jest.fn(),
},
onRemoved: {
addListener: jest.fn(),
},
},
tabGroups: {
update: jest.fn(),
},
alarms: {
clear: jest.fn(),
create: jest.fn(),
onAlarm: {
addListener: jest.fn(),
},
},
runtime: {
onMessage: {
addListener: jest.fn(),
},
onInstalled: {
addListener: jest.fn(),
},
getURL: jest.fn(),
},
};
// Mock console.error
global.console.error = jest.fn();
// Import functions to test
import {
cosineSimilarity,
jaccardSimilarity,
generateGroupName,
extractKeyphrases,
extractPageTypes,
groupTabs,
isGroupableTab,
loadSettings,
settings
} from './background.js';
// Mock the QCO module
jest.mock('./src/quantumChaosOrganizer.js', () => ({
groupTabsQuantumChaosOrganizer: jest.fn()
}));
// Update the import path
import { groupTabsQuantumChaosOrganizer } from './src/quantumChaosOrganizer.js';
// Mock chrome API and global settings
beforeAll(() => {
global.settings = {
groupingAlgorithm: 'qco',
similarityThreshold: 0.5,
maxGroupNameLength: 50,
groupingInterval: 5,
};
});
describe('Tab Grouping Extension', () => {
beforeEach(() => {
jest.clearAllMocks();
// Reset settings before each test
global.settings = {
groupingAlgorithm: 'qco',
similarityThreshold: 0.5,
maxGroupNameLength: 50,
groupingInterval: 5,
};
});
describe('cosineSimilarity', () => {
test('calculates cosine similarity correctly', () => {
const doc1 = { term1: 1, term2: 2 };
const doc2 = { term1: 2, term2: 1 };
expect(cosineSimilarity(doc1, doc2)).toBeCloseTo(0.8, 2);
});
test('returns 0 for orthogonal vectors', () => {
const doc1 = { term1: 1 };
const doc2 = { term2: 1 };
expect(cosineSimilarity(doc1, doc2)).toBe(0);
});
test('returns 1 for identical vectors', () => {
const doc1 = { term1: 1, term2: 2 };
const doc2 = { term1: 1, term2: 2 };
expect(cosineSimilarity(doc1, doc2)).toBeCloseTo(1, 10);
});
});
describe('jaccardSimilarity', () => {
test('calculates Jaccard similarity correctly', () => {
const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['b', 'c', 'd']);
expect(jaccardSimilarity(set1, set2)).toBe(0.5);
});
test('returns 1 for identical sets', () => {
const set1 = new Set(['a', 'b', 'c']);
const set2 = new Set(['a', 'b', 'c']);
expect(jaccardSimilarity(set1, set2)).toBe(1);
});
test('returns 0 for disjoint sets', () => {
const set1 = new Set(['a', 'b']);
const set2 = new Set(['c', 'd']);
expect(jaccardSimilarity(set1, set2)).toBe(0);
});
});
describe('generateGroupName', () => {
beforeEach(() => {
// Reset settings before each test
global.settings = {
maxGroupNameLength: 50
};
});
test('generates a group name based on common terms', () => {
const docs = [
'https://example.com/page1 Example Website',
'https://example.com/page2 Another Example'
];
const name = generateGroupName(docs);
expect(name.toLowerCase()).toContain('example');
});
test('respects maxGroupNameLength setting', () => {
const docs = [
'https://verylongdomainname.com/page1 Very Long Title That Should Be Truncated',
'https://verylongdomainname.com/page2 Another Very Long Title'
];
console.log('Before test - settings:', global.settings);
global.settings = { maxGroupNameLength: 10 };
console.log('After setting - settings:', global.settings);
const name = generateGroupName(docs);
console.log('Generated name:', name, 'length:', name.length);
expect(name.length).toBeLessThanOrEqual(10);
});
test('combines domain and top term when both are available', () => {
const docs = [
'https://github.com/user/repo JavaScript Project Repository',
'https://github.com/user/another-repo Another JavaScript Project'
];
const name = generateGroupName(docs);
expect(name).toBe('Github: javascript');
});
test('uses page type and top term when domain varies', () => {
const docs = [
'https://site1.com/tutorials/js Learn JavaScript Tutorial',
'https://site2.com/learn/javascript Complete JavaScript Course'
];
const name = generateGroupName(docs);
expect(name).toBe('Learning: javascript');
});
test('combines multiple top terms when no common domain or page type', () => {
const docs = [
'https://site1.com/page1 React Framework Overview',
'https://site2.com/page2 Using React Components'
];
const name = generateGroupName(docs);
expect(name).toBe('react & components');
});
test('handles empty input gracefully', () => {
expect(generateGroupName([])).toBe('Group');
expect(generateGroupName(null)).toBe('Group');
expect(generateGroupName(undefined)).toBe('Group');
});
test('filters out stop words from group names', () => {
const docs = [
'https://site.com/page The and of with JavaScript',
'https://site.com/other The and of with Programming'
];
const name = generateGroupName(docs);
// Should not contain stop words like "the", "and", "of", "with"
expect(name.toLowerCase()).not.toMatch(/\b(the|and|of|with)\b/);
// Should contain meaningful terms
expect(name.toLowerCase()).toMatch(/\b(javascript|programming)\b/);
});
});
describe('extractPageTypes', () => {
test('identifies news content', () => {
const docs = [
'https://news.com/article Latest News Article',
'https://blog.com/post Blog Post About Current Events'
];
const types = extractPageTypes(docs);
expect(types).toContain('News');
});
test('identifies shopping content', () => {
const docs = [
'https://shop.com/product Buy This Product',
'https://store.com/item Best Price for Item'
];
const types = extractPageTypes(docs);
expect(types).toContain('Shopping');
});
test('identifies multiple content types with correct frequency order', () => {
const docs = [
'https://site.com/video Watch This Video',
'https://site.com/tutorial Learn From This Tutorial',
'https://site.com/another-video Another Video To Watch',
'https://site.com/article News Article'
];
const types = extractPageTypes(docs);
// Video appears twice, so it should be first
expect(types[0]).toBe('Video');
expect(types).toContain('Learning');
expect(types).toContain('News');
});
test('returns empty array when no recognized types', () => {
const docs = [
'https://site.com/page Generic Page With No Type',
'https://site.com/other Another Generic Page'
];
const types = extractPageTypes(docs);
expect(types).toEqual([]);
});
});
describe('extractKeyphrases', () => {
test('extracts keyphrases from text', () => {
const text = 'artificial intelligence machine learning deep neural networks';
const phrases = extractKeyphrases(text);
expect(phrases).toContain('artificial intelligence');
});
test('respects the number of phrases parameter', () => {
const text = 'artificial intelligence machine learning deep neural networks data science';
const phrases = extractKeyphrases(text, 2);
expect(phrases.length).toBeLessThanOrEqual(2);
});
});
describe('groupTabs - QCO algorithm respects pinned tabs', () => {
beforeEach(() => {
jest.clearAllMocks();
// Mock chrome.tabs.query to return test data
chrome.tabs.query.mockResolvedValue([]);
// Mock chrome.tabs.group to return a group ID
chrome.tabs.group.mockResolvedValue(1);
// Mock chrome.tabGroups.update to resolve successfully
chrome.tabGroups.update.mockResolvedValue({});
// Mock chrome.storage.sync.get to return QCO settings
chrome.storage.sync.get.mockImplementation(defaults =>
Promise.resolve({
...defaults,
groupingAlgorithm: 'qco',
maxGroupNameLength: 50
})
);
});
test('should not include pinned tabs when grouping with QCO', async () => {
// Set up test data
const tabs = [
{ id: 1, pinned: true, url: 'https://example1.com', title: 'Example 1' },
{ id: 2, pinned: false, url: 'https://example2.com', title: 'Example 2' },
{ id: 3, pinned: false, url: 'https://example3.com', title: 'Example 3' }
];
// Set up mocks
chrome.tabs.query.mockResolvedValue(tabs);
// Prepare expected input for the mocked QCO function
const expectedQcoInput = tabs
.filter(tab => !tab.pinned)
.map(t => ({ id: t.id, url: t.url, title: t.title, pinned: t.pinned })); // Match input format
// Setup mock return value based on the expected input structure
const mockGroupResult = [ expectedQcoInput.map(t => ({ id: t.id, url: t.url, title: t.title })) ]; // QCO returns groups of tab objects
groupTabsQuantumChaosOrganizer.mockReturnValue(mockGroupResult);
// Load settings and execute groupTabs
await loadSettings(); // Ensure settings are loaded with 'qco'
global.settings.groupingAlgorithm = 'qco'; // Force setting for test if needed
await groupTabs(); // Call the main function
// Verify the mock was called with the correct, filtered tabs
expect(groupTabsQuantumChaosOrganizer).toHaveBeenCalledTimes(1);
expect(groupTabsQuantumChaosOrganizer).toHaveBeenCalledWith(expectedQcoInput);
// Verify chrome.tabs.group was called based on the mock's return value
expect(chrome.tabs.group).toHaveBeenCalledWith({
tabIds: expectedQcoInput.map(t => t.id) // Extract IDs from the mock input/output
});
});
test('handles empty tab list gracefully', async () => {
chrome.tabs.query.mockResolvedValue([]);
await groupTabs();
expect(groupTabsQuantumChaosOrganizer).not.toHaveBeenCalled();
expect(chrome.tabs.group).not.toHaveBeenCalled();
});
test('handles all pinned tabs gracefully', async () => {
const allPinnedTabs = [
{ id: 1, pinned: true, url: 'https://example1.com', title: 'Example 1' },
{ id: 2, pinned: true, url: 'https://example2.com', title: 'Example 2' }
];
chrome.tabs.query.mockResolvedValue(allPinnedTabs);
await groupTabs();
expect(groupTabsQuantumChaosOrganizer).not.toHaveBeenCalled();
expect(chrome.tabs.group).not.toHaveBeenCalled();
});
test('handles errors in QCO gracefully', async () => {
// Set up test data
const tabs = [
{ id: 1, pinned: false, url: 'https://example.com', title: 'Example' }
];
// Set up mocks
chrome.tabs.query.mockResolvedValue(tabs);
// Mock QCO to throw an error
const testError = new Error('QCO processing error');
groupTabsQuantumChaosOrganizer.mockImplementation(() => {
throw testError;
});
// Mock console.error specifically for this test
const originalConsoleError = console.error;
console.error = jest.fn();
try {
// Load settings and execute groupTabs
await loadSettings();
await groupTabs();
// Verify error handling
expect(chrome.tabs.group).not.toHaveBeenCalled();
expect(console.error).toHaveBeenCalledWith(
'Error in groupTabs: QCO algorithm failed',
testError
);
// Verify no other errors were logged
expect(console.error).toHaveBeenCalledTimes(1);
} finally {
// Restore console.error
console.error = originalConsoleError;
}
});
});
});
describe('Clustering Filter Tests', () => {
// Import the function to test
const { clusterTabs, hierarchicalAgglomerativeClustering } = require('./background.js');
// Import the function we need to mock/control
const { cosineSimilarity } = require('./src/utils/math.js'); // Adjust path if necessary
beforeEach(() => {
// Reset mocks before each test
cosineSimilarity.mockClear();
});
test('clusterTabs filters out clusters with less than 3 tabs', () => {
// Create a simulated tabVectors object.
// Let's assume each tab vector is identical so cosine similarity always 1 > threshold
// Create 5 tabs, but arrange manually so that one cluster ends up being of size 2
const tabVectors = {
'1': { a: 1 },
'2': { a: 1 },
'3': { a: 1 },
'4': { a: 0 }, // This one will be isolated if similarity is 0
'5': { a: 0 } // Similar to 4 so cluster of size 2
};
// Configure the mock implementation for this specific test
cosineSimilarity.mockImplementation((vec1, vec2) => {
if ((vec1.a === 1 && vec2.a === 1) || (vec1.a === 0 && vec2.a === 0)) {
return 1;
}
return 0;
});
// Set similarityThreshold to 0.5 in settings
global.settings = { similarityThreshold: 0.5 };
const clusters = clusterTabs(tabVectors);
// Expected: Only the cluster with tabs '1','2','3' should be returned, group with tabs '4' and '5' is filtered out
expect(clusters).toEqual([['1', '2', '3']]);
// Verify mock usage if needed
// expect(cosineSimilarity).toHaveBeenCalled();
});
test('hierarchicalAgglomerativeClustering filters out clusters with less than 3 tabs', () => {
// ... setup tabVectors ...
const tabVectors = {
'1': { a: 1 },
'2': { a: 1 },
'3': { a: 1 },
'4': { a: 0 },
'5': { a: 0 },
'6': { a: 1 }
};
// Configure the mock implementation for this specific test
cosineSimilarity.mockImplementation((vec1, vec2) => {
if ((vec1.a === 1 && vec2.a === 1) || (vec1.a === 0 && vec2.a === 0)) {
return 1;
}
return 0;
});
// Set similarityThreshold to 0.5 in settings
global.settings = { similarityThreshold: 0.5 };
const clusters = hierarchicalAgglomerativeClustering(tabVectors);
// ... assertions ...
const expectedCluster = ['1', '2', '3', '6'];
// Since order might vary, sort the clusters for comparison
const sortedClusters = clusters.map(cluster => cluster.sort());
expect(sortedClusters).toContainEqual(expectedCluster.sort());
expect(clusters.some(cluster => cluster.length === 2)).toBe(false);
});
});