forked from AceCandy/cc-quick
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathscript.test.mjs
More file actions
894 lines (768 loc) · 23.8 KB
/
script.test.mjs
File metadata and controls
894 lines (768 loc) · 23.8 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
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
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
import test from 'node:test';
import assert from 'node:assert/strict';
import vm from 'node:vm';
import { readFile } from 'node:fs/promises';
const scriptSource = await readFile(new URL('./script.js', import.meta.url), 'utf8');
class FakeClassList {
constructor(initial = []) {
this.classes = new Set(initial);
}
add(name) {
this.classes.add(name);
}
remove(name) {
this.classes.delete(name);
}
toggle(name, force) {
if (force) {
this.classes.add(name);
return true;
}
this.classes.delete(name);
return false;
}
contains(name) {
return this.classes.has(name);
}
}
class FakeEventTarget {
constructor() {
this.listeners = new Map();
}
addEventListener(type, handler) {
const handlers = this.listeners.get(type) || [];
handlers.push(handler);
this.listeners.set(type, handlers);
}
dispatchEvent(event) {
const handlers = this.listeners.get(event.type) || [];
event.currentTarget = this;
for (const handler of handlers) {
handler.call(this, event);
if (event.propagationStopped) {
break;
}
}
return !event.defaultPrevented;
}
}
class FakeElement extends FakeEventTarget {
constructor({
textContent = '',
dataset = {},
classNames = [],
attributes = {},
style = {},
hidden = false,
rectTop = 0,
rectLeft = 0,
rectWidth = 0,
rectHeight = 0
} = {}) {
super();
this.textContent = textContent;
this.dataset = dataset;
this.classList = new FakeClassList(classNames);
this.attributes = attributes;
this.style = style;
this.children = [];
this.removed = false;
this.hidden = hidden;
this.closestHandlers = new Map();
this.rectTop = rectTop;
this.rectLeft = rectLeft;
this.rectWidth = rectWidth;
this.rectHeight = rectHeight;
}
querySelectorAll(selector) {
if (selector.startsWith('.')) {
const className = selector.slice(1);
return this.children.filter((child) => child.classList.contains(className));
}
return [];
}
setClosest(selector, value) {
this.closestHandlers.set(selector, value);
}
closest(selector) {
return this.closestHandlers.get(selector) || null;
}
contains(target) {
return this.children.includes(target);
}
click() {
const event = createEvent('click', { target: this });
super.dispatchEvent(event);
if (!event.propagationStopped && this.ownerDocument) {
this.ownerDocument.dispatchEvent(event);
}
}
getAttribute(name) {
return this.attributes[name];
}
setAttribute(name, value) {
this.attributes[name] = String(value);
}
hasAttribute(name) {
return Object.prototype.hasOwnProperty.call(this.attributes, name);
}
remove() {
this.removed = true;
}
getBoundingClientRect() {
return {
top: this.rectTop,
left: this.rectLeft,
width: this.rectWidth,
height: this.rectHeight,
right: this.rectLeft + this.rectWidth,
bottom: this.rectTop + this.rectHeight
};
}
}
function createEvent(type, init = {}) {
return {
type,
target: init.target || null,
key: init.key,
defaultPrevented: false,
propagationStopped: false,
preventDefault() {
this.defaultPrevented = true;
},
stopPropagation() {
this.propagationStopped = true;
}
};
}
function createLocalStorage(seed = {}) {
const store = new Map(Object.entries(seed));
return {
getItem(key) {
return store.has(key) ? store.get(key) : null;
},
setItem(key, value) {
store.set(key, String(value));
},
removeItem(key) {
store.delete(key);
}
};
}
function createEnvironment({
keyTexts = [],
keycaps = [],
sections = [],
initialHash = '',
platform = 'Win32',
userAgent = 'Mozilla/5.0 (Windows NT 10.0; Win64; x64)',
storage = {},
prefersDark = false,
headerTop = 16,
headerHeight = 108,
sidebarTop = 72,
sidebarLeft = 0,
sidebarWidth = 200,
panelTop = 140,
panelLeft = 220,
panelWidth = 800
} = {}) {
const macButton = new FakeElement({
dataset: { os: 'mac' },
classNames: ['os-btn', 'active']
});
const winButton = new FakeElement({
dataset: { os: 'win' },
classNames: ['os-btn']
});
const toggle = new FakeElement();
toggle.children = [macButton, winButton];
const lightThemeButton = new FakeElement({
dataset: { theme: 'light' },
classNames: ['theme-btn', 'active']
});
const darkThemeButton = new FakeElement({
dataset: { theme: 'dark' },
classNames: ['theme-btn']
});
const themeToggle = new FakeElement();
themeToggle.children = [lightThemeButton, darkThemeButton];
const changelogTrigger = new FakeElement({
classNames: ['changelog-trigger'],
attributes: { 'aria-expanded': 'false' }
});
const changelog = new FakeElement({
classNames: ['changelog-panel'],
attributes: { id: 'changelogPanel' },
hidden: true
});
const changelogPanelInner = new FakeElement();
changelogPanelInner.setClosest('.changelog-panel', changelog);
changelog.children = [changelogPanelInner];
const sectionButtons = sections.map(({ target, active = false }) => new FakeElement({
dataset: { sectionTarget: target },
classNames: ['section-switcher-btn'].concat(active ? ['active'] : []),
attributes: {
'data-section-target': target,
'aria-pressed': active ? 'true' : 'false'
}
}));
const sectionPanels = sections.map(({ target, hidden = true }) => new FakeElement({
dataset: { sectionPanel: target },
attributes: { 'data-section-panel': target },
hidden,
rectTop: panelTop,
rectLeft: panelLeft,
rectWidth: panelWidth,
rectHeight: 320
}));
const pageSidebar = new FakeElement({
classNames: ['page-sidebar'],
rectTop: sidebarTop,
rectLeft: sidebarLeft,
rectWidth: sidebarWidth,
rectHeight: 480
});
const header = new FakeElement({
classNames: ['header'],
rectTop: headerTop,
rectHeight: headerHeight
});
const sectionHeadings = sections.map(({ target }) => new FakeElement({
attributes: { id: target }
}));
const panelByTarget = new Map(sectionPanels.map((panel, index) => [sections[index].target, panel]));
const headingById = new Map(sectionHeadings.map((heading, index) => [sections[index].target, heading]));
sections.forEach((section, index) => {
const button = sectionButtons[index];
const panel = sectionPanels[index];
const heading = sectionHeadings[index];
button.dataset.sectionTarget = section.target;
heading.setClosest('[data-section-panel]', panel);
panel.children = [heading];
});
const groupHeading = new FakeElement({
attributes: { id: 'section-keyboard-group-general-controls' }
});
groupHeading.setClosest('[data-section-panel]', sectionPanels[0] || null);
groupHeading.setClosest('.section-group', sectionPanels[0] || null);
const visitCount = new FakeElement({
textContent: '统计中…',
attributes: {
id: 'siteVisitCount',
'data-counter-namespace': 'cc-quick',
'data-counter-name': 'site-visits'
}
});
const keyElements = keyTexts.map((text) => new FakeElement({ textContent: text }));
const keycapElements = keycaps.map((text) => new FakeElement({ textContent: text }));
const badges = [];
const localStorage = createLocalStorage(storage);
const rootStyleValues = new Map();
const documentElement = {
dataset: {},
style: {
setProperty(name, value) {
rootStyleValues.set(name, String(value));
},
getPropertyValue(name) {
return rootStyleValues.get(name) || '';
}
}
};
const documentTarget = new FakeEventTarget();
const windowTarget = new FakeEventTarget();
const documentBody = new FakeElement();
documentBody.ownerDocument = null;
const outsideClickTarget = new FakeElement();
outsideClickTarget.ownerDocument = null;
const location = {};
const historyCalls = [];
let hashchangeCount = 0;
let hashValue = initialHash;
Object.defineProperty(location, 'hash', {
get() {
return hashValue;
},
set(value) {
const next = String(value);
if (next === hashValue) {
hashValue = next;
return;
}
hashValue = next;
hashchangeCount += 1;
windowTarget.dispatchEvent(createEvent('hashchange'));
}
});
const history = {
replaceState(_state, _title, url) {
historyCalls.push(url);
if (typeof url === 'string') {
const hashIndex = url.indexOf('#');
hashValue = hashIndex === -1 ? '' : url.slice(hashIndex);
}
}
};
const scrollByCalls = [];
const document = {
documentElement,
body: documentBody,
getElementById(id) {
if (id === 'osToggle') {
return toggle;
}
if (id === 'themeToggle') {
return themeToggle;
}
if (id === 'changelogPanel') {
return changelog;
}
if (id === 'changelogTrigger') {
return changelogTrigger;
}
const heading = headingById.get(id);
if (heading) {
return heading;
}
if (id === 'section-keyboard-group-general-controls') {
return groupHeading;
}
if (id === 'siteVisitCount') {
return visitCount;
}
return null;
},
querySelector(selector) {
if (selector === '.changelog-trigger') {
return changelogTrigger;
}
if (selector === '.header') {
return header;
}
if (selector === '.page-sidebar') {
return pageSidebar;
}
return null;
},
querySelectorAll(selector) {
if (selector === '.keycap') {
return keycapElements;
}
if (selector === '.key') {
return keyElements;
}
if (selector === '.badge-new[data-added]') {
return badges;
}
if (selector === '.section-switcher-btn') {
return sectionButtons;
}
if (selector === '[data-section-panel]') {
return sectionPanels;
}
return [];
},
addEventListener: documentTarget.addEventListener.bind(documentTarget),
dispatchEvent(event) {
if (!event.target) {
event.target = documentBody;
}
return documentTarget.dispatchEvent(event);
}
};
documentBody.ownerDocument = document;
outsideClickTarget.ownerDocument = document;
changelog.ownerDocument = document;
changelogPanelInner.ownerDocument = document;
changelogTrigger.ownerDocument = document;
visitCount.ownerDocument = document;
groupHeading.ownerDocument = document;
sectionButtons.forEach((button) => {
button.ownerDocument = document;
});
sectionPanels.forEach((panel) => {
panel.ownerDocument = document;
});
sectionHeadings.forEach((heading) => {
heading.ownerDocument = document;
});
header.ownerDocument = document;
for (const [target, panel] of panelByTarget.entries()) {
panel.setClosest('[data-section-panel]', panel);
panel.setClosest(`[data-section-panel="${target}"]`, panel);
}
const window = {
location,
history,
scrollBy(options) {
scrollByCalls.push(options);
},
addEventListener: windowTarget.addEventListener.bind(windowTarget),
dispatchEvent(event) {
return windowTarget.dispatchEvent(event);
}
};
window.window = window;
window.document = document;
const context = vm.createContext({
document,
window,
localStorage,
history,
navigator: { platform, userAgent },
setInterval(fn, delay) {
if (typeof window.setInterval === 'function') {
return window.setInterval(fn, delay);
}
return { fn, delay };
},
matchMedia(query) {
return {
matches: prefersDark && query === '(prefers-color-scheme: dark)'
};
},
Date,
console
});
return {
context,
window,
document,
documentElement,
header,
keyElements,
keycapElements,
macButton,
winButton,
lightThemeButton,
darkThemeButton,
sectionButtons,
sectionPanels,
sectionHeadings,
changelogTrigger,
changelog,
changelogPanelInner,
groupHeading,
visitCount,
outsideClickTarget,
localStorage,
historyCalls,
scrollByCalls,
getCssVar(name) {
return rootStyleValues.get(name) || '';
},
getHashchangeCount() {
return hashchangeCount;
}
};
}
function executeScript(context) {
vm.runInContext(scriptSource, context);
}
test('点击 mac 按钮时,纯文本快捷键也会切换到 Mac 写法', () => {
const env = createEnvironment({
keyTexts: ['ShiftTab', 'AltP'],
platform: 'Win32'
});
executeScript(env.context);
env.macButton.click();
assert.deepEqual(
env.keyElements.map((element) => element.textContent),
['⇧Tab', '⌥P']
);
assert.equal(env.localStorage.getItem('cc-os'), 'mac');
assert.equal(env.localStorage.getItem('cc-os-manual'), '1');
});
test('原有 keycap 结构继续按上游规则切换', () => {
const env = createEnvironment({
keycaps: ['Alt', 'Shift'],
platform: 'MacIntel',
userAgent: 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_7)'
});
executeScript(env.context);
env.winButton.click();
assert.deepEqual(
env.keycapElements.map((element) => element.textContent),
['Alt', 'Shift']
);
assert.equal(env.localStorage.getItem('cc-os'), 'win');
});
test('点击主题按钮时,会同步 data-theme 和 localStorage', () => {
const env = createEnvironment();
executeScript(env.context);
env.darkThemeButton.click();
assert.equal(env.documentElement.dataset.theme, 'dark');
assert.equal(env.localStorage.getItem('cc-theme'), 'dark');
assert.equal(env.darkThemeButton.classList.contains('active'), true);
assert.equal(env.lightThemeButton.classList.contains('active'), false);
});
test('没有手动主题时,会回退到系统主题', () => {
const env = createEnvironment({ prefersDark: true });
executeScript(env.context);
assert.equal(env.documentElement.dataset.theme, 'dark');
assert.equal(env.localStorage.getItem('cc-theme'), 'dark');
});
test('初始化时会根据 header 高度写入 sticky 偏移变量', () => {
const env = createEnvironment({
headerTop: 16,
headerHeight: 108
});
executeScript(env.context);
assert.equal(env.getCssVar('--sticky-shell-top'), '136px');
assert.equal(env.getCssVar('--sticky-scroll-margin'), '160px');
});
test('初始化时会默认激活第一个 section', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', active: true, hidden: false },
{ target: 'section-mcp', hidden: true }
]
});
executeScript(env.context);
assert.equal(env.sectionButtons[0].classList.contains('active'), true);
assert.equal(env.sectionButtons[0].attributes['aria-pressed'], 'true');
assert.equal(env.sectionPanels[0].hidden, false);
assert.equal(env.sectionButtons[1].classList.contains('active'), false);
assert.equal(env.sectionPanels[1].hidden, true);
});
test('点击 section 按钮时,激活态和可见面板同步切换', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', active: true, hidden: false },
{ target: 'section-mcp', hidden: true }
]
});
executeScript(env.context);
env.sectionButtons[1].click();
assert.equal(env.sectionButtons[0].classList.contains('active'), false);
assert.equal(env.sectionButtons[0].attributes['aria-pressed'], 'false');
assert.equal(env.sectionPanels[0].hidden, true);
assert.equal(env.sectionButtons[1].classList.contains('active'), true);
assert.equal(env.sectionButtons[1].attributes['aria-pressed'], 'true');
assert.equal(env.sectionPanels[1].hidden, false);
assert.equal(env.window.location.hash, '#section-mcp');
assert.deepEqual(env.historyCalls, ['#section-mcp']);
assert.equal(env.getHashchangeCount(), 0);
});
test('点击 section 按钮时,会把激活面板顶部对齐到左侧导航顶部', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', active: true, hidden: false },
{ target: 'section-cli', hidden: true }
],
sidebarTop: 80,
panelTop: 164
});
executeScript(env.context);
env.sectionButtons[1].click();
assert.equal(env.scrollByCalls.length, 1);
assert.equal(env.scrollByCalls[0].top, 84);
assert.equal(env.scrollByCalls[0].left, 0);
assert.equal(env.scrollByCalls[0].behavior, 'auto');
});
test('重复点击当前激活 section 时,不应继续滚动页面', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', active: true, hidden: false },
{ target: 'section-cli', hidden: true }
],
sidebarTop: 80,
panelTop: 164
});
executeScript(env.context);
env.sectionButtons[0].click();
assert.equal(env.sectionButtons[0].classList.contains('active'), true);
assert.equal(env.sectionPanels[0].hidden, false);
assert.deepEqual(env.scrollByCalls, []);
});
test('手机端顶部导航与正文同列时,切换 section 不应触发对齐滚动', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', active: true, hidden: false },
{ target: 'section-cli', hidden: true }
],
sidebarTop: 360,
sidebarLeft: 0,
sidebarWidth: 390,
panelTop: 430,
panelLeft: 0,
panelWidth: 390
});
executeScript(env.context);
env.sectionButtons[1].click();
assert.equal(env.sectionButtons[1].classList.contains('active'), true);
assert.equal(env.sectionPanels[1].hidden, false);
assert.deepEqual(env.scrollByCalls, []);
});
test('初始 hash 指向 group 时,会激活其父 section', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', hidden: true },
{ target: 'section-mcp', active: true, hidden: false }
],
initialHash: '#section-keyboard-group-general-controls'
});
executeScript(env.context);
assert.equal(env.groupHeading.closest('[data-section-panel]'), env.sectionPanels[0]);
assert.equal(env.sectionButtons[0].classList.contains('active'), true);
assert.equal(env.sectionButtons[0].attributes['aria-pressed'], 'true');
assert.equal(env.sectionPanels[0].hidden, false);
assert.equal(env.sectionButtons[1].classList.contains('active'), false);
assert.equal(env.sectionPanels[1].hidden, true);
});
test('section 切换应按 data-section-panel 选中面板而不是标题 id', () => {
const env = createEnvironment({
sections: [
{ target: 'section-keyboard', hidden: true },
{ target: 'section-mcp', hidden: true }
]
});
executeScript(env.context);
assert.equal(env.document.getElementById('section-keyboard'), env.sectionHeadings[0]);
assert.notEqual(env.document.getElementById('section-keyboard'), env.sectionPanels[0]);
env.sectionButtons[0].click();
assert.equal(env.sectionPanels[0].hidden, false);
assert.equal(env.sectionButtons[0].classList.contains('active'), true);
assert.equal(env.sectionButtons[0].attributes['aria-pressed'], 'true');
assert.equal(env.window.location.hash, '#section-keyboard');
});
test('点击 changelog trigger 后会展开,再点一次会收起', () => {
const env = createEnvironment();
executeScript(env.context);
env.changelogTrigger.click();
assert.equal(env.changelog.hidden, false);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'true');
env.changelogTrigger.click();
assert.equal(env.changelog.hidden, true);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'false');
});
test('按 Esc 或点击外部时会关闭 changelog', () => {
const env = createEnvironment();
executeScript(env.context);
env.changelogTrigger.click();
assert.equal(env.changelog.hidden, false);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'true');
env.document.dispatchEvent(createEvent('keydown', { key: 'Escape', target: env.document.body }));
assert.equal(env.changelog.hidden, true);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'false');
env.changelogTrigger.click();
assert.equal(env.changelog.hidden, false);
env.document.dispatchEvent(createEvent('click', { target: env.outsideClickTarget }));
assert.equal(env.changelog.hidden, true);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'false');
});
test('点击 changelog 面板内部元素时不会关闭,点击外部才关闭', () => {
const env = createEnvironment();
executeScript(env.context);
env.changelogTrigger.click();
assert.equal(env.changelog.hidden, false);
env.changelogPanelInner.click();
assert.equal(env.changelog.hidden, false);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'true');
env.outsideClickTarget.click();
assert.equal(env.changelog.hidden, true);
assert.equal(env.changelogTrigger.attributes['aria-expanded'], 'false');
});
test('脚本初始化不会再写入 cc-density', () => {
const env = createEnvironment();
executeScript(env.context);
assert.equal(env.localStorage.getItem('cc-density'), null);
});
test('脚本初始化会通过 CounterAPI 增加并展示本站访问量', async () => {
const env = createEnvironment();
const calls = [];
env.context.Counter = class Counter {
constructor(config) {
calls.push({ type: 'constructor', config });
}
async up(name) {
calls.push({ type: 'up', name });
return { count: 12345 };
}
};
executeScript(env.context);
await Promise.resolve();
assert.deepEqual(JSON.parse(JSON.stringify(calls)), [
{ type: 'constructor', config: { namespace: 'cc-quick', version: 'v1' } },
{ type: 'up', name: 'site-visits' }
]);
assert.equal(env.visitCount.textContent, '12,345');
assert.equal(env.visitCount.attributes['data-counter-state'], 'ready');
});
test('访问量会优先展示缓存并每 15 秒只读刷新', async () => {
const env = createEnvironment({
storage: {
'cc-quick:siteVisitCount': '120'
}
});
const calls = [];
const intervals = [];
env.window.setInterval = (fn, delay) => {
intervals.push({ fn, delay });
return intervals.length;
};
env.context.setInterval = env.window.setInterval;
env.context.Counter = class Counter {
async up(name) {
calls.push({ type: 'up', name });
return { count: 121 };
}
async get(name) {
calls.push({ type: 'get', name });
return { count: 130 };
}
};
executeScript(env.context);
assert.equal(env.visitCount.textContent, '120');
assert.equal(env.visitCount.attributes['data-counter-state'], 'ready');
assert.equal(intervals[0].delay, 15000);
await Promise.resolve();
assert.equal(env.visitCount.textContent, '121');
await intervals[0].fn();
assert.deepEqual(calls, [
{ type: 'up', name: 'site-visits' },
{ type: 'get', name: 'site-visits' }
]);
assert.equal(env.visitCount.textContent, '130');
assert.equal(env.localStorage.getItem('cc-quick:siteVisitCount'), '130');
});
test('访问量自动刷新失败时保留已有数字', async () => {
const env = createEnvironment({
storage: {
'cc-quick:siteVisitCount': '120'
}
});
const intervals = [];
env.window.setInterval = (fn, delay) => {
intervals.push({ fn, delay });
return intervals.length;
};
env.context.setInterval = env.window.setInterval;
env.context.Counter = class Counter {
async up() {
return { count: 121 };
}
async get() {
throw new Error('network failed');
}
};
executeScript(env.context);
await Promise.resolve();
await intervals[0].fn();
assert.equal(env.visitCount.textContent, '121');
assert.equal(env.visitCount.attributes['data-counter-state'], 'ready');
});
test('CounterAPI 不可用时访问量展示为暂不可用', async () => {
const env = createEnvironment();
env.context.Counter = class Counter {
async up() {
throw new Error('network failed');
}
};
executeScript(env.context);
await Promise.resolve();
await Promise.resolve();
assert.equal(env.visitCount.textContent, '暂不可用');
assert.equal(env.visitCount.attributes['data-counter-state'], 'error');
});