-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathtest.js
More file actions
1092 lines (884 loc) · 49.6 KB
/
test.js
File metadata and controls
1092 lines (884 loc) · 49.6 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
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* Air Quality Card v2.6.0 — Unit Tests
* Run with: node test.js
*
* Tests color functions, recommendation waterfall, config validation,
* and overall status logic by extracting methods from the card class.
*/
let passed = 0;
let failed = 0;
function assert(condition, message) {
if (condition) {
passed++;
} else {
failed++;
console.error(` FAIL: ${message}`);
}
}
function section(name) {
console.log(`\n--- ${name} ---`);
}
// ============================================================
// Extract the class methods by evaluating in a mock DOM context
// ============================================================
// Minimal mock for HTMLElement and customElements
class MockHTMLElement {
constructor() { this._shadowRoot = {}; }
attachShadow() { return {}; }
dispatchEvent() {}
}
// Mock LitElement base for the editor
class MockLitElementBase {
static get properties() { return {}; }
static get styles() { return ''; }
render() { return ''; }
}
MockLitElementBase.prototype.html = (strings, ...values) => strings.join('');
MockLitElementBase.prototype.css = (strings, ...values) => strings.join('');
class MockHuiView extends MockLitElementBase {}
const registeredElements = {};
const mockCustomElements = {
define(name, cls) { registeredElements[name] = cls; },
get(name) {
if (name === 'hui-masonry-view' || name === 'hui-view') return MockHuiView;
return registeredElements[name];
}
};
// Patch globals
global.HTMLElement = MockHTMLElement;
global.customElements = mockCustomElements;
global.window = { customCards: [] };
global.document = { createElement: () => ({}) };
global.CustomEvent = class CustomEvent {};
global.console = { ...console, info: () => {} }; // suppress banner
// Load the card
require('./air-quality-card.js');
const CardClass = registeredElements['air-quality-card'];
if (!CardClass) {
console.error('FATAL: AirQualityCard class not registered');
process.exit(1);
}
// Create instance with mock hass for method testing
const card = new CardClass();
card._hass = {
config: { unit_system: { temperature: '°F' } },
states: {},
callApi: async () => []
};
card._config = {
name: 'Test',
hours_to_show: 24,
temperature_unit: 'auto'
};
// ============================================================
// COLOR FUNCTION TESTS
// ============================================================
section('CO2 Color');
assert(card._getCO2Color(400) === '#4caf50', 'CO2 400 = green');
assert(card._getCO2Color(700) === '#8bc34a', 'CO2 700 = light green');
assert(card._getCO2Color(900) === '#ffc107', 'CO2 900 = yellow');
assert(card._getCO2Color(1200) === '#ff9800', 'CO2 1200 = orange');
assert(card._getCO2Color(2000) === '#f44336', 'CO2 2000 = red');
section('PM2.5 Color');
assert(card._getPM25Color(3) === '#4caf50', 'PM25 3 = green');
assert(card._getPM25Color(10) === '#8bc34a', 'PM25 10 = light green');
assert(card._getPM25Color(20) === '#ffc107', 'PM25 20 = yellow');
assert(card._getPM25Color(30) === '#ff9800', 'PM25 30 = orange');
assert(card._getPM25Color(50) === '#f44336', 'PM25 50 = red');
section('PM1 Color');
assert(card._getPM1Color(3) === '#4caf50', 'PM1 3 = green');
assert(card._getPM1Color(10) === '#8bc34a', 'PM1 10 = light green');
assert(card._getPM1Color(20) === '#ffc107', 'PM1 20 = yellow');
assert(card._getPM1Color(30) === '#ff9800', 'PM1 30 = orange');
assert(card._getPM1Color(40) === '#f44336', 'PM1 40 = red');
section('PM10 Color');
assert(card._getPM10Color(10) === '#4caf50', 'PM10 10 = green');
assert(card._getPM10Color(30) === '#8bc34a', 'PM10 30 = light green');
assert(card._getPM10Color(60) === '#ffc107', 'PM10 60 = yellow');
assert(card._getPM10Color(100) === '#ff9800', 'PM10 100 = orange');
assert(card._getPM10Color(200) === '#f44336', 'PM10 200 = red');
section('PM0.3 Color');
assert(card._getPM03Color(200) === '#4caf50', 'PM03 200 = green');
assert(card._getPM03Color(800) === '#8bc34a', 'PM03 800 = light green');
assert(card._getPM03Color(2000) === '#ffc107', 'PM03 2000 = yellow');
assert(card._getPM03Color(4000) === '#ff9800', 'PM03 4000 = orange');
assert(card._getPM03Color(6000) === '#f44336', 'PM03 6000 = red');
section('CO Color');
assert(card._getCOColor(2) === '#4caf50', 'CO 2 = green');
assert(card._getCOColor(6) === '#8bc34a', 'CO 6 = light green');
assert(card._getCOColor(20) === '#ffc107', 'CO 20 = yellow');
assert(card._getCOColor(50) === '#ff9800', 'CO 50 = orange');
assert(card._getCOColor(150) === '#f44336', 'CO 150 = red');
section('Radon Color (Bq/m³)');
assert(card._getRadonColor(30) === '#4caf50', 'Radon 30 Bq = green');
assert(card._getRadonColor(80) === '#8bc34a', 'Radon 80 Bq = light green');
assert(card._getRadonColor(120) === '#ffc107', 'Radon 120 Bq = yellow');
assert(card._getRadonColor(200) === '#ff9800', 'Radon 200 Bq = orange');
assert(card._getRadonColor(400) === '#f44336', 'Radon 400 Bq = red');
section('HCHO Color');
assert(card._getHCHOColor(10) === '#4caf50', 'HCHO 10 = green');
assert(card._getHCHOColor(30) === '#8bc34a', 'HCHO 30 = light green');
assert(card._getHCHOColor(80) === '#ffc107', 'HCHO 80 = yellow');
assert(card._getHCHOColor(150) === '#ff9800', 'HCHO 150 = orange');
assert(card._getHCHOColor(300) === '#f44336', 'HCHO 300 = red');
section('tVOC Color');
assert(card._getTVOCColor(50) === '#4caf50', 'tVOC 50 = green');
assert(card._getTVOCColor(200) === '#8bc34a', 'tVOC 200 = light green');
assert(card._getTVOCColor(400) === '#ffc107', 'tVOC 400 = yellow');
assert(card._getTVOCColor(800) === '#ff9800', 'tVOC 800 = orange');
assert(card._getTVOCColor(1500) === '#f44336', 'tVOC 1500 = red');
section('Humidity Color');
assert(card._getHumidityColor(20) === '#ff9800', 'Humidity 20 = orange (too dry)');
assert(card._getHumidityColor(35) === '#8bc34a', 'Humidity 35 = light green');
assert(card._getHumidityColor(45) === '#4caf50', 'Humidity 45 = green (ideal)');
assert(card._getHumidityColor(55) === '#8bc34a', 'Humidity 55 = light green');
assert(card._getHumidityColor(70) === '#ff9800', 'Humidity 70 = orange (too humid)');
section('Temperature Color (Fahrenheit)');
card._config.temperature_unit = 'F';
assert(card._getTempColor(60) === '#2196f3', 'Temp 60F = blue');
assert(card._getTempColor(66) === '#03a9f4', 'Temp 66F = light blue');
assert(card._getTempColor(70) === '#4caf50', 'Temp 70F = green');
assert(card._getTempColor(74) === '#ff9800', 'Temp 74F = orange');
assert(card._getTempColor(80) === '#f44336', 'Temp 80F = red');
section('Temperature Color (Celsius)');
card._config.temperature_unit = 'C';
assert(card._getTempColor(15) === '#2196f3', 'Temp 15C = blue');
assert(card._getTempColor(19) === '#03a9f4', 'Temp 19C = light blue');
assert(card._getTempColor(21) === '#4caf50', 'Temp 21C = green');
assert(card._getTempColor(23) === '#ff9800', 'Temp 23C = orange');
assert(card._getTempColor(28) === '#f44336', 'Temp 28C = red');
// ============================================================
// RECOMMENDATION WATERFALL TESTS
// ============================================================
// Helper to set up hass states for recommendation testing
function setStates(states) {
card._hass.states = {};
card._config = {
name: 'Test',
hours_to_show: 24,
temperature_unit: 'auto'
};
for (const [key, value] of Object.entries(states)) {
const entityId = `sensor.${key}`;
card._config[`${key}_entity`] = entityId;
card._hass.states[entityId] = { state: String(value) };
}
}
section('Recommendation — CO Safety (highest priority)');
setStates({ co: 150, co2: 2000, pm25: 50 });
assert(card._getRecommendation() === 'CO Danger — Leave Area', 'CO > 100 = CO Danger even with high CO2/PM25');
setStates({ co: 50, co2: 2000 });
assert(card._getRecommendation() === 'CO Warning — Ventilate Now', 'CO > 35 = CO Warning');
setStates({ co: 15 });
assert(card._getRecommendation() === 'CO Elevated — Ventilate', 'CO > 9 = CO Elevated');
setStates({ co: 3 });
assert(card._getRecommendation() === 'All Good', 'CO 3 = All Good');
section('Recommendation — CO not suppressed by outdoor override');
setStates({ co: 150 });
card._config.outdoor_co2_entity = 'sensor.outdoor_co2';
card._config.outdoor_pm25_entity = 'sensor.outdoor_pm25';
card._hass.states['sensor.outdoor_co2'] = { state: '5000' };
card._hass.states['sensor.outdoor_pm25'] = { state: '100' };
assert(card._getRecommendation() === 'CO Danger — Leave Area', 'CO Danger not suppressed by outdoor override');
section('Recommendation — Standard waterfall');
setStates({ co2: 1800 });
assert(card._getRecommendation() === 'Ventilate Now', 'CO2 1800 = Ventilate Now');
setStates({ pm25: 40 });
assert(card._getRecommendation() === 'Run Air Purifier', 'PM25 40 = Run Air Purifier');
setStates({ pm10: 160 });
assert(card._getRecommendation() === 'Run Air Purifier', 'PM10 160 = Run Air Purifier');
setStates({ hcho: 150 });
assert(card._getRecommendation() === 'Ventilate — Formaldehyde', 'HCHO 150 = Ventilate Formaldehyde');
setStates({ tvoc: 600 });
assert(card._getRecommendation() === 'Ventilate — VOCs Elevated', 'tVOC 600 = Ventilate VOCs');
setStates({ pm25: 30, co2: 1100 });
assert(card._getRecommendation() === 'Air Purifier + Ventilate', 'PM25 30 + CO2 1100 = combo');
setStates({ pm25: 30 });
assert(card._getRecommendation() === 'Run Air Purifier', 'PM25 30 alone = Run Air Purifier');
setStates({ pm10: 100 });
assert(card._getRecommendation() === 'Consider Air Purifier', 'PM10 100 = Consider Air Purifier');
setStates({ co2: 1100 });
assert(card._getRecommendation() === 'Open Window', 'CO2 1100 = Open Window');
setStates({ humidity: 25 });
assert(card._getRecommendation() === 'Too Dry', 'Humidity 25 = Too Dry');
setStates({ humidity: 70 });
assert(card._getRecommendation() === 'Too Humid', 'Humidity 70 = Too Humid');
setStates({ co2: 850 });
assert(card._getRecommendation() === 'Consider Ventilating', 'CO2 850 = Consider Ventilating');
setStates({ pm25: 20 });
assert(card._getRecommendation() === 'Consider Ventilating', 'PM25 20 = Consider Ventilating');
setStates({ co2: 400, pm25: 3 });
assert(card._getRecommendation() === 'All Good', 'Low CO2 + PM25 = All Good');
section('Recommendation — Outdoor override');
setStates({ co2: 1100 });
card._config.outdoor_co2_entity = 'sensor.outdoor_co2';
card._hass.states['sensor.outdoor_co2'] = { state: '1500' };
assert(card._getRecommendation() === 'Keep Windows Closed', 'Open Window suppressed when outdoor CO2 worse');
setStates({ pm25: 30, co2: 1100 });
card._config.outdoor_pm25_entity = 'sensor.outdoor_pm25';
card._hass.states['sensor.outdoor_pm25'] = { state: '50' };
assert(card._getRecommendation() === 'Run Air Purifier', 'Combo rec falls back to purifier when outdoor worse');
// ============================================================
// RECOMMENDATION ICON TESTS
// ============================================================
section('Recommendation Icons');
assert(card._getRecommendationIcon('All Good') === 'mdi:check-circle', 'All Good icon');
assert(card._getRecommendationIcon('CO Danger — Leave Area') === 'mdi:alert-octagon', 'CO Danger icon');
assert(card._getRecommendationIcon('CO Warning — Ventilate Now') === 'mdi:alert-octagon', 'CO Warning icon');
assert(card._getRecommendationIcon('CO Elevated — Ventilate') === 'mdi:alert', 'CO Elevated icon');
assert(card._getRecommendationIcon('Consider Air Purifier') === 'mdi:air-purifier', 'Consider Air Purifier icon');
assert(card._getRecommendationIcon('Run Air Purifier') === 'mdi:air-purifier', 'Run Air Purifier icon');
assert(card._getRecommendationIcon('Open Window') === 'mdi:window-open-variant', 'Open Window icon');
assert(card._getRecommendationIcon('Keep Windows Closed') === 'mdi:window-closed-variant', 'Keep Windows Closed icon');
// ============================================================
// CONFIG VALIDATION TESTS
// ============================================================
section('Config Validation');
// Should throw with no entities
let threw = false;
try { card.setConfig({}); } catch (e) { threw = true; }
assert(threw, 'Empty config throws');
// Should accept any single sensor
const singleSensorConfigs = [
'co2_entity', 'pm25_entity', 'pm1_entity', 'pm10_entity', 'pm03_entity',
'hcho_entity', 'tvoc_entity', 'co_entity', 'radon_entity', 'humidity_entity', 'temperature_entity'
];
for (const key of singleSensorConfigs) {
let ok = true;
try { card.setConfig({ [key]: 'sensor.test' }); } catch (e) { ok = false; }
assert(ok, `Single ${key} accepted`);
}
// Defaults
card.setConfig({ co2_entity: 'sensor.co2' });
assert(card._config.name === 'Air Quality', 'Default name');
assert(card._config.hours_to_show === 24, 'Default hours_to_show');
assert(card._config.temperature_unit === 'auto', 'Default temperature_unit is auto');
assert(card._config.radon_unit === 'auto', 'Default radon_unit is auto');
// ============================================================
// OVERALL STATUS TESTS
// ============================================================
section('Overall Status');
setStates({ co: 50 });
assert(card._getOverallStatus().status === 'Dangerous', 'CO 50 = Dangerous');
assert(card._getOverallStatus().color === '#d32f2f', 'CO 50 = dark red');
setStates({ co: 15 });
assert(card._getOverallStatus().status === 'Poor', 'CO 15 = Poor');
setStates({ co2: 2000 });
assert(card._getOverallStatus().status === 'Poor', 'CO2 2000 = Poor');
setStates({ co2: 1200 });
assert(card._getOverallStatus().status === 'Fair', 'CO2 1200 = Fair');
setStates({ co2: 900 });
assert(card._getOverallStatus().status === 'Moderate', 'CO2 900 = Moderate');
setStates({ co2: 700 });
assert(card._getOverallStatus().status === 'Good', 'CO2 700 = Good');
setStates({ co2: 400 });
assert(card._getOverallStatus().status === 'Excellent', 'CO2 400 = Excellent');
// ============================================================
// TEMPERATURE UNIT DETECTION
// ============================================================
section('Temperature Unit Detection');
card._config.temperature_unit = 'auto';
card._hass.config.unit_system.temperature = '°C';
assert(card._isCelsius() === true, 'Auto detects Celsius');
assert(card._getTempUnit() === '°C', 'Auto returns °C');
card._hass.config.unit_system.temperature = '°F';
assert(card._isCelsius() === false, 'Auto detects Fahrenheit');
assert(card._getTempUnit() === '°F', 'Auto returns °F');
card._config.temperature_unit = 'C';
assert(card._isCelsius() === true, 'Explicit C override');
card._config.temperature_unit = 'F';
assert(card._isCelsius() === false, 'Explicit F override');
// ============================================================
// RADON UNIT DETECTION
// ============================================================
section('Radon Unit Detection');
card._config.radon_unit = 'auto';
card._config.radon_entity = 'sensor.radon';
card._hass.states['sensor.radon'] = { state: '2.0', attributes: { unit_of_measurement: 'pCi/L' } };
assert(card._getRadonUnit() === 'pCi/L', 'Auto detects pCi/L from entity');
assert(card._isRadonPciL() === true, 'isRadonPciL true for pCi');
assert(card._getRadonBqm3(2.0) === 74, 'pCi/L to Bq/m³ conversion (2.0 * 37 = 74)');
card._hass.states['sensor.radon'] = { state: '100', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonUnit() === 'Bq/m³', 'Auto detects Bq/m³ from entity');
card._config.radon_unit = 'Bq/m³';
assert(card._getRadonUnit() === 'Bq/m³', 'Explicit Bq/m³ override');
assert(card._getRadonBqm3(100) === 100, 'Bq/m³ passthrough');
card._config.radon_unit = 'pCi/L';
assert(card._getRadonUnit() === 'pCi/L', 'Explicit pCi/L override');
// ============================================================
// RADON ADVISORY TESTS
// ============================================================
section('Radon Advisory');
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto', radon_unit: 'Bq/m³', radon_entity: 'sensor.radon' };
card._hass.states['sensor.radon'] = { state: '350', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'danger', 'Radon 350 Bq = danger advisory');
card._hass.states['sensor.radon'] = { state: '200', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'warning', 'Radon 200 Bq = warning advisory');
card._hass.states['sensor.radon'] = { state: '110', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'info', 'Radon 110 Bq = info advisory');
card._hass.states['sensor.radon'] = { state: '40', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory() === null, 'Radon 40 Bq = no advisory');
// ============================================================
// RADON DOES NOT AFFECT RECOMMENDATIONS
// ============================================================
section('Radon does NOT affect recommendations');
setStates({ co2: 400 });
card._config.radon_entity = 'sensor.radon';
card._config.radon_unit = 'Bq/m³';
card._hass.states['sensor.radon'] = { state: '400', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRecommendation() === 'All Good', 'High radon does not change recommendation');
// ============================================================
// RADON OVERALL STATUS
// ============================================================
section('Radon Overall Status');
setStates({});
card._config.radon_entity = 'sensor.radon';
card._config.radon_unit = 'Bq/m³';
card._hass.states['sensor.radon'] = { state: '300', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Poor', 'Radon 300 Bq = Poor status');
card._hass.states['sensor.radon'] = { state: '150', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Fair', 'Radon 150 Bq = Fair status');
card._hass.states['sensor.radon'] = { state: '50', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Excellent', 'Radon 50 Bq does not degrade status');
// ============================================================
// RADON LONGTERM TESTS
// ============================================================
section('Radon Long-Term Advisory');
// Advisory uses higher of short-term and long-term
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto', radon_unit: 'Bq/m³', radon_entity: 'sensor.radon', radon_longterm_entity: 'sensor.radon_lt' };
card._hass.states['sensor.radon'] = { state: '50', attributes: { unit_of_measurement: 'Bq/m³' } };
card._hass.states['sensor.radon_lt'] = { state: '200', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'warning', 'Advisory uses longterm when higher (200 Bq LT = warning)');
card._hass.states['sensor.radon'] = { state: '350', attributes: { unit_of_measurement: 'Bq/m³' } };
card._hass.states['sensor.radon_lt'] = { state: '50', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'danger', 'Advisory uses short-term when higher (350 Bq ST = danger)');
// Advisory works with only longterm configured
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto', radon_unit: 'Bq/m³', radon_longterm_entity: 'sensor.radon_lt' };
card._hass.states['sensor.radon_lt'] = { state: '200', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory().level === 'warning', 'Advisory works with only longterm entity (200 Bq = warning)');
card._hass.states['sensor.radon_lt'] = { state: '40', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getRadonAdvisory() === null, 'No advisory when longterm is low');
// Advisory subtitle shows both values when both configured
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto', radon_unit: 'Bq/m³', radon_entity: 'sensor.radon', radon_longterm_entity: 'sensor.radon_lt' };
card._hass.states['sensor.radon'] = { state: '120', attributes: { unit_of_measurement: 'Bq/m³' } };
card._hass.states['sensor.radon_lt'] = { state: '110', attributes: { unit_of_measurement: 'Bq/m³' } };
const advisory = card._getRadonAdvisory();
assert(advisory && advisory.subtitle.includes('Short-term') && advisory.subtitle.includes('Long-term'), 'Advisory subtitle shows both values when both configured');
section('Radon Long-Term Overall Status');
// Overall status uses higher of short-term and long-term
setStates({});
card._config.radon_entity = 'sensor.radon';
card._config.radon_longterm_entity = 'sensor.radon_lt';
card._config.radon_unit = 'Bq/m³';
card._hass.states['sensor.radon'] = { state: '50', attributes: { unit_of_measurement: 'Bq/m³' } };
card._hass.states['sensor.radon_lt'] = { state: '300', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Poor', 'Overall status uses longterm when higher (300 Bq LT = Poor)');
card._hass.states['sensor.radon'] = { state: '150', attributes: { unit_of_measurement: 'Bq/m³' } };
card._hass.states['sensor.radon_lt'] = { state: '50', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Fair', 'Overall status uses short-term when higher (150 Bq ST = Fair)');
// Works with only longterm
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto', radon_unit: 'Bq/m³', radon_longterm_entity: 'sensor.radon_lt' };
card._hass.states['sensor.radon_lt'] = { state: '300', attributes: { unit_of_measurement: 'Bq/m³' } };
assert(card._getOverallStatus().status === 'Poor', 'Overall status works with only longterm (300 Bq = Poor)');
section('Radon Long-Term Config Validation');
// radon_longterm_entity alone should be valid config
let configValid = true;
try {
card.setConfig({ radon_longterm_entity: 'sensor.radon_lt' });
} catch (e) {
configValid = false;
}
assert(configValid, 'radon_longterm_entity alone is valid config');
// ============================================================
// STATUS LABEL TESTS (must match color thresholds)
// ============================================================
section('CO2 Status Label');
assert(card._getCO2Status(400) === 'Excellent', 'CO2 400 = Excellent');
assert(card._getCO2Status(599) === 'Excellent', 'CO2 599 = Excellent');
assert(card._getCO2Status(600) === 'Good', 'CO2 600 = Good (boundary)');
assert(card._getCO2Status(700) === 'Good', 'CO2 700 = Good');
assert(card._getCO2Status(800) === 'Moderate', 'CO2 800 = Moderate (boundary, was missing tier)');
assert(card._getCO2Status(900) === 'Moderate', 'CO2 900 = Moderate (was incorrectly "Good")');
assert(card._getCO2Status(1000) === 'Elevated', 'CO2 1000 = Elevated (boundary)');
assert(card._getCO2Status(1200) === 'Elevated', 'CO2 1200 = Elevated');
assert(card._getCO2Status(1500) === 'Poor', 'CO2 1500 = Poor (boundary)');
assert(card._getCO2Status(2000) === 'Poor', 'CO2 2000 = Poor');
section('Humidity Status Label');
assert(card._getHumidityStatus(20) === 'Too Dry', 'Humidity 20 = Too Dry');
assert(card._getHumidityStatus(30) === 'Dry', 'Humidity 30 = Dry (boundary)');
assert(card._getHumidityStatus(35) === 'Dry', 'Humidity 35 = Dry');
assert(card._getHumidityStatus(40) === 'Comfortable', 'Humidity 40 = Comfortable (boundary)');
assert(card._getHumidityStatus(45) === 'Comfortable', 'Humidity 45 = Comfortable');
assert(card._getHumidityStatus(50) === 'Humid', 'Humidity 50 = Humid (boundary fix)');
assert(card._getHumidityStatus(55) === 'Humid', 'Humidity 55 = Humid');
assert(card._getHumidityStatus(60) === 'Too Humid', 'Humidity 60 = Too Humid (boundary fix)');
assert(card._getHumidityStatus(70) === 'Too Humid', 'Humidity 70 = Too Humid');
section('Temperature Status Label (Celsius)');
card._config.temperature_unit = 'C';
assert(card._getTempStatus(15) === 'Cold', 'Temp 15C = Cold');
assert(card._getTempStatus(18) === 'Cool', 'Temp 18C = Cool (boundary)');
assert(card._getTempStatus(19) === 'Cool', 'Temp 19C = Cool');
assert(card._getTempStatus(20) === 'Comfortable', 'Temp 20C = Comfortable (boundary)');
assert(card._getTempStatus(21) === 'Comfortable', 'Temp 21C = Comfortable');
assert(card._getTempStatus(22) === 'Warm', 'Temp 22C = Warm (boundary fix)');
assert(card._getTempStatus(23) === 'Warm', 'Temp 23C = Warm');
assert(card._getTempStatus(24) === 'Hot', 'Temp 24C = Hot (boundary fix)');
assert(card._getTempStatus(28) === 'Hot', 'Temp 28C = Hot');
section('Temperature Status Label (Fahrenheit)');
card._config.temperature_unit = 'F';
assert(card._getTempStatus(60) === 'Cold', 'Temp 60F = Cold');
assert(card._getTempStatus(65) === 'Cool', 'Temp 65F = Cool (boundary)');
assert(card._getTempStatus(68) === 'Comfortable', 'Temp 68F = Comfortable (boundary)');
assert(card._getTempStatus(70) === 'Comfortable', 'Temp 70F = Comfortable');
assert(card._getTempStatus(72) === 'Warm', 'Temp 72F = Warm (boundary fix)');
assert(card._getTempStatus(74) === 'Warm', 'Temp 74F = Warm');
assert(card._getTempStatus(76) === 'Hot', 'Temp 76F = Hot (boundary fix)');
assert(card._getTempStatus(80) === 'Hot', 'Temp 80F = Hot');
card._config.temperature_unit = 'auto';
// ============================================================
// TIME-BASED GRAPH X COORDINATE TESTS (issue #22)
// ============================================================
section('Graph X by timestamp');
// Setup a 24-hour window: start = 0, end = 86400000
card._timeWindow = { start: 0, end: 86400000 };
const W = 300, P = 2;
assert(card._computeGraphX(0, W, P) === P, 'point at window start → x = padding');
assert(card._computeGraphX(86400000, W, P) === W - P, 'point at window end → x = width - padding');
assert(Math.abs(card._computeGraphX(43200000, W, P) - (W / 2)) < 0.001, 'point at midpoint → x ≈ width/2');
// Points outside the window get clamped (defensive: API can occasionally return slightly out-of-range data)
assert(card._computeGraphX(-1000, W, P) === P, 'point before start → clamped to padding');
assert(card._computeGraphX(86400000 + 1000, W, P) === W - P, 'point after end → clamped to width-padding');
// Unevenly sampled data: a spike at hour 4 of a 24h window must render at ~16.6% of width
// (the bug that #22 reported: previously it would render based on data index, not timestamp)
const fourHoursIn = 4 * 60 * 60 * 1000;
const expectedX = P + (fourHoursIn / 86400000) * (W - 2 * P);
assert(Math.abs(card._computeGraphX(fourHoursIn, W, P) - expectedX) < 0.001,
'4h-in spike renders at correct fractional X regardless of total data-point count');
// Defensive: zero-span window doesn't NaN
card._timeWindow = { start: 5000, end: 5000 };
assert(card._computeGraphX(5000, W, P) === P, 'zero-span window does not produce NaN');
// Defensive: missing time window doesn't crash
card._timeWindow = null;
assert(card._computeGraphX(12345, W, P) === P, 'missing time window returns padding instead of NaN');
card._timeWindow = undefined;
// ============================================================
// OUTDOOR-ONLY MODE TESTS
// ============================================================
section('Outdoor-Only Mode');
// Outdoor-only config is valid
let outdoorOnlyCard = new CardClass();
let outdoorOnlyValid = true;
try {
outdoorOnlyCard.setConfig({ outdoor_pm25_entity: 'sensor.outdoor_pm25' });
} catch (e) {
outdoorOnlyValid = false;
}
assert(outdoorOnlyValid, 'outdoor_pm25_entity alone is valid config');
assert(outdoorOnlyCard._outdoorOnly === true, '_outdoorOnly flag set when only outdoor entities configured');
assert(outdoorOnlyCard._config.pm25_entity === 'sensor.outdoor_pm25', 'outdoor_pm25_entity promoted to pm25_entity');
assert(outdoorOnlyCard._config.outdoor_pm25_entity === undefined, 'outdoor_pm25_entity removed after promotion');
// Multiple outdoor entities all promote
const multiOutdoor = new CardClass();
multiOutdoor.setConfig({
outdoor_co2_entity: 'sensor.out_co2',
outdoor_pm25_entity: 'sensor.out_pm25',
outdoor_temperature_entity: 'sensor.out_temp'
});
assert(multiOutdoor._outdoorOnly === true, 'multi-outdoor: _outdoorOnly true');
assert(multiOutdoor._config.co2_entity === 'sensor.out_co2', 'outdoor_co2_entity promoted');
assert(multiOutdoor._config.pm25_entity === 'sensor.out_pm25', 'outdoor_pm25_entity promoted');
assert(multiOutdoor._config.temperature_entity === 'sensor.out_temp', 'outdoor_temperature_entity promoted');
// Indoor + outdoor: no promotion, outdoor remains as overlay
const mixed = new CardClass();
mixed.setConfig({
pm25_entity: 'sensor.indoor_pm25',
outdoor_pm25_entity: 'sensor.outdoor_pm25'
});
assert(mixed._outdoorOnly === false, 'mixed indoor+outdoor: _outdoorOnly false');
assert(mixed._config.pm25_entity === 'sensor.indoor_pm25', 'mixed: indoor entity preserved');
assert(mixed._config.outdoor_pm25_entity === 'sensor.outdoor_pm25', 'mixed: outdoor stays for overlay');
// Empty config still throws
let emptyThrew = false;
try {
new CardClass().setConfig({});
} catch (e) {
emptyThrew = true;
}
assert(emptyThrew, 'empty config still throws');
// Recommendations suppressed in outdoor-only mode
const outdoorRec = new CardClass();
outdoorRec.setConfig({ outdoor_co2_entity: 'sensor.out_co2' });
outdoorRec._hass = card._hass;
outdoorRec._hass.states['sensor.out_co2'] = { state: '2000', attributes: {} }; // would normally trigger "Ventilate Now"
assert(outdoorRec._getRecommendation() === null, '_getRecommendation returns null in outdoor-only mode');
// Recommendations work normally with indoor entity
const indoorRec = new CardClass();
indoorRec.setConfig({ co2_entity: 'sensor.in_co2' });
indoorRec._hass = card._hass;
indoorRec._hass.states['sensor.in_co2'] = { state: '2000', attributes: {} };
assert(indoorRec._getRecommendation() === 'Ventilate Now', 'indoor mode: _getRecommendation works normally');
// Restore card._config for downstream tests
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto' };
card._outdoorOnly = false;
// ============================================================
// MIN/MAX HELPER TESTS (issue #23)
// ============================================================
section('Min/Max Helper');
assert(card._getMinMax(null) === null, 'null data → null');
assert(card._getMinMax([]) === null, 'empty array → null');
const sample = [
{ time: 1, value: 5 },
{ time: 2, value: 10 },
{ time: 3, value: 2 },
{ time: 4, value: 8 }
];
const mm = card._getMinMax(sample);
assert(mm && mm.min === 2, '_getMinMax min = 2');
assert(mm && mm.max === 10, '_getMinMax max = 10');
// Single-point edge case
const single = card._getMinMax([{ time: 1, value: 7 }]);
assert(single.min === 7 && single.max === 7, 'single point: min === max');
// All same values
const flat = card._getMinMax([{ time: 1, value: 4 }, { time: 2, value: 4 }, { time: 3, value: 4 }]);
assert(flat.min === 4 && flat.max === 4, 'flat data: min === max');
section('Graph value formatting');
assert(card._formatGraphValue(5.4, 'ppm') === 5, 'ppm rounds');
assert(card._formatGraphValue(5.4, 'ppb') === 5, 'ppb rounds');
assert(card._formatGraphValue(5.4, 'Bq/m³') === 5, 'Bq/m³ rounds');
assert(card._formatGraphValue(5.4, '°C') === 5, '°C rounds');
assert(card._formatGraphValue(5.45, 'pCi/L') === '5.5', 'pCi/L 1 decimal (rounded)');
assert(card._formatGraphValue(2.3, 'μg/m³') === '2.3', 'μg/m³ 1 decimal');
// Default config has show_min_max: false (opt-in)
const defaultCard = new CardClass();
defaultCard.setConfig({ co2_entity: 'sensor.co2' });
assert(defaultCard._config.show_min_max === false, 'show_min_max defaults to false');
// User can opt in
const minMaxCard = new CardClass();
minMaxCard.setConfig({ co2_entity: 'sensor.co2', show_min_max: true });
assert(minMaxCard._config.show_min_max === true, 'show_min_max can be enabled');
// ============================================================
// METRIC ORDERING (issue #19)
// ============================================================
section('Metric order — default');
const defaultOrderCard = new CardClass();
defaultOrderCard.setConfig({ co2_entity: 'sensor.co2' });
const defaultOrder = defaultOrderCard._getMetricOrder();
assert(defaultOrder[0] === 'co', 'default order: co first');
assert(defaultOrder[defaultOrder.length - 1] === 'temperature', 'default order: temperature last');
assert(defaultOrder.length === 13, 'default order: all 13 metrics');
section('Metric order — user override');
const reorderedCard = new CardClass();
reorderedCard.setConfig({
co2_entity: 'sensor.co2',
order: ['temperature', 'humidity', 'co2', 'pm10', 'pm25']
});
const reordered = reorderedCard._getMetricOrder();
assert(reordered[0] === 'temperature', 'user order: temperature first');
assert(reordered[1] === 'humidity', 'user order: humidity second');
assert(reordered[2] === 'co2', 'user order: co2 third');
assert(reordered[3] === 'pm10', 'user order: pm10 fourth');
assert(reordered[4] === 'pm25', 'user order: pm25 fifth');
// Unmentioned metrics get appended in default order — user never loses a sensor
assert(reordered.includes('radon'), 'unmentioned metrics still present');
assert(reordered.length === 13, 'user order: total still 13');
section('Metric order — invalid input');
const badOrderCard = new CardClass();
badOrderCard.setConfig({ co2_entity: 'sensor.co2', order: 'not an array' });
const fallback = badOrderCard._getMetricOrder();
assert(fallback[0] === 'co', 'non-array order falls back to defaults');
const partialBadCard = new CardClass();
partialBadCard.setConfig({
co2_entity: 'sensor.co2',
order: ['temperature', 'invalid_metric', 'co2']
});
const filtered = partialBadCard._getMetricOrder();
assert(filtered.indexOf('temperature') === 0, 'invalid metrics are dropped, valid ones preserved');
assert(filtered.indexOf('co2') === 1, 'invalid entries skipped in order');
assert(!filtered.includes('invalid_metric'), 'invalid metric never appears');
const emptyOrderCard = new CardClass();
emptyOrderCard.setConfig({ co2_entity: 'sensor.co2', order: [] });
assert(emptyOrderCard._getMetricOrder()[0] === 'co', 'empty array → default order');
// ============================================================
// COMPACT DISPLAY MODE (issue #20)
// ============================================================
section('Compact mode — config');
const compactCard = new CardClass();
compactCard.setConfig({ co2_entity: 'sensor.co2', display: 'compact' });
assert(compactCard._config.display === 'compact', 'display: compact accepted');
assert(compactCard._isCompact() === true, '_isCompact() true for compact display');
const fullCard = new CardClass();
fullCard.setConfig({ co2_entity: 'sensor.co2' });
assert(fullCard._config.display === 'full', 'display defaults to full');
assert(fullCard._isCompact() === false, '_isCompact() false for default display');
// Card size: compact should be smaller
assert(compactCard.getCardSize() === 1, 'compact getCardSize = 1');
assert(fullCard.getCardSize() >= 3, 'full getCardSize ≥ 3');
section('Compact mode — tap actions');
// _fireAction is a no-op when the corresponding action isn't configured
const noAction = new CardClass();
noAction.setConfig({ co2_entity: 'sensor.co2', display: 'compact' });
let dispatched = null;
noAction.dispatchEvent = (event) => { dispatched = event; };
noAction._fireAction('tap');
assert(dispatched === null, 'no tap_action configured → no event dispatched');
// When tap_action IS configured, hass-action event is dispatched with the right detail
const withTap = new CardClass();
withTap.setConfig({
co2_entity: 'sensor.co2',
display: 'compact',
tap_action: { action: 'navigate', navigation_path: '/lovelace/air-quality' }
});
let captured = null;
withTap.dispatchEvent = (event) => { captured = event; };
withTap._fireAction('tap');
// Note: in node's mocked CustomEvent, we don't get the full event API, but we can
// verify _fireAction's dispatch logic was reached by side-effect (captured set).
assert(captured !== null, 'tap_action configured → event dispatched');
// hold_action and double_tap_action also work
const withHold = new CardClass();
withHold.setConfig({
co2_entity: 'sensor.co2',
display: 'compact',
hold_action: { action: 'more-info' }
});
let held = null;
withHold.dispatchEvent = (event) => { held = event; };
withHold._fireAction('hold');
assert(held !== null, 'hold_action configured → event dispatched');
// _fireAction does nothing if the specific action isn't configured (tap_action set, hold_action not)
const onlyTap = new CardClass();
onlyTap.setConfig({
co2_entity: 'sensor.co2',
display: 'compact',
tap_action: { action: 'more-info' }
});
let unwanted = null;
onlyTap.dispatchEvent = (event) => { unwanted = event; };
onlyTap._fireAction('hold');
assert(unwanted === null, 'tap_action set but hold_action absent → no hold event');
// ============================================================
// CUSTOM THRESHOLDS (issues #21 / #24)
// ============================================================
section('Custom Thresholds — CO2');
const co2Custom = new CardClass();
co2Custom.setConfig({ co2_entity: 'sensor.co2', co2_thresholds: [500, 700, 900, 1200] });
assert(co2Custom._getCO2Color(450) === '#4caf50', 'custom CO2: 450 < 500 → green');
assert(co2Custom._getCO2Color(550) === '#8bc34a', 'custom CO2: 550 < 700 → light green');
assert(co2Custom._getCO2Color(800) === '#ffc107', 'custom CO2: 800 < 900 → yellow');
assert(co2Custom._getCO2Color(1000) === '#ff9800', 'custom CO2: 1000 < 1200 → orange');
assert(co2Custom._getCO2Color(1500) === '#f44336', 'custom CO2: 1500 → red');
assert(co2Custom._getMetricStatus('co2', 800) === 'Moderate', 'custom CO2 status follows custom thresholds');
// Original defaults still work for cards without override
const co2Default = new CardClass();
co2Default.setConfig({ co2_entity: 'sensor.co2' });
assert(co2Default._getCO2Color(700) === '#8bc34a', 'unchanged default behavior (CO2 700 = light green)');
assert(co2Default._getCO2Color(900) === '#ffc107', 'unchanged default behavior (CO2 900 = yellow)');
section('Custom Thresholds — Temperature (Brad in Thailand)');
const tempThai = new CardClass();
// Brad keeps AC at 26-29 °C; with custom thresholds, 28 °C reads as Comfortable, not Hot
tempThai.setConfig({ temperature_entity: 'sensor.t', temperature_unit: 'C', temperature_thresholds: [22, 25, 28, 31] });
assert(tempThai._getTempColor(20) === '#2196f3', 'Thai temp 20°C = blue (Cold)');
assert(tempThai._getTempColor(26) === '#4caf50', 'Thai temp 26°C = green (Comfortable)');
assert(tempThai._getTempColor(28) === '#ff9800', 'Thai temp 28°C = orange (Warm)');
assert(tempThai._getTempColor(32) === '#f44336', 'Thai temp 32°C = red (Hot)');
assert(tempThai._getMetricStatus('temp_c', 28) === 'Warm', 'Thai temp 28°C status = Warm');
section('Custom Thresholds — Humidity');
const humidCustom = new CardClass();
humidCustom.setConfig({ humidity_entity: 'sensor.h', humidity_thresholds: [25, 35, 55, 65] });
assert(humidCustom._getHumidityColor(20) === '#ff9800', 'custom humidity 20 = too dry');
assert(humidCustom._getHumidityColor(30) === '#8bc34a', 'custom humidity 30 = dry');
assert(humidCustom._getHumidityColor(45) === '#4caf50', 'custom humidity 45 = comfortable');
assert(humidCustom._getHumidityColor(60) === '#8bc34a', 'custom humidity 60 = humid');
assert(humidCustom._getHumidityColor(70) === '#ff9800', 'custom humidity 70 = too humid');
section('Custom Thresholds — PM2.5 (single override)');
const pmCustom = new CardClass();
pmCustom.setConfig({ pm25_entity: 'sensor.pm25', pm25_thresholds: [3, 8, 15, 25] });
assert(pmCustom._getPM25Color(2) === '#4caf50', 'custom PM2.5 2 = green');
assert(pmCustom._getPM25Color(20) === '#ff9800', 'custom PM2.5 20 = orange');
// Other metrics still use defaults
assert(pmCustom._getCO2Color(700) === '#8bc34a', 'PM override does not affect CO2 defaults');
section('Custom Thresholds — Validation (invalid input falls back to defaults)');
const invalidCard = new CardClass();
invalidCard.setConfig({ co2_entity: 'sensor.co2', co2_thresholds: [600, 800] }); // too few
assert(invalidCard._getCO2Color(700) === '#8bc34a', 'too-few thresholds → fall back to defaults');
const wrongType = new CardClass();
wrongType.setConfig({ co2_entity: 'sensor.co2', co2_thresholds: 'not an array' });
assert(wrongType._getCO2Color(700) === '#8bc34a', 'non-array thresholds → defaults');
const mixedType = new CardClass();
mixedType.setConfig({ co2_entity: 'sensor.co2', co2_thresholds: [600, '800', 1000, 1500] });
assert(mixedType._getCO2Color(700) === '#8bc34a', 'mixed-type thresholds → defaults');
section('Custom Thresholds — tVOC (mode-specific)');
const tvocPpb = new CardClass();
tvocPpb.setConfig({ tvoc_entity: 'sensor.tvoc', tvoc_unit: 'ppb', tvoc_thresholds: [50, 150, 300, 600] });
assert(tvocPpb._getTVOCColor(100) === '#8bc34a', 'tVOC ppb 100 < 150 = light green (custom)');
assert(tvocPpb._getTVOCColor(700) === '#f44336', 'tVOC ppb 700 > 600 = red (custom)');
const tvocIndex = new CardClass();
tvocIndex.setConfig({ tvoc_entity: 'sensor.tvoc', tvoc_unit: 'index', tvoc_thresholds: [80, 130, 200, 350] });
assert(tvocIndex._getTVOCColor(100) === '#8bc34a', 'tVOC index 100 < 130 = light green (custom)');
// ============================================================
// LOCALIZATION (issue #10, supersedes PR #11)
// ============================================================
section('Language resolution');
// Default behavior: no language config, no hass.locale → English
const enCard = new CardClass();
enCard.setConfig({ co2_entity: 'sensor.co2' });
enCard._hass = { config: { unit_system: { temperature: '°F' } }, states: {} };
assert(enCard._resolveLanguage() === 'en', 'default → en');
// hass.locale.language wins (modern HA)
enCard._hass = { config: { unit_system: { temperature: '°F' } }, states: {}, locale: { language: 'es' } };
assert(enCard._resolveLanguage() === 'es', 'hass.locale.language → es');
// hass.language fallback (older HA)
enCard._hass = { config: { unit_system: { temperature: '°F' } }, states: {}, language: 'fr' };
assert(enCard._resolveLanguage() === 'fr', 'hass.language fallback → fr');
// Explicit config wins over both
enCard._hass = { config: { unit_system: { temperature: '°F' } }, states: {}, locale: { language: 'es' } };
enCard._config.language = 'de';
assert(enCard._resolveLanguage() === 'de', 'config.language overrides hass.locale.language');
// Unknown language falls back to en
enCard._config.language = 'xx';
assert(enCard._resolveLanguage() === 'en', 'unknown language → en fallback');
// Regional code is stripped (e.g. en-US → en)
enCard._config.language = 'auto';
enCard._hass = { config: { unit_system: { temperature: '°F' } }, states: {}, locale: { language: 'es-MX' } };
assert(enCard._resolveLanguage() === 'es', 'es-MX → es (regional code stripped)');
section('Translation lookup');
// English baseline
enCard._config.language = 'en';
assert(enCard._t('status', 'excellent') === 'Excellent', 'en status: excellent');
assert(enCard._t('status', 'poor') === 'Poor', 'en status: poor');
assert(enCard._t('recommendation', 'open_window') === 'Open Window', 'en recommendation: open_window');
// Spanish
enCard._config.language = 'es';
assert(enCard._t('status', 'excellent') === 'Excelente', 'es status: Excelente');
assert(enCard._t('status', 'poor') === 'Malo', 'es status: Malo');
assert(enCard._t('recommendation', 'open_window') === 'Abre la ventana', 'es recommendation: Abre la ventana');
// French
enCard._config.language = 'fr';
assert(enCard._t('status', 'excellent') === 'Excellent', 'fr status: Excellent');
assert(enCard._t('recommendation', 'run_air_purifier') === 'Utiliser le purificateur', 'fr recommendation: Utiliser le purificateur');
// German
enCard._config.language = 'de';
assert(enCard._t('status', 'good') === 'Gut', 'de status: Gut');
assert(enCard._t('recommendation', 'all_good') === 'Alles gut', 'de recommendation: Alles gut');
// Missing key falls back to English
enCard._config.language = 'es';
assert(enCard._t('status', 'not_a_real_key') === 'not_a_real_key', 'unknown key returns the key itself');
section('Interpolation (_ts)');
enCard._config.language = 'en';
assert(enCard._ts('subtitle', 'co_danger', { value: 42 }) === 'CO at 42 ppm — dangerous levels detected', 'en interpolated subtitle');
enCard._config.language = 'es';
assert(enCard._ts('subtitle', 'co_danger', { value: 42 }) === 'CO en 42 ppm — niveles peligrosos detectados', 'es interpolated subtitle');
section('Overall status reflects language');
// Reuse the existing setup pattern
function aqCardWithLang(lang) {
const c = new CardClass();
c.setConfig({ co2_entity: 'sensor.co2', language: lang });
c._hass = { config: { unit_system: { temperature: '°F' } }, states: { 'sensor.co2': { state: '2000' } } };
return c;
}
assert(aqCardWithLang('en')._getOverallStatus().status === 'Poor', 'en: 2000ppm → Poor');
assert(aqCardWithLang('es')._getOverallStatus().status === 'Malo', 'es: 2000ppm → Malo');
assert(aqCardWithLang('fr')._getOverallStatus().status === 'Mauvais', 'fr: 2000ppm → Mauvais');
assert(aqCardWithLang('de')._getOverallStatus().status === 'Schlecht', 'de: 2000ppm → Schlecht');
section('Recommendation key + translation');
function recCardWithLang(lang, co2) {
const c = new CardClass();
c.setConfig({ co2_entity: 'sensor.co2', language: lang });
c._hass = { config: { unit_system: { temperature: '°F' } }, states: { 'sensor.co2': { state: String(co2) } } };
return c;
}
assert(recCardWithLang('en', 2000)._getRecommendationKey() === 'ventilate_now', 'key for high CO2 = ventilate_now');
assert(recCardWithLang('en', 2000)._getRecommendation() === 'Ventilate Now', 'en rec text: Ventilate Now');
assert(recCardWithLang('es', 2000)._getRecommendation() === 'Ventila ahora', 'es rec text: Ventila ahora');
assert(recCardWithLang('de', 2000)._getRecommendation() === 'Jetzt lüften', 'de rec text: Jetzt lüften');
// Icon resolution works with both key (preferred) and English text (backward-compat)
assert(recCardWithLang('en', 2000)._getRecommendationIcon('ventilate_now') === 'mdi:alert-circle', 'icon by key');
assert(recCardWithLang('en', 2000)._getRecommendationIcon('Ventilate Now') === 'mdi:alert-circle', 'icon by English text (backward-compat)');
// Reset card._config for downstream tests
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto' };
// ============================================================
// CARD SIZE TESTS
// ============================================================
section('Card Size');
card._config = { name: 'Test', hours_to_show: 24, temperature_unit: 'auto' };
assert(card.getCardSize() === 3, 'Base size = 3');
card._config.co2_entity = 'sensor.co2';
assert(card.getCardSize() === 4, 'One sensor = 4');
card._config.pm25_entity = 'sensor.pm25';
card._config.humidity_entity = 'sensor.hum';
card._config.temperature_entity = 'sensor.temp';