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
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
2374
2375
2376
2377
2378
2379
2380
2381
2382
2383
2384
2385
2386
2387
2388
2389
2390
2391
2392
2393
2394
2395
2396
2397
2398
2399
2400
2401
2402
2403
2404
2405
2406
2407
2408
2409
2410
2411
2412
2413
2414
2415
2416
2417
2418
2419
2420
2421
2422
2423
2424
2425
2426
2427
2428
2429
2430
2431
2432
2433
2434
2435
2436
2437
2438
2439
2440
2441
2442
2443
2444
2445
2446
2447
2448
2449
2450
2451
2452
2453
2454
2455
2456
2457
2458
2459
2460
2461
2462
2463
2464
2465
2466
2467
2468
2469
2470
2471
2472
2473
2474
2475
2476
2477
2478
2479
2480
2481
2482
2483
2484
2485
2486
2487
2488
2489
2490
2491
2492
2493
2494
2495
2496
2497
2498
2499
2500
2501
2502
2503
2504
2505
2506
2507
2508
2509
2510
2511
2512
2513
2514
2515
2516
2517
2518
2519
2520
2521
2522
2523
2524
2525
2526
2527
2528
2529
2530
2531
2532
2533
2534
2535
2536
2537
2538
2539
2540
2541
2542
2543
2544
2545
2546
2547
2548
2549
2550
2551
2552
2553
2554
2555
2556
2557
2558
2559
2560
2561
2562
2563
2564
2565
2566
2567
2568
2569
2570
2571
2572
2573
2574
2575
2576
2577
2578
2579
2580
2581
2582
2583
2584
2585
2586
2587
2588
2589
2590
2591
2592
2593
2594
2595
2596
2597
2598
2599
2600
2601
2602
2603
2604
2605
2606
2607
2608
2609
2610
2611
2612
2613
2614
2615
2616
2617
2618
2619
2620
2621
2622
2623
2624
2625
2626
2627
2628
2629
2630
2631
2632
2633
2634
2635
2636
2637
2638
2639
2640
2641
2642
2643
2644
2645
2646
2647
2648
2649
2650
2651
2652
2653
2654
2655
2656
2657
2658
2659
2660
2661
2662
2663
2664
2665
2666
2667
2668
2669
2670
2671
2672
2673
2674
2675
2676
2677
2678
2679
2680
2681
2682
2683
2684
2685
2686
2687
2688
2689
2690
2691
2692
2693
2694
2695
2696
2697
2698
2699
2700
2701
2702
2703
2704
2705
2706
2707
2708
2709
2710
2711
2712
2713
2714
2715
2716
2717
2718
2719
2720
2721
2722
2723
2724
2725
2726
2727
2728
2729
2730
2731
2732
2733
2734
2735
2736
2737
2738
2739
2740
2741
2742
2743
2744
2745
2746
2747
2748
2749
2750
2751
2752
2753
2754
2755
2756
2757
2758
2759
2760
2761
2762
2763
2764
2765
2766
2767
2768
2769
2770
2771
2772
2773
2774
2775
2776
2777
2778
2779
2780
2781
2782
2783
2784
2785
2786
2787
2788
2789
2790
2791
2792
2793
2794
2795
2796
2797
2798
2799
2800
2801
2802
2803
2804
2805
2806
2807
2808
2809
2810
2811
2812
2813
2814
2815
2816
2817
2818
2819
2820
2821
2822
2823
2824
2825
2826
2827
2828
2829
2830
2831
2832
2833
2834
2835
2836
2837
2838
2839
2840
2841
2842
2843
2844
2845
2846
2847
2848
2849
2850
2851
2852
2853
2854
2855
2856
2857
2858
2859
2860
2861
2862
2863
2864
2865
2866
2867
2868
2869
2870
2871
2872
2873
2874
2875
2876
2877
2878
2879
2880
2881
2882
2883
2884
2885
2886
2887
2888
2889
2890
2891
2892
2893
2894
2895
2896
2897
2898
2899
2900
2901
2902
2903
2904
2905
2906
2907
2908
2909
2910
2911
2912
2913
2914
2915
2916
2917
2918
2919
2920
2921
2922
2923
2924
2925
2926
2927
2928
2929
2930
2931
2932
2933
2934
2935
2936
2937
2938
2939
2940
2941
2942
2943
2944
2945
2946
2947
2948
2949
2950
2951
2952
2953
2954
2955
2956
2957
2958
2959
2960
2961
2962
2963
2964
2965
2966
2967
2968
2969
2970
2971
2972
2973
2974
2975
2976
2977
2978
2979
2980
2981
2982
2983
2984
2985
2986
2987
2988
2989
2990
2991
2992
2993
2994
2995
2996
2997
2998
2999
3000
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
3098
3099
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
3215
3216
3217
3218
3219
3220
3221
3222
3223
3224
3225
3226
3227
3228
3229
3230
3231
3232
3233
3234
3235
3236
3237
3238
3239
3240
3241
3242
3243
3244
3245
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
|
import { TaskMeta, Suite, File, TestAnnotation, TestArtifact, ImportDuration, Test, Task, TaskResultPack, FileSpecification, CancelReason, SequenceSetupFiles, SequenceHooks } from '@vitest/runner';
import { TestError, SerializedError, Arrayable, ParsedStack, Awaitable } from '@vitest/utils';
import { A as AfterSuiteRunMeta, U as UserConsoleLog, P as ProvidedContext, L as LabelColor } from './rpc.d.RH3apGEf.js';
import { Writable } from 'node:stream';
import { DevEnvironment, TransformResult as TransformResult$1, ViteDevServer, Plugin, UserConfig as UserConfig$1, DepOptimizationConfig, ServerOptions, ConfigEnv, AliasOptions } from 'vite';
import { S as SerializedTestSpecification, c as SourceModuleDiagnostic, B as BrowserTesterOptions } from './browser.d.ChKACdzH.js';
import { MockedModule } from '@vitest/mocker';
import { StackTraceParserOptions } from '@vitest/utils/source-map';
import { BrowserCommands } from 'vitest/browser';
import { B as BrowserTraceViewMode, S as SerializedConfig, F as FakeTimerInstallOpts } from './config.d.Cy95HiCx.js';
import { PrettyFormatOptions } from '@vitest/pretty-format';
import { SnapshotSummary, SnapshotStateOptions } from '@vitest/snapshot';
import { SerializedDiffOptions } from '@vitest/utils/diff';
import { chai } from '@vitest/expect';
import { happyDomTypes, jsdomTypes } from 'vitest/optional-types.js';
import { c as ContextTestEnvironment, d as WorkerExecuteContext, e as WorkerTestEnvironment } from './worker.d.Dyxm8DEL.js';
import { O as OTELCarrier } from './traces.d.402V_yFI.js';
import { B as BenchmarkResult } from './benchmark.d.DAaHLpsq.js';
import { a as RuntimeCoverageProviderModule } from './coverage.d.BZtK59WP.js';
import { SnapshotManager } from '@vitest/snapshot/manager';
import { Console } from 'node:console';
import { Stats } from 'node:fs';
type ChaiConfig = Omit<Partial<typeof chai.config>, "useProxy" | "proxyExcludedKeys">;
type HappyDOMOptions = Omit<NonNullable<ConstructorParameters<typeof happyDomTypes.Window>[0]>, "console">;
type JSDOMOptions = ConstructorOptionsOverride & Omit<jsdomTypes.ConstructorOptions, keyof ConstructorOptionsOverride>;
interface ConstructorOptionsOverride {
/**
* The html content for the test.
*
* @default '<!DOCTYPE html>'
*/
html?: string | ArrayBufferLike;
/**
* userAgent affects the value read from navigator.userAgent, as well as the User-Agent header sent while fetching subresources.
*
* @default `Mozilla/5.0 (${process.platform}) AppleWebKit/537.36 (KHTML, like Gecko) jsdom/${jsdomVersion}`
*/
userAgent?: string;
/**
* url sets the value returned by window.location, document.URL, and document.documentURI,
* and affects things like resolution of relative URLs within the document
* and the same-origin restrictions and referrer used while fetching subresources.
*
* @default 'http://localhost:3000'.
*/
url?: string;
/**
* Enable console?
*
* @default false
*/
console?: boolean;
/**
* jsdom does not have the capability to render visual content, and will act like a headless browser by default.
* It provides hints to web pages through APIs such as document.hidden that their content is not visible.
*
* When the `pretendToBeVisual` option is set to `true`, jsdom will pretend that it is rendering and displaying
* content.
*
* @default true
*/
pretendToBeVisual?: boolean;
/**
* Enable CookieJar
*
* @default false
*/
cookieJar?: boolean;
resources?: "usable";
}
declare class ReportedTaskImplementation {
/**
* The project associated with the test or suite.
*/
readonly project: TestProject;
/**
* Unique identifier.
* This ID is deterministic and will be the same for the same test across multiple runs.
* The ID is based on the project name, module url and test order.
*/
readonly id: string;
/**
* Location in the module where the test or suite is defined.
*/
readonly location: {
line: number;
column: number;
} | undefined;
/**
* Checks if the test did not fail the suite.
* If the test is not finished yet or was skipped, it will return `true`.
*/
ok(): boolean;
/**
* Custom metadata that was attached to the test during its execution.
*/
meta(): TaskMeta;
}
declare class TestCase extends ReportedTaskImplementation {
#private;
readonly type = "test";
/**
* Direct reference to the test module where the test or suite is defined.
*/
readonly module: TestModule;
/**
* Name of the test.
*/
readonly name: string;
/**
* Options that the test was initiated with.
*/
readonly options: TaskOptions;
/**
* Parent suite. If the test was called directly inside the module, the parent will be the module itself.
*/
readonly parent: TestSuite | TestModule;
/**
* Full name of the test including all parent suites separated with `>`.
*/
get fullName(): string;
/**
* Test results.
* - **pending**: Test was collected, but didn't finish running yet.
* - **passed**: Test passed successfully
* - **failed**: Test failed to execute
* - **skipped**: Test was skipped during collection or dynamically with `ctx.skip()`.
*/
result(): TestResult;
/**
* Test annotations added via the `task.annotate` API during the test execution.
*/
annotations(): ReadonlyArray<TestAnnotation>;
/**
* @experimental
*
* Test artifacts recorded via the `recordArtifact` API during the test execution.
*/
artifacts(): ReadonlyArray<TestArtifact>;
/**
* Useful information about the test like duration, memory usage, etc.
* Diagnostic is only available after the test has finished.
*/
diagnostic(): TestDiagnostic | undefined;
}
declare class TestCollection {
#private;
constructor(task: Suite | File, project: TestProject);
/**
* Returns the test or suite at a specific index.
*/
at(index: number): TestCase | TestSuite | undefined;
/**
* The number of tests and suites in the collection.
*/
get size(): number;
/**
* Returns the collection in array form for easier manipulation.
*/
array(): (TestCase | TestSuite)[];
/**
* Filters all tests that are part of this collection and its children.
*/
allTests(state?: TestState): Generator<TestCase, undefined, void>;
/**
* Filters only the tests that are part of this collection.
*/
tests(state?: TestState): Generator<TestCase, undefined, void>;
/**
* Filters only the suites that are part of this collection.
*/
suites(): Generator<TestSuite, undefined, void>;
/**
* Filters all suites that are part of this collection and its children.
*/
allSuites(): Generator<TestSuite, undefined, void>;
[Symbol.iterator](): Generator<TestSuite | TestCase, undefined, void>;
}
type ReportedHookContext = {
readonly name: "beforeAll" | "afterAll";
readonly entity: TestSuite | TestModule;
} | {
readonly name: "beforeEach" | "afterEach";
readonly entity: TestCase;
};
declare abstract class SuiteImplementation extends ReportedTaskImplementation {
/**
* Collection of suites and tests that are part of this suite.
*/
readonly children: TestCollection;
/**
* Errors that happened outside of the test run during collection, like syntax errors.
*/
errors(): SerializedError[];
}
declare class TestSuite extends SuiteImplementation {
#private;
readonly type = "suite";
/**
* Name of the test or the suite.
*/
readonly name: string;
/**
* Direct reference to the test module where the test or suite is defined.
*/
readonly module: TestModule;
/**
* Parent suite. If suite was called directly inside the module, the parent will be the module itself.
*/
readonly parent: TestSuite | TestModule;
/**
* Options that suite was initiated with.
*/
readonly options: TaskOptions;
/**
* Checks if the suite has any failed tests.
* This will also return `false` if suite failed during collection.
*/
ok: () => boolean;
/**
* The meta information attached to the suite during its collection or execution.
*/
meta: () => TaskMeta;
/**
* Checks the running state of the suite.
*/
state(): TestSuiteState;
/**
* Full name of the suite including all parent suites separated with `>`.
*/
get fullName(): string;
}
declare class TestModule extends SuiteImplementation {
readonly location: undefined;
readonly type = "module";
/**
* The Vite environment that processes files on the server.
*
* Can be empty if test module did not run yet.
*/
readonly viteEnvironment: DevEnvironment | undefined;
/**
* This is usually an absolute UNIX file path.
* It can be a virtual ID if the file is not on the disk.
* This value corresponds to the ID in the Vite's module graph.
*/
readonly moduleId: string;
/**
* Module id relative to the project. This is the same as `task.name`.
*/
readonly relativeModuleId: string;
/**
* Checks the running state of the test file.
*/
state(): TestModuleState;
/**
* Checks if the module has any failed tests.
* This will also return `false` if module failed during collection.
*/
ok: () => boolean;
/**
* The meta information attached to the module during its collection or execution.
*/
meta: () => TaskMeta;
/**
* Useful information about the module like duration, memory usage, etc.
* If the module was not executed yet, all diagnostic values will return `0`.
*/
diagnostic(): ModuleDiagnostic;
}
interface TaskOptions {
readonly each: boolean | undefined;
readonly fails: boolean | undefined;
readonly concurrent: boolean | undefined;
readonly shuffle: boolean | undefined;
readonly retry: number | undefined;
readonly repeats: number | undefined;
readonly mode: "run" | "only" | "skip" | "todo";
}
type TestSuiteState = "skipped" | "pending" | "failed" | "passed";
type TestModuleState = TestSuiteState | "queued";
type TestState = TestResult["state"];
type TestResult = TestResultPassed | TestResultFailed | TestResultSkipped | TestResultPending;
interface TestResultPending {
/**
* The test was collected, but didn't finish running yet.
*/
readonly state: "pending";
/**
* Pending tests have no errors.
*/
readonly errors: undefined;
}
interface TestResultPassed {
/**
* The test passed successfully.
*/
readonly state: "passed";
/**
* Errors that were thrown during the test execution.
*
* **Note**: If test was retried successfully, errors will still be reported.
*/
readonly errors: ReadonlyArray<TestError> | undefined;
}
interface TestResultFailed {
/**
* The test failed to execute.
*/
readonly state: "failed";
/**
* Errors that were thrown during the test execution.
*/
readonly errors: ReadonlyArray<TestError>;
}
interface TestResultSkipped {
/**
* The test was skipped with `only` (on another test), `skip` or `todo` flag.
* You can see which one was used in the `options.mode` option.
*/
readonly state: "skipped";
/**
* Skipped tests have no errors.
*/
readonly errors: undefined;
/**
* A custom note passed down to `ctx.skip(note)`.
*/
readonly note: string | undefined;
}
interface TestDiagnostic {
/**
* If the duration of the test is above `slowTestThreshold`.
*/
readonly slow: boolean;
/**
* The amount of memory used by the test in bytes.
* This value is only available if the test was executed with `logHeapUsage` flag.
*/
readonly heap: number | undefined;
/**
* The time it takes to execute the test in ms.
*/
readonly duration: number;
/**
* The time in ms when the test started.
*/
readonly startTime: number;
/**
* The amount of times the test was retried.
*/
readonly retryCount: number;
/**
* The amount of times the test was repeated as configured by `repeats` option.
* This value can be lower if the test failed during the repeat and no `retry` is configured.
*/
readonly repeatCount: number;
/**
* If test passed on a second retry.
*/
readonly flaky: boolean;
}
interface ModuleDiagnostic {
/**
* The time it takes to import and initiate an environment.
*/
readonly environmentSetupDuration: number;
/**
* The time it takes Vitest to setup test harness (runner, mocks, etc.).
*/
readonly prepareDuration: number;
/**
* The time it takes to import the test module.
* This includes importing everything in the module and executing suite callbacks.
*/
readonly collectDuration: number;
/**
* The time it takes to import the setup module.
*/
readonly setupDuration: number;
/**
* Accumulated duration of all tests and hooks in the module.
*/
readonly duration: number;
/**
* The amount of memory used by the test module in bytes.
* This value is only available if the test was executed with `logHeapUsage` flag.
*/
readonly heap: number | undefined;
/**
* The time spent importing every non-externalized dependency that Vitest has processed.
*/
readonly importDurations: Record<string, ImportDuration>;
}
declare function experimental_getRunnerTask(entity: TestCase): Test;
declare function experimental_getRunnerTask(entity: TestSuite): Suite;
declare function experimental_getRunnerTask(entity: TestModule): File;
declare function experimental_getRunnerTask(entity: TestCase | TestSuite | TestModule): Suite | File | Test;
declare class TestSpecification {
/**
* The task ID associated with the test module.
*/
readonly taskId: string;
/**
* The test project that the module belongs to.
*/
readonly project: TestProject;
/**
* The ID of the module in the Vite module graph. It is usually an absolute file path.
*/
readonly moduleId: string;
/**
* The current test pool. It's possible to have multiple pools in a single test project with `poolMatchGlob` and `typecheck.enabled`.
* @experimental In Vitest 4, the project will only support a single pool and this property will be removed.
*/
readonly pool: Pool;
/**
* Line numbers of the test locations to run.
*/
readonly testLines: number[] | undefined;
constructor(project: TestProject, moduleId: string, pool: Pool, testLines?: number[] | undefined);
/**
* Test module associated with the specification.
*/
get testModule(): TestModule | undefined;
toJSON(): SerializedTestSpecification;
}
interface CoverageSummaryData {
lines: Totals;
statements: Totals;
branches: Totals;
functions: Totals;
}
declare class CoverageSummary {
constructor(data: CoverageSummary | CoverageSummaryData);
merge(obj: CoverageSummary): CoverageSummary;
toJSON(): CoverageSummaryData;
isEmpty(): boolean;
data: CoverageSummaryData;
lines: Totals;
statements: Totals;
branches: Totals;
functions: Totals;
}
interface CoverageMapData {
[key: string]: FileCoverage | FileCoverageData;
}
declare class CoverageMap {
constructor(data: CoverageMapData | CoverageMap);
addFileCoverage(pathOrObject: string | FileCoverage | FileCoverageData): void;
files(): string[];
fileCoverageFor(filename: string): FileCoverage;
filter(callback: (key: string) => boolean): void;
getCoverageSummary(): CoverageSummary;
merge(data: CoverageMapData | CoverageMap): void;
toJSON(): CoverageMapData;
data: CoverageMapData;
}
interface Location {
line: number;
column: number;
}
interface Range {
start: Location;
end: Location;
}
interface BranchMapping {
loc: Range;
type: string;
locations: Range[];
line: number;
}
interface FunctionMapping {
name: string;
decl: Range;
loc: Range;
line: number;
}
interface FileCoverageData {
path: string;
statementMap: { [key: string]: Range };
fnMap: { [key: string]: FunctionMapping };
branchMap: { [key: string]: BranchMapping };
s: { [key: string]: number };
f: { [key: string]: number };
b: { [key: string]: number[] };
}
interface Totals {
total: number;
covered: number;
skipped: number;
pct: number;
}
interface Coverage {
covered: number;
total: number;
coverage: number;
}
declare class FileCoverage implements FileCoverageData {
constructor(data: string | FileCoverage | FileCoverageData);
merge(other: FileCoverageData): void;
getBranchCoverageByLine(): { [line: number]: Coverage };
getLineCoverage(): { [line: number]: number };
getUncoveredLines(): number[];
resetHits(): void;
computeBranchTotals(): Totals;
computeSimpleTotals(): Totals;
toSummary(): CoverageSummary;
toJSON(): object;
data: FileCoverageData;
path: string;
statementMap: { [key: string]: Range };
fnMap: { [key: string]: FunctionMapping };
branchMap: { [key: string]: BranchMapping };
s: { [key: string]: number };
f: { [key: string]: number };
b: { [key: string]: number[] };
}
interface Node {
isRoot(): boolean;
visit(visitor: Visitor, state: any): void;
}
interface Visitor<N extends Node = Node> {
onStart(root: N, state: any): void;
onSummary(root: N, state: any): void;
onDetail(root: N, state: any): void;
onSummaryEnd(root: N, state: any): void;
onEnd(root: N, state: any): void;
}
interface FileOptions {
file: string;
}
interface ProjectOptions {
projectRoot: string;
}
interface ReportOptions {
clover: CloverOptions;
cobertura: CoberturaOptions;
"html-spa": HtmlSpaOptions;
html: HtmlOptions;
json: JsonOptions$1;
"json-summary": JsonSummaryOptions;
lcov: LcovOptions;
lcovonly: LcovOnlyOptions;
none: never;
teamcity: TeamcityOptions;
text: TextOptions;
"text-lcov": TextLcovOptions;
"text-summary": TextSummaryOptions;
}
interface CloverOptions extends FileOptions, ProjectOptions {}
interface CoberturaOptions extends FileOptions, ProjectOptions {}
interface HtmlSpaOptions extends HtmlOptions {
metricsToShow: Array<"lines" | "branches" | "functions" | "statements">;
}
interface HtmlOptions {
verbose: boolean;
skipEmpty: boolean;
subdir: string;
linkMapper: LinkMapper;
}
type JsonOptions$1 = FileOptions;
type JsonSummaryOptions = FileOptions;
interface LcovOptions extends FileOptions, ProjectOptions {}
interface LcovOnlyOptions extends FileOptions, ProjectOptions {}
interface TeamcityOptions extends FileOptions {
blockName: string;
}
interface TextOptions extends FileOptions {
maxCols: number;
skipEmpty: boolean;
skipFull: boolean;
}
type TextLcovOptions = ProjectOptions;
type TextSummaryOptions = FileOptions;
interface LinkMapper {
getPath(node: string | Node): string;
relativePath(source: string | Node, target: string | Node): string;
assetPath(node: Node, name: string): string;
}
type TransformResult = string | Partial<TransformResult$1> | undefined | null | void;
type CoverageResults = unknown;
interface CoverageProvider {
name: string;
/** Called when provider is being initialized before tests run */
initialize: (ctx: Vitest) => Promise<void> | void;
/** Called when setting coverage options for Vitest context (`ctx.config.coverage`) */
resolveOptions: () => ResolvedCoverageOptions;
/** Callback to clean previous reports */
clean: (clean?: boolean) => void | Promise<void>;
/** Called with coverage results after a single test file has been run */
onAfterSuiteRun: (meta: AfterSuiteRunMeta) => void | Promise<void>;
/** Callback called when test run fails */
onTestFailure?: () => void | Promise<void>;
/** Callback to generate final coverage results */
generateCoverage: (reportContext: ReportContext) => CoverageResults | Promise<CoverageResults>;
/** Callback to convert coverage results to coverage reports. Called with results returned from `generateCoverage` */
reportCoverage: (coverage: CoverageResults, reportContext: ReportContext) => void | Promise<void>;
/** Callback for `--merge-reports` options. Called with multiple coverage results generated by `generateCoverage`. */
mergeReports?: (coverages: CoverageResults[]) => void | Promise<void>;
/** Callback called for instrumenting files with coverage counters. */
onFileTransform?: (sourceCode: string, id: string, pluginCtx: any) => TransformResult | Promise<TransformResult>;
/**
* Return `true` if this file is transformed by the coverage provider.
* This is used to generate the persistent file hash by `fsModuleCache`
* @experimental
*/
requiresTransform?: (id: string) => boolean;
/** Callback that's called when the coverage is enabled via a programmatic `enableCoverage` API. */
onEnabled?: () => void | Promise<void>;
}
interface ReportContext {
/** Indicates whether all tests were run. False when only specific tests were run. */
allTestsRun?: boolean;
}
interface CoverageProviderModule extends RuntimeCoverageProviderModule {
/**
* Factory for creating a new coverage provider
*/
getProvider: () => CoverageProvider | Promise<CoverageProvider>;
}
type CoverageReporter = keyof ReportOptions | (string & {});
type CoverageReporterWithOptions<ReporterName extends CoverageReporter = CoverageReporter> = ReporterName extends keyof ReportOptions ? ReportOptions[ReporterName] extends never ? [ReporterName, object] : [ReporterName, Partial<ReportOptions[ReporterName]>] : [ReporterName, Record<string, unknown>];
type CoverageProviderName = "v8" | "istanbul" | "custom" | undefined;
type CoverageOptions<T extends CoverageProviderName = CoverageProviderName> = T extends "istanbul" ? {
provider: T;
} & CoverageIstanbulOptions : T extends "v8" ? {
/**
* Provider to use for coverage collection.
*
* @default 'v8'
*/
provider: T;
} & CoverageV8Options : T extends "custom" ? {
provider: T;
} & CustomProviderOptions : {
provider?: T;
} & CoverageV8Options;
/** Fields that have default values. Internally these will always be defined. */
type FieldsWithDefaultValues = "enabled" | "clean" | "cleanOnRerun" | "reportsDirectory" | "exclude" | "reportOnFailure" | "allowExternal" | "processingConcurrency";
type ResolvedCoverageOptions<T extends CoverageProviderName = CoverageProviderName> = CoverageOptions<T> & Required<Pick<CoverageOptions<T>, FieldsWithDefaultValues>> & {
reporter: CoverageReporterWithOptions[];
};
interface BaseCoverageOptions {
/**
* Enables coverage collection. Can be overridden using `--coverage` CLI option.
*
* @default false
*/
enabled?: boolean;
/**
* List of files included in coverage as glob patterns.
* By default only files covered by tests are included.
*
* See [Including and excluding files from coverage report](https://vitest.dev/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples.
*/
include?: string[];
/**
* List of files excluded from coverage as glob patterns.
* Files are first checked against `coverage.include`.
*
* See [Including and excluding files from coverage report](https://vitest.dev/guide/coverage.html#including-and-excluding-files-from-coverage-report) for examples.
*/
exclude?: string[];
/**
* Clean coverage results before running tests
*
* @default true
*/
clean?: boolean;
/**
* Clean coverage report on watch rerun
*
* @default true
*/
cleanOnRerun?: boolean;
/**
* Directory to write coverage report to
*
* @default './coverage'
*/
reportsDirectory?: string;
/**
* Coverage reporters to use.
* See [istanbul documentation](https://istanbul.js.org/docs/advanced/alternative-reporters/) for detailed list of all reporters.
*
* @default ['text', 'html', 'clover', 'json']
*/
reporter?: Arrayable<CoverageReporter> | (CoverageReporter | [CoverageReporter] | CoverageReporterWithOptions)[];
/**
* Do not show files with 100% statement, branch, and function coverage
*
* @default false
*/
skipFull?: boolean;
/**
* Configurations for thresholds
*
* @example
*
* ```ts
* {
* // Thresholds for all files
* functions: 95,
* branches: 70,
* perFile: true,
* autoUpdate: true,
*
* // Thresholds for utilities
* 'src/utils/**.ts': {
* lines: 100,
* statements: 95,
* }
* }
* ```
*/
thresholds?: Thresholds | ({
[glob: string]: Pick<Thresholds, 100 | "statements" | "functions" | "branches" | "lines">;
} & Thresholds);
/**
* Watermarks for statements, lines, branches and functions.
*
* Default value is `[50,80]` for each property.
*/
watermarks?: {
statements?: [number, number];
functions?: [number, number];
branches?: [number, number];
lines?: [number, number];
};
/**
* Generate coverage report even when tests fail.
*
* @default false
*/
reportOnFailure?: boolean;
/**
* Collect coverage of files outside the project `root`.
*
* @default false
*/
allowExternal?: boolean;
/**
* Apply exclusions again after coverage has been remapped to original sources.
* This is useful when your source files are transpiled and may contain source maps
* of non-source files.
*
* Use this option when you are seeing files that show up in report even if they
* match your `coverage.exclude` patterns.
*
* @default false
*/
excludeAfterRemap?: boolean;
/**
* Concurrency limit used when processing the coverage results.
* Defaults to `Math.min(20, os.availableParallelism?.() ?? os.cpus().length)`
*/
processingConcurrency?: number;
/**
* Set to array of class method names to ignore for coverage
*
* @default []
*/
ignoreClassMethods?: string[];
}
interface CoverageIstanbulOptions extends BaseCoverageOptions {}
interface CoverageV8Options extends BaseCoverageOptions {}
interface CustomProviderOptions extends Pick<BaseCoverageOptions, FieldsWithDefaultValues> {
/** Name of the module or path to a file to load the custom provider from */
customProviderModule: string;
}
interface Thresholds {
/** Set global thresholds to `100` */
100?: boolean;
/** Check thresholds per file. */
perFile?: boolean;
/**
* Update threshold values automatically when current coverage is higher than earlier thresholds
* Also can accept a function to format the new threshold values
*
* @default false
*/
autoUpdate?: boolean | ((newThreshold: number) => number);
/** Thresholds for statements */
statements?: number;
/** Thresholds for functions */
functions?: number;
/** Thresholds for branches */
branches?: number;
/** Thresholds for lines */
lines?: number;
}
interface TestRunResult {
testModules: TestModule[];
unhandledErrors: unknown[];
}
declare class TypeCheckError extends Error {
message: string;
stacks: ParsedStack[];
name: string;
constructor(message: string, stacks: ParsedStack[]);
}
interface ErrorOptions {
type?: string;
fullStack?: boolean;
project?: TestProject;
verbose?: boolean;
screenshotPaths?: string[];
task?: Task;
showCodeFrame?: boolean;
}
type Listener = () => void;
declare class Logger {
ctx: Vitest;
outputStream: NodeJS.WriteStream | Writable;
errorStream: NodeJS.WriteStream | Writable;
private _clearScreenPending;
private _highlights;
private cleanupListeners;
console: Console;
constructor(ctx: Vitest, outputStream?: NodeJS.WriteStream | Writable, errorStream?: NodeJS.WriteStream | Writable);
log(...args: any[]): void;
error(...args: any[]): void;
warn(...args: any[]): void;
clearFullScreen(message?: string): void;
clearScreen(message: string, force?: boolean): void;
private _clearScreen;
printError(err: unknown, options?: ErrorOptions): void;
deprecate(message: string): void;
clearHighlightCache(filename?: string): void;
highlight(filename: string, source: string): string;
printNoTestFound(filters?: string[]): void;
printBanner(): void;
printBrowserBanner(project: TestProject): void;
printUnhandledErrors(errors: ReadonlyArray<unknown>): void;
printSourceTypeErrors(errors: TypeCheckError[]): void;
getColumns(): number;
onTerminalCleanup(listener: Listener): void;
private addCleanupListeners;
private registerUnhandledRejection;
}
interface SuiteResultCache {
failed: boolean;
duration: number;
}
declare class ResultsCache {
private logger;
private cache;
private workspacesKeyMap;
private cachePath;
private version;
private root;
constructor(logger: Logger);
getCachePath(): string | null;
setConfig(root: string, config: ResolvedConfig["cache"]): void;
getResults(key: string): SuiteResultCache | undefined;
clearCache(): Promise<void>;
readFromCache(): Promise<void>;
updateResults(files: File[]): void;
removeFromCache(filepath: string): void;
writeToCache(): Promise<void>;
}
type FileStatsCache = Pick<Stats, "size">;
declare class FilesStatsCache {
cache: Map<string, FileStatsCache>;
getStats(key: string): FileStatsCache | undefined;
populateStats(root: string, specs: TestSpecification[]): Promise<void>;
updateStats(fsPath: string, key: string): Promise<void>;
removeStats(fsPath: string): void;
}
declare class VitestCache {
results: ResultsCache;
stats: FilesStatsCache;
constructor(logger: Logger);
getFileTestResults(key: string): SuiteResultCache | undefined;
getFileStats(key: string): {
size: number;
} | undefined;
static resolveCacheDir(root: string, dir?: string, projectName?: string): string;
}
declare class VitestPackageInstaller {
isPackageExists(name: string, options?: {
paths?: string[];
}): boolean;
ensureInstalled(dependency: string, root: string, version?: string): Promise<boolean>;
}
type TestRunEndReason = "passed" | "interrupted" | "failed";
interface Reporter {
onInit?: (vitest: Vitest) => void;
/**
* Called when the project initiated the browser instance.
* project.browser will always be defined.
* @experimental
*/
onBrowserInit?: (project: TestProject) => Awaitable<void>;
onTestRemoved?: (trigger?: string) => Awaitable<void>;
onWatcherStart?: (files?: File[], errors?: unknown[]) => Awaitable<void>;
onWatcherRerun?: (files: string[], trigger?: string) => Awaitable<void>;
onServerRestart?: (reason?: string) => Awaitable<void>;
onUserConsoleLog?: (log: UserConsoleLog) => Awaitable<void>;
onProcessTimeout?: () => Awaitable<void>;
/**
* Called when the new test run starts.
*/
onTestRunStart?: (specifications: ReadonlyArray<TestSpecification>) => Awaitable<void>;
/**
* Called when the test run is finished.
*/
onTestRunEnd?: (testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason) => Awaitable<void>;
/**
* Called when the module is enqueued for testing. The file itself is not loaded yet.
*/
onTestModuleQueued?: (testModule: TestModule) => Awaitable<void>;
/**
* Called when the test file is loaded and the module is ready to run tests.
*/
onTestModuleCollected?: (testModule: TestModule) => Awaitable<void>;
/**
* Called when starting to run tests of the test file
*/
onTestModuleStart?: (testModule: TestModule) => Awaitable<void>;
/**
* Called when all tests of the test file have finished running.
*/
onTestModuleEnd?: (testModule: TestModule) => Awaitable<void>;
/**
* Called when test case is ready to run.
* Called before the `beforeEach` hooks for the test are run.
*/
onTestCaseReady?: (testCase: TestCase) => Awaitable<void>;
/**
* Called after the test and its hooks are finished running.
* The `result()` cannot be `pending`.
*/
onTestCaseResult?: (testCase: TestCase) => Awaitable<void>;
/**
* Called when annotation is added via the `task.annotate` API.
*/
onTestCaseAnnotate?: (testCase: TestCase, annotation: TestAnnotation) => Awaitable<void>;
/**
* Called when artifacts are recorded on tests via the `recordArtifact` utility.
*/
onTestCaseArtifactRecord?: (testCase: TestCase, artifact: TestArtifact) => Awaitable<void>;
/**
* Called when test suite is ready to run.
* Called before the `beforeAll` hooks for the test are run.
*/
onTestSuiteReady?: (testSuite: TestSuite) => Awaitable<void>;
/**
* Called after the test suite and its hooks are finished running.
* The `state` cannot be `pending`.
*/
onTestSuiteResult?: (testSuite: TestSuite) => Awaitable<void>;
/**
* Called before the hook starts to run.
*/
onHookStart?: (hook: ReportedHookContext) => Awaitable<void>;
/**
* Called after the hook finished running.
*/
onHookEnd?: (hook: ReportedHookContext) => Awaitable<void>;
onCoverage?: (coverage: unknown) => Awaitable<void>;
}
interface BlobOptions {
outputFile?: string;
}
declare class BlobReporter implements Reporter {
start: number;
ctx: Vitest;
options: BlobOptions;
coverage: unknown | undefined;
constructor(options: BlobOptions);
onInit(ctx: Vitest): void;
onCoverage(coverage: unknown): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>): Promise<void>;
}
interface MergedBlobs {
files: File[];
errors: unknown[];
coverages: unknown[];
executionTimes: number[];
}
declare class StateManager {
filesMap: Map<string, File[]>;
pathsSet: Set<string>;
idMap: Map<string, Task>;
taskFileMap: WeakMap<Task, File>;
errorsSet: Set<unknown>;
reportedTasksMap: WeakMap<Task, TestModule | TestCase | TestSuite>;
blobs?: MergedBlobs;
transformTime: number;
metadata: Record<string, {
externalized: Record<string, string>;
duration: Record<string, number[]>;
tmps: Record<string, string>;
dumpDir?: string;
outline?: {
externalized: number;
inlined: number;
};
}>;
onUnhandledError?: OnUnhandledErrorCallback;
constructor(options: {
onUnhandledError?: OnUnhandledErrorCallback;
});
catchError(error: unknown, type: string): void;
clearErrors(): void;
getUnhandledErrors(): unknown[];
getPaths(): string[];
/**
* Return files that were running or collected.
*/
getFiles(keys?: string[]): File[];
getTestModules(keys?: string[]): TestModule[];
getFilepaths(): string[];
getFailedFilepaths(): string[];
collectPaths(paths?: string[]): void;
collectFiles(project: TestProject, files?: File[]): void;
clearFiles(project: TestProject, paths?: string[]): void;
updateId(task: Task, project: TestProject): void;
getReportedEntity(task: Task): TestModule | TestCase | TestSuite | undefined;
getReportedEntityById(taskId: string): TestModule | TestCase | TestSuite | undefined;
updateTasks(packs: TaskResultPack[]): void;
updateUserLog(log: UserConsoleLog): void;
getCountOfFailedTests(): number;
cancelFiles(files: FileSpecification[], project: TestProject): void;
}
declare class VitestWatcher {
private vitest;
/**
* Modules that will be invalidated on the next run.
*/
readonly invalidates: Set<string>;
/**
* Test files that have changed and need to be rerun.
*/
readonly changedTests: Set<string>;
private readonly _onRerun;
constructor(vitest: Vitest);
unregisterWatcher: () => void;
registerWatcher(): this;
private scheduleRerun;
private getTestFilesFromWatcherTrigger;
onFileChange: (id: string) => void;
onFileDelete: (id: string) => void;
onFileCreate: (id: string) => void;
private handleSetupFile;
/**
* @returns A value indicating whether rerun is needed (changedTests was mutated)
*/
private handleFileChanged;
}
interface WatcherTriggerPattern {
pattern: RegExp;
testsToRun: (file: string, match: RegExpMatchArray) => string[] | string | null | undefined | void;
}
interface VitestOptions {
packageInstaller?: VitestPackageInstaller;
stdin?: NodeJS.ReadStream;
stdout?: NodeJS.WriteStream | Writable;
stderr?: NodeJS.WriteStream | Writable;
}
declare class Vitest {
readonly mode: VitestRunMode;
/**
* Current Vitest version.
* @example '2.0.0'
*/
readonly version: string;
static readonly version: string;
/**
* The logger instance used to log messages. It's recommended to use this logger instead of `console`.
* It's possible to override stdout and stderr streams when initiating Vitest.
* @example
* new Vitest('test', {
* stdout: new Writable(),
* })
*/
readonly logger: Logger;
/**
* The package installer instance used to install Vitest packages.
* @example
* await vitest.packageInstaller.ensureInstalled('@vitest/browser', process.cwd())
*/
readonly packageInstaller: VitestPackageInstaller;
/**
* A path to the built Vitest directory. This is usually a folder in `node_modules`.
*/
readonly distPath: string;
/**
* A list of projects that are currently running.
* If projects were filtered with `--project` flag, they won't appear here.
*/
projects: TestProject[];
/**
* A watcher handler. This is not the file system watcher. The handler only
* exposes methods to handle changed files.
*
* If you have your own watcher, you can use these methods to replicate
* Vitest behaviour.
*/
readonly watcher: VitestWatcher;
private isFirstRun;
private restartsCount;
private readonly specifications;
private pool;
private _config?;
private _vite?;
private _state?;
private _cache?;
private _snapshot?;
private _coverageProvider?;
constructor(mode: VitestRunMode, cliOptions: UserConfig, options?: VitestOptions);
private _onRestartListeners;
private _onClose;
private _onSetServer;
private _onCancelListeners;
private _onUserTestsRerun;
private _onFilterWatchedSpecification;
/**
* The global config.
*/
get config(): ResolvedConfig;
/**
* Global Vite's dev server instance.
*/
get vite(): ViteDevServer;
/**
* The global test state manager.
* @experimental The State API is experimental and not subject to semver.
*/
get state(): StateManager;
/**
* The global snapshot manager. You can access the current state on `snapshot.summary`.
*/
get snapshot(): SnapshotManager;
/**
* Test results and test file stats cache. Primarily used by the sequencer to sort tests.
*/
get cache(): VitestCache;
enableCoverage(): Promise<void>;
disableCoverage(): void;
private clearAllCachePaths;
private _coverageOverrideCache;
/**
* Inject new test projects into the workspace.
* @param config Glob, config path or a custom config options.
* @returns An array of new test projects. Can be empty if the name was filtered out.
*/
private injectTestProject;
/**
* Provide a value to the test context. This value will be available to all tests with `inject`.
*/
provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
/**
* Get global provided context.
*/
getProvidedContext(): ProvidedContext;
/**
* Return project that has the root (or "global") config.
*/
getRootProject(): TestProject;
getProjectByName(name: string): TestProject;
/**
* Import a file using Vite module runner. The file will be transformed by Vite and executed in a separate context.
* @param moduleId The ID of the module in Vite module graph
*/
import<T>(moduleId: string): Promise<T>;
/**
* Creates a coverage provider if `coverage` is enabled in the config.
*/
createCoverageProvider(): Promise<CoverageProvider | null>;
private resolveProjects;
/**
* Glob test files in every project and create a TestSpecification for each file and pool.
* @param filters String filters to match the test files.
*/
globTestSpecifications(filters?: string[]): Promise<TestSpecification[]>;
private initCoverageProvider;
/**
* Deletes all Vitest caches, including `experimental.fsModuleCache`.
* @experimental
*/
experimental_clearCache(): Promise<void>;
/**
* Merge reports from multiple runs located in the specified directory (value from `--merge-reports` if not specified).
*/
mergeReports(directory?: string): Promise<TestRunResult>;
/**
* Returns the seed, if tests are running in a random order.
*/
getSeed(): number | null;
collect(filters?: string[]): Promise<TestRunResult>;
/**
* Returns the list of test files that match the config and filters.
* @param filters String filters to match the test files
*/
getRelevantTestSpecifications(filters?: string[]): Promise<TestSpecification[]>;
/**
* Initialize reporters, the coverage provider, and run tests.
* This method can throw an error:
* - `FilesNotFoundError` if no tests are found
* - `GitNotFoundError` if `--related` flag is used, but git repository is not initialized
* - `Error` from the user reporters
* @param filters String filters to match the test files
*/
start(filters?: string[]): Promise<TestRunResult>;
/**
* Initialize reporters and the coverage provider. This method doesn't run any tests.
* If the `--watch` flag is provided, Vitest will still run changed tests even if this method was not called.
*/
init(): Promise<void>;
/**
* If there is a test run happening, returns a promise that will
* resolve when the test run is finished.
*/
waitForTestRunEnd(): Promise<void>;
/**
* Get test specifications associated with the given module. If module is not a test file, an empty array is returned.
*
* **Note:** this method relies on a cache generated by `globTestSpecifications`. If the file was not processed yet, use `project.matchesGlobPattern` instead.
* @param moduleId The module ID to get test specifications for.
*/
getModuleSpecifications(moduleId: string): TestSpecification[];
/**
* Vitest automatically caches test specifications for each file. This method clears the cache for the given file or the whole cache altogether.
*/
clearSpecificationsCache(moduleId?: string): void;
/**
* Run tests for the given test specifications. This does not trigger `onWatcher*` events.
* @param specifications A list of specifications to run.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
runTestSpecifications(specifications: TestSpecification[], allTestsRun?: boolean): Promise<TestRunResult>;
/**
* Rerun files and trigger `onWatcherRerun`, `onWatcherStart` and `onTestsRerun` events.
* @param specifications A list of specifications to run.
* @param allTestsRun Indicates whether all tests were run. This only matters for coverage.
*/
rerunTestSpecifications(specifications: TestSpecification[], allTestsRun?: boolean): Promise<TestRunResult>;
private runFiles;
/**
* Returns module's diagnostic. If `testModule` is not provided, `selfTime` and `totalTime` will be aggregated across all tests.
*
* If the module was not transformed or executed, the diagnostic will be empty.
* @experimental
* @see {@link https://vitest.dev/api/advanced/vitest#getsourcemodulediagnostic}
*/
experimental_getSourceModuleDiagnostic(moduleId: string, testModule?: TestModule): Promise<SourceModuleDiagnostic>;
experimental_parseSpecifications(specifications: TestSpecification[], options?: {
/** @default os.availableParallelism() */
concurrency?: number;
}): Promise<TestModule[]>;
experimental_parseSpecification(specification: TestSpecification): Promise<TestModule>;
/**
* Collect tests in specified modules. Vitest will run the files to collect tests.
* @param specifications A list of specifications to run.
*/
collectTests(specifications: TestSpecification[]): Promise<TestRunResult>;
/**
* Gracefully cancel the current test run. Vitest will wait until all running tests are finished before cancelling.
*/
cancelCurrentRun(reason: CancelReason): Promise<void>;
private initializeGlobalSetup;
/**
* Update snapshots in specified files. If no files are provided, it will update files with failed tests and obsolete snapshots.
* @param files The list of files on the file system
*/
updateSnapshot(files?: string[]): Promise<TestRunResult>;
/**
* Enable the mode that allows updating snapshots when running tests.
* This method doesn't run any tests.
*
* Every test that runs after this method is called will update snapshots.
* To disable the mode, call `resetSnapshotUpdate`.
*/
enableSnapshotUpdate(): void;
/**
* Disable the mode that allows updating snapshots when running tests.
*/
resetSnapshotUpdate(): void;
/**
* Set the global test name pattern to a regexp.
* This method doesn't run any tests.
*/
setGlobalTestNamePattern(pattern: string | RegExp): void;
/**
* Returns the regexp used for the global test name pattern.
*/
getGlobalTestNamePattern(): RegExp | undefined;
/**
* Resets the global test name pattern. This method doesn't run any tests.
*/
resetGlobalTestNamePattern(): void;
private _rerunTimer;
private scheduleRerun;
/**
* Invalidate a file in all projects.
*/
invalidateFile(filepath: string): void;
private reportCoverage;
/**
* Closes all projects and their associated resources.
* This can only be called once; the closing promise is cached until the server restarts.
*/
close(): Promise<void>;
/**
* Closes all projects and exit the process
* @param force If true, the process will exit immediately after closing the projects.
*/
exit(force?: boolean): Promise<void>;
/**
* Should the server be kept running after the tests are done.
*/
shouldKeepServer(): boolean;
/**
* Register a handler that will be called when the server is restarted due to a config change.
*/
onServerRestart(fn: OnServerRestartHandler): void;
/**
* Register a handler that will be called when the test run is cancelled with `vitest.cancelCurrentRun`.
*/
onCancel(fn: (reason: CancelReason) => Awaitable<void>): () => void;
/**
* Register a handler that will be called when the server is closed.
*/
onClose(fn: () => Awaitable<void>): void;
/**
* Register a handler that will be called when the tests are rerunning.
*/
onTestsRerun(fn: OnTestsRerunHandler): void;
/**
* Register a handler that will be called when a file is changed.
* This callback should return `true` of `false` indicating whether the test file needs to be rerun.
* @example
* const testsToRun = [resolve('./test.spec.ts')]
* vitest.onFilterWatchedSpecification(specification => testsToRun.includes(specification.moduleId))
*/
onFilterWatchedSpecification(fn: (specification: TestSpecification) => boolean): void;
/**
* Check if the project with a given name should be included.
*/
matchesProjectFilter(name: string): boolean;
}
type OnServerRestartHandler = (reason?: string) => Promise<void> | void;
type OnTestsRerunHandler = (testFiles: TestSpecification[]) => Promise<void> | void;
interface CDPSession {
send: (method: string, params?: Record<string, unknown>) => Promise<unknown>;
on: (event: string, listener: (...args: unknown[]) => void) => void;
once: (event: string, listener: (...args: unknown[]) => void) => void;
off: (event: string, listener: (...args: unknown[]) => void) => void;
}
interface BrowserModuleMocker {
register: (sessionId: string, module: MockedModule) => Promise<void>;
delete: (sessionId: string, url: string) => Promise<void>;
clear: (sessionId: string) => Promise<void>;
}
interface BrowserProviderOption<Options extends object = object> {
name: string;
supportedBrowser?: ReadonlyArray<string>;
options: Options;
providerFactory: (project: TestProject) => BrowserProvider;
serverFactory: BrowserServerFactory;
}
interface BrowserServerOptions {
project: TestProject;
coveragePlugin: () => Plugin;
mocksPlugins: (options: {
filter: (id: string) => boolean;
}) => Plugin[];
metaEnvReplacer: () => Plugin;
}
interface BrowserServerFactory {
(options: BrowserServerOptions): Promise<ParentProjectBrowser>;
}
interface BrowserProvider {
name: string;
mocker?: BrowserModuleMocker;
readonly initScripts?: string[];
/**
* @experimental opt-in into file parallelisation
*/
supportsParallelism: boolean;
getCommandsContext: (sessionId: string) => Record<string, unknown>;
openPage: (sessionId: string, url: string) => Promise<void>;
getCDPSession?: (sessionId: string) => Promise<CDPSession>;
close: () => Awaitable<void>;
}
type BrowserBuiltinProvider = "webdriverio" | "playwright" | "preview";
interface _BrowserNames {}
type UnsupportedProperties = "browser" | "typecheck" | "alias" | "sequence" | "root" | "pool" | "runner" | "api" | "deps" | "environment" | "environmentOptions" | "server" | "benchmark" | "name";
interface BrowserInstanceOption extends Omit<ProjectConfig, UnsupportedProperties>, Pick<BrowserConfigOptions, "headless" | "locators" | "viewport" | "testerHtmlPath" | "screenshotDirectory" | "screenshotFailures"> {
/**
* Name of the browser
*/
browser: keyof _BrowserNames extends never ? string : _BrowserNames[keyof _BrowserNames];
name?: string;
provider?: BrowserProviderOption;
}
interface BrowserConfigOptions {
/**
* if running tests in the browser should be the default
*
* @default false
*/
enabled?: boolean;
/**
* Configurations for different browser setups
*/
instances?: BrowserInstanceOption[];
/**
* Browser provider
* @example
* ```ts
* import { playwright } from '@vitest/browser-playwright'
* export default defineConfig({
* test: {
* browser: {
* provider: playwright(),
* },
* },
* })
* ```
*/
provider?: BrowserProviderOption;
/**
* enable headless mode
*
* @default process.env.CI
*/
headless?: boolean;
/**
* Serve API options.
*
* The default port is 63315.
*/
api?: ApiConfig | number;
/**
* Isolate test environment after each test
*
* @default true
* @deprecated use top-level `isolate` instead
*/
isolate?: boolean;
/**
* Run test files in parallel if provider supports this option
* This option only has effect in headless mode (enabled in CI by default)
*
* @default // Same as "test.fileParallelism"
* @deprecated use top-level `fileParallelism` instead
*/
fileParallelism?: boolean;
/**
* Show Vitest UI
*
* @default !process.env.CI
*/
ui?: boolean;
/**
* Default viewport size
*/
viewport?: {
/**
* Width of the viewport
* @default 414
*/
width: number;
/**
* Height of the viewport
* @default 896
*/
height: number;
};
/**
* Locator options
*/
locators?: {
/**
* Attribute used to locate elements by test id
* @default 'data-testid'
*/
testIdAttribute?: string;
};
/**
* Generate traces that can be viewed on https://trace.playwright.dev/
*
* This option is supported only by **playwright** provider.
*/
trace?: BrowserTraceViewMode | {
mode: BrowserTraceViewMode;
/**
* The directory where all traces will be stored. By default, Vitest
* stores all traces in `__traces__` folder close to the test file.
*/
tracesDir?: string;
/**
* Whether to capture screenshots during tracing. Screenshots are used to build a timeline preview.
* @default true
*/
screenshots?: boolean;
/**
* If this option is true tracing will
* - capture DOM snapshot on every action
* - record network activity
* @default true
*/
snapshots?: boolean;
};
/**
* Directory where screenshots will be saved when page.screenshot() is called
* If not set, all screenshots are saved to __screenshots__ directory in the same folder as the test file.
* If this is set, it will be resolved relative to the project root.
* @default __screenshots__
*/
screenshotDirectory?: string;
/**
* Should Vitest take screenshots if the test fails
* @default !browser.ui
*/
screenshotFailures?: boolean;
/**
* Path to the index.html file that will be used to run tests.
*/
testerHtmlPath?: string;
/**
* Scripts injected into the main window.
*/
orchestratorScripts?: BrowserScript[];
/**
* Commands that will be executed on the server
* via the browser `import("vitest/browser").commands` API.
* @see {@link https://vitest.dev/api/browser/commands}
*/
commands?: Record<string, BrowserCommand<any>>;
/**
* Timeout for connecting to the browser
* @default 30000
*/
connectTimeout?: number;
expect?: {
toMatchScreenshot?: { [ComparatorName in keyof ToMatchScreenshotComparators] : {
/**
* The name of the comparator to use for visual diffing.
*
* @defaultValue `'pixelmatch'`
*/
comparatorName?: ComparatorName;
comparatorOptions?: ToMatchScreenshotComparators[ComparatorName];
} }[keyof ToMatchScreenshotComparators] & ToMatchScreenshotOptions;
};
/**
* Enables tracking uncaught errors and exceptions so they can be reported by Vitest.
*
* If you need to hide certain errors, it is recommended to use [`onUnhandledError`](https://vitest.dev/config/#onunhandlederror) option instead.
*
* Disabling this will completely remove all Vitest error handlers, which can help debugging with the "Pause on exceptions" checkbox turned on.
* @default true
*/
trackUnhandledErrors?: boolean;
}
interface BrowserCommandContext {
testPath: string | undefined;
provider: BrowserProvider;
project: TestProject;
sessionId: string;
triggerCommand: <K extends keyof BrowserCommands>(name: K, ...args: Parameters<BrowserCommands[K]>) => ReturnType<BrowserCommands[K]>;
}
interface BrowserServerStateSession {
project: TestProject;
connected: () => void;
fail: (v: Error) => void;
}
interface BrowserOrchestrator {
cleanupTesters: () => Promise<void>;
createTesters: (options: BrowserTesterOptions) => Promise<void>;
onCancel: (reason: CancelReason) => Promise<void>;
$close: () => void;
}
interface BrowserServerState {
orchestrators: Map<string, BrowserOrchestrator>;
}
interface ParentProjectBrowser {
spawn: (project: TestProject) => ProjectBrowser;
vite: ViteDevServer;
}
interface ProjectBrowser {
vite: ViteDevServer;
state: BrowserServerState;
provider: BrowserProvider;
close: () => Promise<void>;
initBrowserProvider: (project: TestProject) => Promise<void>;
parseStacktrace: (stack: string) => ParsedStack[];
parseErrorStacktrace: (error: TestError, options?: StackTraceParserOptions) => ParsedStack[];
registerCommand: <K extends keyof BrowserCommands>(name: K, cb: BrowserCommand<Parameters<BrowserCommands[K]>, ReturnType<BrowserCommands[K]>>) => void;
triggerCommand: <K extends keyof BrowserCommands>(name: K, context: BrowserCommandContext, ...args: Parameters<BrowserCommands[K]>) => ReturnType<BrowserCommands[K]>;
}
interface BrowserCommand<
Payload extends unknown[] = [],
ReturnValue = any
> {
(context: BrowserCommandContext, ...payload: Payload): Awaitable<ReturnValue>;
}
interface BrowserScript {
/**
* If "content" is provided and type is "module", this will be its identifier.
*
* If you are using TypeScript, you can add `.ts` extension here for example.
* @default `injected-${index}.js`
*/
id?: string;
/**
* JavaScript content to be injected. This string is processed by Vite plugins if type is "module".
*
* You can use `id` to give Vite a hint about the file extension.
*/
content?: string;
/**
* Path to the script. This value is resolved by Vite so it can be a node module or a file path.
*/
src?: string;
/**
* If the script should be loaded asynchronously.
*/
async?: boolean;
/**
* Script type.
* @default 'module'
*/
type?: string;
}
interface ResolvedBrowserOptions extends BrowserConfigOptions {
name: string;
enabled: boolean;
headless: boolean;
isolate: boolean;
fileParallelism: boolean;
api: ApiConfig;
ui: boolean;
viewport: {
width: number;
height: number;
};
screenshotFailures: boolean;
locators: {
testIdAttribute: string;
};
trace: {
mode: BrowserTraceViewMode;
tracesDir?: string;
screenshots?: boolean;
snapshots?: boolean;
};
}
type ToMatchScreenshotResolvePath = (data: {
/**
* Path **without** extension, sanitized and relative to the test file.
*
* This comes from the arguments passed to `toMatchScreenshot`; if called
* without arguments this will be the auto-generated name.
*
* @example
* test('calls `onClick`', () => {
* expect(locator).toMatchScreenshot()
* // arg = "calls-onclick-1"
* })
*
* @example
* expect(locator).toMatchScreenshot('foo/bar/baz.png')
* // arg = "foo/bar/baz"
*
* @example
* expect(locator).toMatchScreenshot('../foo/bar/baz.png')
* // arg = "foo/bar/baz"
*/
arg: string;
/**
* Screenshot extension, with leading dot.
*
* This can be set through the arguments passed to `toMatchScreenshot`, but
* the value will fall back to `'.png'` if an unsupported extension is used.
*/
ext: string;
/**
* The instance's browser name.
*/
browserName: string;
/**
* The value of {@linkcode process.platform}.
*/
platform: NodeJS.Platform;
/**
* The value provided to
* {@linkcode https://vitest.dev/config/browser/screenshotdirectory|browser.screenshotDirectory},
* if none is provided, its default value.
*/
screenshotDirectory: string;
/**
* Absolute path to the project's
* {@linkcode https://vitest.dev/config/#root|root}.
*/
root: string;
/**
* Path to the test file, relative to the project's
* {@linkcode https://vitest.dev/config/#root|root}.
*/
testFileDirectory: string;
/**
* The test's filename.
*/
testFileName: string;
/**
* The {@linkcode https://vitest.dev/api/#test|test}'s name, including
* parent {@linkcode https://vitest.dev/api/#describe|describe}, sanitized.
*/
testName: string;
/**
* The value provided to
* {@linkcode https://vitest.dev/config/#attachmentsdir|attachmentsDir},
* if none is provided, its default value.
*/
attachmentsDir: string;
}) => string;
interface ToMatchScreenshotOptions {
/**
* Overrides default reference screenshot path.
*
* @default `${root}/${testFileDirectory}/${screenshotDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}`
*/
resolveScreenshotPath?: ToMatchScreenshotResolvePath;
/**
* Overrides default screenshot path used for diffs.
*
* @default `${root}/${attachmentsDir}/${testFileDirectory}/${testFileName}/${arg}-${browserName}-${platform}${ext}`
*/
resolveDiffPath?: ToMatchScreenshotResolvePath;
}
interface ToMatchScreenshotComparators {}
declare class TestProject {
options?: InitializeProjectOptions | undefined;
/**
* The global Vitest instance.
*/
readonly vitest: Vitest;
/**
* Resolved global configuration. If there are no workspace projects, this will be the same as `config`.
*/
readonly globalConfig: ResolvedConfig;
/**
* Browser instance if the browser is enabled. This is initialized when the tests run for the first time.
*/
browser?: ProjectBrowser;
/**
* Temporary directory for the project. This is unique for each project. Vitest stores transformed content here.
*/
readonly tmpDir: string;
/** @inetrnal */ testFilesList: string[] | null;
private runner;
private closingPromise;
private typecheckFilesList;
private _globalSetups?;
private _provided;
constructor(vitest: Vitest, options?: InitializeProjectOptions | undefined, tmpDir?: string);
/**
* The unique hash of this project. This value is consistent between the reruns.
*
* It is based on the root of the project (not consistent between OS) and its name.
*/
get hash(): string;
/**
* Provide a value to the test context. This value will be available to all tests with `inject`.
*/
provide: <T extends keyof ProvidedContext & string>(key: T, value: ProvidedContext[T]) => void;
/**
* Get the provided context. The project context is merged with the global context.
*/
getProvidedContext(): ProvidedContext;
/**
* Creates a new test specification. Specifications describe how to run tests.
* @param moduleId The file path
*/
createSpecification(moduleId: string, locations?: number[] | undefined, pool?: string): TestSpecification;
toJSON(): SerializedTestProject;
/**
* Vite's dev server instance. Every workspace project has its own server.
*/
get vite(): ViteDevServer;
/**
* Resolved project configuration.
*/
get config(): ResolvedConfig;
/**
* The name of the project or an empty string if not set.
*/
get name(): string;
/**
* The color used when reporting tasks of this project.
*/
get color(): ProjectName["color"];
/**
* Serialized project configuration. This is the config that tests receive.
*/
get serializedConfig(): SerializedConfig;
/**
* Check if this is the root project. The root project is the one that has the root config.
*/
isRootProject(): boolean;
onTestsRerun(cb: OnTestsRerunHandler): void;
/**
* Get all files in the project that match the globs in the config and the filters.
* @param filters String filters to match the test files.
*/
globTestFiles(filters?: string[]): Promise<{
/**
* Test files that match the filters.
*/
testFiles: string[];
/**
* Typecheck test files that match the filters. This will be empty unless `typecheck.enabled` is `true`.
*/
typecheckTestFiles: string[];
}>;
private globAllTestFiles;
isBrowserEnabled(): boolean;
private markTestFile;
/**
* Test if a file matches the test globs. This does the actual glob matching if the test is not cached, unlike `isCachedTestFile`.
*/
matchesTestGlob(moduleId: string, source?: () => string): boolean;
private isInSourceTestCode;
private filterFiles;
private _parentBrowser?;
/**
* Closes the project and all associated resources. This can only be called once; the closing promise is cached until the server restarts.
* If the resources are needed again, create a new project.
*/
close(): Promise<void>;
/**
* Import a file using Vite module runner.
* @param moduleId The ID of the module in Vite module graph
*/
import<T>(moduleId: string): Promise<T>;
private _setHash;
private _serializeOverriddenConfig;
private clearTmpDir;
}
interface SerializedTestProject {
name: string;
serializedConfig: SerializedConfig;
context: ProvidedContext;
}
interface InitializeProjectOptions extends TestProjectInlineConfiguration {
configFile: string | false;
}
interface PoolRunnerInitializer {
readonly name: string;
createPoolWorker: (options: PoolOptions) => PoolWorker;
}
interface PoolOptions {
distPath: string;
project: TestProject;
method: "run" | "collect";
cacheFs?: boolean;
environment: ContextTestEnvironment;
execArgv: string[];
env: Partial<NodeJS.ProcessEnv>;
}
interface PoolWorker {
readonly name: string;
readonly reportMemory?: boolean;
readonly cacheFs?: boolean;
on: (event: string, callback: (arg: any) => void) => void;
off: (event: string, callback: (arg: any) => void) => void;
send: (message: WorkerRequest) => void;
deserialize: (data: unknown) => unknown;
start: () => Promise<void>;
stop: () => Promise<void>;
/**
* This is called on workers that already satisfy certain constraints:
* - The task has the same worker name
* - The task has the same project
*/
canReuse?: (task: PoolTask) => boolean;
}
interface PoolTask {
worker: "forks" | "threads" | "vmForks" | "vmThreads" | (string & {});
project: TestProject;
isolate: boolean;
/**
* Custom `process.env`. All tasks in the same project will reference the same object,
* so modifying it once will modify it for every task.
*/
env: Partial<NodeJS.ProcessEnv>;
/**
* Custom `execArgv`. All tasks in the same project will reference the same array,
* so modifying it once will modify it for every task.
*/
execArgv: string[];
context: WorkerExecuteContext;
memoryLimit: number | null;
}
type WorkerRequest = {
__vitest_worker_request__: true;
} & ({
type: "start";
poolId: number;
workerId: WorkerExecuteContext["workerId"];
options: {
reportMemory: boolean;
};
context: {
environment: WorkerTestEnvironment;
config: SerializedConfig;
pool: string;
};
traces: {
enabled: boolean;
sdkPath?: string;
otelCarrier?: OTELCarrier;
};
} | {
type: "stop";
otelCarrier?: OTELCarrier;
} | {
type: "run";
context: WorkerExecuteContext;
otelCarrier?: OTELCarrier;
} | {
type: "collect";
context: WorkerExecuteContext;
otelCarrier?: OTELCarrier;
} | {
type: "cancel";
});
type WorkerResponse = {
__vitest_worker_response__: true;
} & ({
type: "started";
error?: unknown;
} | {
type: "stopped";
error?: unknown;
} | {
type: "testfileFinished";
usedMemory?: number;
error?: unknown;
});
interface BaseOptions {
isTTY?: boolean;
}
declare abstract class BaseReporter implements Reporter {
start: number;
end: number;
watchFilters?: string[];
failedUnwatchedFiles: TestModule[];
isTTY: boolean;
ctx: Vitest;
renderSucceed: boolean;
protected verbose: boolean;
private _filesInWatchMode;
private _timeStart;
constructor(options?: BaseOptions);
onInit(ctx: Vitest): void;
log(...messages: any): void;
error(...messages: any): void;
relative(path: string): string;
onTestRunStart(_specifications: ReadonlyArray<TestSpecification>): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, _reason: TestRunEndReason): void;
onTestCaseResult(testCase: TestCase): void;
onTestSuiteResult(testSuite: TestSuite): void;
onTestModuleEnd(testModule: TestModule): void;
private logFailedTask;
protected printTestModule(testModule: TestModule): void;
protected printTestCase(moduleState: TestModuleState, test: TestCase): void;
private getModuleLog;
protected printTestSuite(testSuite: TestSuite): void;
protected getTestName(test: Task, _separator?: string): string;
protected getFullName(test: Task, separator?: string): string;
protected getTestIndentation(test: Task): string;
protected printAnnotations(test: TestCase, console: "log" | "error", padding?: number): void;
protected getEntityPrefix(entity: TestCase | TestModule | TestSuite): string;
protected getTestCaseSuffix(testCase: TestCase): string;
protected getStateSymbol(test: TestCase | TestModule | TestSuite): string;
private getDurationPrefix;
onWatcherStart(files?: File[], errors?: unknown[]): void;
onWatcherRerun(files: string[], trigger?: string): void;
onUserConsoleLog(log: UserConsoleLog, taskState?: TestResult["state"]): void;
onTestRemoved(trigger?: string): void;
shouldLog(log: UserConsoleLog, taskState?: TestResult["state"]): boolean;
onServerRestart(reason?: string): void;
reportSummary(files: File[], errors: unknown[]): void;
reportTestSummary(files: File[], errors: unknown[]): void;
private printImportsBreakdown;
private importDurationTime;
private ellipsisPath;
private printErrorsSummary;
reportBenchmarkSummary(files: File[]): void;
private printTaskErrors;
}
interface DefaultReporterOptions extends BaseOptions {
summary?: boolean;
}
declare class DefaultReporter extends BaseReporter {
private options;
private summary?;
constructor(options?: DefaultReporterOptions);
onTestRunStart(specifications: ReadonlyArray<TestSpecification>): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason): void;
onTestModuleQueued(file: TestModule): void;
onTestModuleCollected(module: TestModule): void;
onTestModuleEnd(module: TestModule): void;
onTestCaseReady(test: TestCase): void;
onTestCaseResult(test: TestCase): void;
onHookStart(hook: ReportedHookContext): void;
onHookEnd(hook: ReportedHookContext): void;
onInit(ctx: Vitest): void;
}
interface GithubActionsReporterOptions {
onWritePath?: (path: string) => string;
/**
* @default true
*/
displayAnnotations?: boolean;
}
declare class GithubActionsReporter implements Reporter {
ctx: Vitest;
options: GithubActionsReporterOptions;
constructor(options?: GithubActionsReporterOptions);
onInit(ctx: Vitest): void;
onTestCaseAnnotate(testCase: TestCase, annotation: TestAnnotation): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>): void;
}
interface HTMLOptions {
outputFile?: string;
}
type Status = "passed" | "failed" | "skipped" | "pending" | "todo" | "disabled";
type Milliseconds = number;
interface Callsite {
line: number;
column: number;
}
interface JsonAssertionResult {
ancestorTitles: Array<string>;
fullName: string;
status: Status;
title: string;
meta: TaskMeta;
duration?: Milliseconds | null;
failureMessages: Array<string> | null;
location?: Callsite | null;
}
interface JsonTestResult {
message: string;
name: string;
status: "failed" | "passed";
startTime: number;
endTime: number;
assertionResults: Array<JsonAssertionResult>;
}
interface JsonTestResults {
numFailedTests: number;
numFailedTestSuites: number;
numPassedTests: number;
numPassedTestSuites: number;
numPendingTests: number;
numPendingTestSuites: number;
numTodoTests: number;
numTotalTests: number;
numTotalTestSuites: number;
startTime: number;
success: boolean;
testResults: Array<JsonTestResult>;
snapshot: SnapshotSummary;
coverageMap?: CoverageMap | null | undefined;
}
interface JsonOptions {
outputFile?: string;
}
declare class JsonReporter implements Reporter {
start: number;
ctx: Vitest;
options: JsonOptions;
coverageMap?: CoverageMap;
constructor(options: JsonOptions);
onInit(ctx: Vitest): void;
onCoverage(coverageMap: unknown): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>): Promise<void>;
/**
* Writes the report to an output file if specified in the config,
* or logs it to the console otherwise.
* @param report
*/
writeReport(report: string): Promise<void>;
}
interface ClassnameTemplateVariables {
filename: string;
filepath: string;
}
interface JUnitOptions {
outputFile?: string;
/**
* Template for the classname attribute. Can be either a string or a function. The string can contain placeholders {filename} and {filepath}.
*/
classnameTemplate?: string | ((classnameVariables: ClassnameTemplateVariables) => string);
suiteName?: string;
/**
* Write <system-out> and <system-err> for console output
* @default true
*/
includeConsoleOutput?: boolean;
/**
* Add <testcase file="..."> attribute (validated on CIRCLE CI and GitLab CI)
* @default false
*/
addFileAttribute?: boolean;
}
declare class JUnitReporter implements Reporter {
private ctx;
private reportFile?;
private baseLog;
private logger;
private _timeStart;
private fileFd?;
private options;
constructor(options: JUnitOptions);
onInit(ctx: Vitest): Promise<void>;
writeElement(name: string, attrs: Record<string, any>, children: () => Promise<void>): Promise<void>;
writeLogs(task: Task, type: "err" | "out"): Promise<void>;
writeTasks(tasks: Task[], filename: string): Promise<void>;
onTestRunEnd(testModules: ReadonlyArray<TestModule>): Promise<void>;
}
declare class DotReporter extends BaseReporter {
private renderer?;
private tests;
private finishedTests;
onInit(ctx: Vitest): void;
printTestModule(): void;
onWatcherRerun(files: string[], trigger?: string): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason): void;
onTestModuleCollected(module: TestModule): void;
onTestCaseReady(test: TestCase): void;
onTestCaseResult(test: TestCase): void;
onTestModuleEnd(testModule: TestModule): void;
private createSummary;
}
declare class HangingProcessReporter implements Reporter {
whyRunning: (() => void) | undefined;
onInit(): void;
onProcessTimeout(): void;
}
declare class TapReporter implements Reporter {
protected ctx: Vitest;
private logger;
onInit(ctx: Vitest): void;
static getComment(task: Task): string;
private logErrorDetails;
protected logTasks(tasks: Task[]): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>): void;
}
declare class TapFlatReporter extends TapReporter {
onInit(ctx: Vitest): void;
onTestRunEnd(testModules: ReadonlyArray<TestModule>): void;
}
declare class TreeReporter extends DefaultReporter {
protected verbose: boolean;
renderSucceed: boolean;
}
declare class VerboseReporter extends DefaultReporter {
protected verbose: boolean;
renderSucceed: boolean;
printTestModule(_module: TestModule): void;
onTestCaseResult(test: TestCase): void;
}
type FormattedBenchmarkResult = BenchmarkResult & {
id: string;
};
declare function renderTable(options: {
tasks: Task[];
level: number;
shallow?: boolean;
showHeap: boolean;
columns: number;
slowTestThreshold: number;
compare?: Record<Task["id"], FormattedBenchmarkResult>;
}): string;
declare class BenchmarkReporter extends DefaultReporter {
compare?: Parameters<typeof renderTable>[0]["compare"];
onInit(ctx: Vitest): Promise<void>;
onTaskUpdate(packs: TaskResultPack[]): void;
onTestSuiteResult(testSuite: TestSuite): void;
protected printTestModule(testModule: TestModule): void;
private printSuiteTable;
onTestRunEnd(testModules: ReadonlyArray<TestModule>, unhandledErrors: ReadonlyArray<SerializedError>, reason: TestRunEndReason): Promise<void>;
}
declare class VerboseBenchmarkReporter extends BenchmarkReporter {
protected verbose: boolean;
}
declare const BenchmarkReportsMap: {
default: typeof BenchmarkReporter;
verbose: typeof VerboseBenchmarkReporter;
};
type BenchmarkBuiltinReporters = keyof typeof BenchmarkReportsMap;
declare const ReportersMap: {
default: typeof DefaultReporter;
blob: typeof BlobReporter;
verbose: typeof VerboseReporter;
dot: typeof DotReporter;
json: typeof JsonReporter;
tap: typeof TapReporter;
"tap-flat": typeof TapFlatReporter;
junit: typeof JUnitReporter;
tree: typeof TreeReporter;
"hanging-process": typeof HangingProcessReporter;
"github-actions": typeof GithubActionsReporter;
};
type BuiltinReporters = keyof typeof ReportersMap;
interface BuiltinReporterOptions {
"default": DefaultReporterOptions;
"verbose": DefaultReporterOptions;
"dot": BaseOptions;
"tree": BaseOptions;
"json": JsonOptions;
"blob": BlobOptions;
"tap": never;
"tap-flat": never;
"junit": JUnitOptions;
"hanging-process": never;
"html": HTMLOptions;
"github-actions": GithubActionsReporterOptions;
}
interface TestSequencer {
/**
* Slicing tests into shards. Will be run before `sort`.
* Only run, if `shard` is defined.
*/
shard: (files: TestSpecification[]) => Awaitable<TestSpecification[]>;
sort: (files: TestSpecification[]) => Awaitable<TestSpecification[]>;
}
interface TestSequencerConstructor {
new (ctx: Vitest): TestSequencer;
}
interface BenchmarkUserOptions {
/**
* Include globs for benchmark test files
*
* @default ['**\/*.{bench,benchmark}.?(c|m)[jt]s?(x)']
*/
include?: string[];
/**
* Exclude globs for benchmark test files
* @default ['**\/node_modules/**', '**\/dist/**', '**\/cypress/**', '**\/.{idea,git,cache,output,temp}/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*']
*/
exclude?: string[];
/**
* Include globs for in-source benchmark test files
*
* @default []
*/
includeSource?: string[];
/**
* Custom reporter for output. Can contain one or more built-in report names, reporter instances,
* and/or paths to custom reporters
*
* @default ['default']
*/
reporters?: Arrayable<BenchmarkBuiltinReporters | Reporter>;
/**
* @deprecated Use `benchmark.outputJson` instead
*/
outputFile?: string | (Partial<Record<BenchmarkBuiltinReporters, string>> & Record<string, string>);
/**
* benchmark output file to compare against
*/
compare?: string;
/**
* benchmark output file
*/
outputJson?: string;
/**
* Include `samples` array of benchmark results for API or custom reporter usages.
* This is disabled by default to reduce memory usage.
* @default false
*/
includeSamples?: boolean;
}
type BuiltinEnvironment = "node" | "jsdom" | "happy-dom" | "edge-runtime";
type VitestEnvironment = BuiltinEnvironment | (string & Record<never, never>);
type CSSModuleScopeStrategy = "stable" | "scoped" | "non-scoped";
type ApiConfig = Pick<ServerOptions, "port" | "strictPort" | "host" | "middlewareMode">;
interface EnvironmentOptions {
/**
* jsdom options.
*/
jsdom?: JSDOMOptions;
happyDOM?: HappyDOMOptions;
[x: string]: unknown;
}
type VitestRunMode = "test" | "benchmark";
interface ProjectName {
label: string;
color?: LabelColor;
}
interface SequenceOptions {
/**
* Class that handles sorting and sharding algorithm.
* If you only need to change sorting, you can extend
* your custom sequencer from `BaseSequencer` from `vitest/node`.
* @default BaseSequencer
*/
sequencer?: TestSequencerConstructor;
/**
* Controls the order in which this project runs its tests when using multiple [projects](/guide/projects).
*
* - Projects with the same group order number will run together, and groups are run from lowest to highest.
* - If you don’t set this option, all projects run in parallel.
* - If several projects use the same group order, they will run at the same time.
* @default 0
*/
groupOrder?: number;
/**
* Should files and tests run in random order.
* @default false
*/
shuffle?: boolean | {
/**
* Should files run in random order. Long running tests will not start
* earlier if you enable this option.
* @default false
*/
files?: boolean;
/**
* Should tests run in random order.
* @default false
*/
tests?: boolean;
};
/**
* Should tests run in parallel.
* @default false
*/
concurrent?: boolean;
/**
* Defines how setup files should be ordered
* - 'parallel' will run all setup files in parallel
* - 'list' will run all setup files in the order they are defined in the config file
* @default 'parallel'
*/
setupFiles?: SequenceSetupFiles;
/**
* Seed for the random number generator.
* @default Date.now()
*/
seed?: number;
/**
* Defines how hooks should be ordered
* - `stack` will order "after" hooks in reverse order, "before" hooks will run sequentially
* - `list` will order hooks in the order they are defined
* - `parallel` will run hooks in a single group in parallel
* @default 'stack'
*/
hooks?: SequenceHooks;
}
type DepsOptimizationOptions = Omit<DepOptimizationConfig, "disabled" | "noDiscovery"> & {
enabled?: boolean;
};
interface DepsOptions {
/**
* Enable dependency optimization. This can improve the performance of your tests.
*/
optimizer?: Partial<Record<"client" | "ssr" | ({} & string), DepsOptimizationOptions>>;
web?: {
/**
* Should Vitest process assets (.png, .svg, .jpg, etc) files and resolve them like Vite does in the browser.
*
* These module will have a default export equal to the path to the asset, if no query is specified.
*
* **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
*
* @default true
*/
transformAssets?: boolean;
/**
* Should Vitest process CSS (.css, .scss, .sass, etc) files and resolve them like Vite does in the browser.
*
* If CSS files are disabled with `css` options, this option will just silence UNKNOWN_EXTENSION errors.
*
* **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
*
* @default true
*/
transformCss?: boolean;
/**
* Regexp pattern to match external files that should be transformed.
*
* By default, files inside `node_modules` are externalized and not transformed.
*
* **At the moment, this option only works with `{ pool: 'vmThreads' }`.**
*
* @default []
*/
transformGlobPattern?: RegExp | RegExp[];
};
/**
* Interpret CJS module's default as named exports
*
* @default true
*/
interopDefault?: boolean;
/**
* A list of directories relative to the config file that should be treated as module directories.
*
* @default ['node_modules']
*/
moduleDirectories?: string[];
}
type InlineReporter = Reporter;
type ReporterName = BuiltinReporters | "html" | (string & {});
type ReporterWithOptions<Name extends ReporterName = ReporterName> = Name extends keyof BuiltinReporterOptions ? BuiltinReporterOptions[Name] extends never ? [Name, object] : [Name, Partial<BuiltinReporterOptions[Name]>] : [Name, Record<string, unknown>];
interface ResolveSnapshotPathHandlerContext {
config: SerializedConfig;
}
type ResolveSnapshotPathHandler = (testPath: string, snapExtension: string, context: ResolveSnapshotPathHandlerContext) => string;
type BuiltinPool = "browser" | "threads" | "forks" | "vmThreads" | "vmForks" | "typescript";
type Pool = BuiltinPool | (string & {});
interface InlineConfig {
/**
* Name of the project. Will be used to display in the reporter.
*/
name?: string | ProjectName;
/**
* Benchmark options.
*
* @default {}
*/
benchmark?: BenchmarkUserOptions;
/**
* A list of [glob patterns](https://superchupu.dev/tinyglobby/comparison) that match your test files.
*
* @default ['**\/*.{test,spec}.?(c|m)[jt]s?(x)']
* @see {@link https://vitest.dev/config/include}
*/
include?: string[];
/**
* Exclude globs for test files
* @default ['**\/node_modules/**', '**\/.git/**']
*/
exclude?: string[];
/**
* Include globs for in-source test files
*
* @default []
*/
includeSource?: string[];
/**
* Handling for dependencies inlining or externalizing
*
*/
deps?: DepsOptions;
server?: {
deps?: ServerDepsOptions;
debug?: {
/**
* The folder where Vitest stores the contents of transformed
* test files that can be inspected manually.
*
* If `true`, Vitest dumps the files in `.vitest-dump` folder relative to the root of the project.
*
* You can also use `VITEST_DEBUG_DUMP` env variable to enable this.
*/
dump?: string | true;
/**
* If dump is enabled, should Vitest load the files from there instead of transforming them.
*
* You can also use `VITEST_DEBUG_LOAD_DUMP` env variable to enable this.
*/
load?: boolean;
};
};
/**
* Base directory to scan for the test files
*
* @default `config.root`
*/
dir?: string;
/**
* Register apis globally
*
* @default false
*/
globals?: boolean;
/**
* Running environment
*
* Supports 'node', 'jsdom', 'happy-dom', 'edge-runtime'
*
* If used unsupported string, will try to load the package `vitest-environment-${env}`
*
* @default 'node'
*/
environment?: VitestEnvironment;
/**
* Environment options.
*/
environmentOptions?: EnvironmentOptions;
/**
* Run tests in an isolated environment. This option has no effect on vmThreads pool.
*
* Disabling this option improves performance if your code doesn't rely on side effects.
*
* @default true
*/
isolate?: boolean;
/**
* Pass additional arguments to `node` process when spawning the worker.
*
* See [Command-line API | Node.js](https://nodejs.org/docs/latest/api/cli.html) for more information.
*
* Set to `process.execArgv` to pass all arguments of the current process.
*
* Be careful when using, it as some options may crash worker, e.g. --prof, --title. See https://github.com/nodejs/node/issues/41103
*
* @default [] // no execution arguments are passed
*/
execArgv?: string[];
/**
* Specifies the memory limit for `worker_thread` or `child_process` before they are recycled.
* If you see memory leaks, try to tinker this value.
*/
vmMemoryLimit?: string | number;
/**
* Pool used to run tests in.
*
* Supports 'threads', 'forks', 'vmThreads', 'vmForks'
*
* @default 'forks'
*/
pool?: Exclude<Pool, "browser"> | PoolRunnerInitializer;
/**
* Maximum number or percentage of workers to run tests in.
*/
maxWorkers?: number | string;
/**
* Should all test files run in parallel. Doesn't affect tests running in the same file.
* Setting this to `false` will override `maxWorkers` option to `1`.
*
* @default true
*/
fileParallelism?: boolean;
/**
* Options for projects
*/
projects?: TestProjectConfiguration[];
/**
* Update snapshot
*
* @default false
*/
update?: boolean;
/**
* Watch mode
*
* @default !process.env.CI
*/
watch?: boolean;
/**
* Project root
*
* @default process.cwd()
*/
root?: string;
/**
* Custom reporter for output. Can contain one or more built-in report names, reporter instances,
* and/or paths to custom reporters.
*
* @default []
*/
reporters?: Arrayable<ReporterName | InlineReporter> | ((ReporterName | InlineReporter) | [ReporterName] | ReporterWithOptions)[];
/**
* Write test results to a file when the --reporter=json` or `--reporter=junit` option is also specified.
* Also definable individually per reporter by using an object instead.
*/
outputFile?: string | (Partial<Record<BuiltinReporters, string>> & Record<string, string>);
/**
* Default timeout of a test in milliseconds
*
* @default 5000
*/
testTimeout?: number;
/**
* Default timeout of a hook in milliseconds
*
* @default 10000
*/
hookTimeout?: number;
/**
* Default timeout to wait for close when Vitest shuts down, in milliseconds
*
* @default 10000
*/
teardownTimeout?: number;
/**
* Silent mode
*
* Use `'passed-only'` to see logs from failing tests only.
*
* @default false
*/
silent?: boolean | "passed-only";
/**
* Hide logs for skipped tests
*
* @default false
*/
hideSkippedTests?: boolean;
/**
* Path to setup files
*/
setupFiles?: string | string[];
/**
* Path to global setup files
*/
globalSetup?: string | string[];
/**
* Glob pattern of file paths that will trigger the whole suite rerun
*
* Useful if you are testing calling CLI commands
*
* @default ['**\/package.json/**', '**\/{vitest,vite}.config.*\/**']
*/
forceRerunTriggers?: string[];
/**
* Pattern configuration to rerun only the tests that are affected
* by the changes of specific files in the repository.
*/
watchTriggerPatterns?: WatcherTriggerPattern[];
/**
* Coverage options
*/
coverage?: CoverageOptions;
/**
* run test names with the specified pattern
*/
testNamePattern?: string | RegExp;
/**
* Will call `.mockClear()` on all spies before each test
* @default false
*/
clearMocks?: boolean;
/**
* Will call `.mockReset()` on all spies before each test
* @default false
*/
mockReset?: boolean;
/**
* Will call `.mockRestore()` on all spies before each test
* @default false
*/
restoreMocks?: boolean;
/**
* Will restore all global stubs to their original values before each test
* @default false
*/
unstubGlobals?: boolean;
/**
* Will restore all env stubs to their original values before each test
* @default false
*/
unstubEnvs?: boolean;
/**
* Serve API options.
*
* When set to true, the default port is 51204.
*
* @default false
*/
api?: boolean | number | ApiConfig;
/**
* Enable Vitest UI
*
* @default false
*/
ui?: boolean;
/**
* options for test in a browser environment
*
* @default false
*/
browser?: BrowserConfigOptions;
/**
* Open UI automatically.
*
* @default !process.env.CI
*/
open?: boolean;
/**
* Base url for the UI
*
* @default '/__vitest__/'
*/
uiBase?: string;
/**
* Format options for snapshot testing.
*/
snapshotFormat?: Omit<PrettyFormatOptions, "plugins" | "compareKeys"> & {
compareKeys?: null | undefined;
};
/**
* Path to a module which has a default export of diff config.
*/
diff?: string | SerializedDiffOptions;
/**
* Paths to snapshot serializer modules.
*/
snapshotSerializers?: string[];
/**
* Resolve custom snapshot path
*/
resolveSnapshotPath?: ResolveSnapshotPathHandler;
/**
* Path to a custom snapshot environment module that has a default export of `SnapshotEnvironment` object.
*/
snapshotEnvironment?: string;
/**
* Pass with no tests
*/
passWithNoTests?: boolean;
/**
* Allow tests and suites that are marked as only
*
* @default !process.env.CI
*/
allowOnly?: boolean;
/**
* Show heap usage after each test. Useful for debugging memory leaks.
*/
logHeapUsage?: boolean;
/**
* Custom environment variables assigned to `process.env` before running tests.
*/
env?: Partial<NodeJS.ProcessEnv>;
/**
* Options for @sinon/fake-timers
*/
fakeTimers?: FakeTimerInstallOpts;
/**
* Custom handler for console.log in tests.
*
* Return `false` to ignore the log.
*/
onConsoleLog?: (log: string, type: "stdout" | "stderr", entity: TestModule | TestCase | TestSuite | undefined) => boolean | void;
/**
* Enable stack trace filtering. If absent, all stack trace frames
* will be shown.
*
* Return `false` to omit the frame.
*/
onStackTrace?: (error: TestError, frame: ParsedStack) => boolean | void;
/**
* A callback that can return `false` to ignore an unhandled error
*/
onUnhandledError?: OnUnhandledErrorCallback;
/**
* Indicates if CSS files should be processed.
*
* When excluded, the CSS files will be replaced with empty strings to bypass the subsequent processing.
*
* @default { include: [], modules: { classNameStrategy: false } }
*/
css?: boolean | {
include?: RegExp | RegExp[];
exclude?: RegExp | RegExp[];
modules?: {
classNameStrategy?: CSSModuleScopeStrategy;
};
};
/**
* A number of tests that are allowed to run at the same time marked with `test.concurrent`.
* @default 5
*/
maxConcurrency?: number;
/**
* Options for configuring cache policy.
* @default { dir: 'node_modules/.vite/vitest/{project-hash}' }
*/
cache?: false | {
/**
* @deprecated Use Vite's "cacheDir" instead if you want to change the cache director. Note caches will be written to "cacheDir\/vitest".
*/
dir: string;
};
/**
* Options for configuring the order of running tests.
*/
sequence?: SequenceOptions;
/**
* Specifies an `Object`, or an `Array` of `Object`,
* which defines aliases used to replace values in `import` or `require` statements.
* Will be merged with the default aliases inside `resolve.alias`.
*/
alias?: AliasOptions;
/**
* Ignore any unhandled errors that occur
*
* @default false
*/
dangerouslyIgnoreUnhandledErrors?: boolean;
/**
* Options for configuring typechecking test environment.
*/
typecheck?: Partial<TypecheckConfig>;
/**
* The number of milliseconds after which a test is considered slow and reported as such in the results.
*
* @default 300
*/
slowTestThreshold?: number;
/**
* Path to a custom test runner.
*/
runner?: string;
/**
* Debug tests by opening `node:inspector` in worker / child process.
* Provides similar experience as `--inspect` Node CLI argument.
*
* Requires `fileParallelism: false`.
*/
inspect?: boolean | string;
/**
* Debug tests by opening `node:inspector` in worker / child process and wait for debugger to connect.
* Provides similar experience as `--inspect-brk` Node CLI argument.
*
* Requires `fileParallelism: false`.
*/
inspectBrk?: boolean | string;
/**
* Inspector options. If `--inspect` or `--inspect-brk` is enabled, these options will be passed to the inspector.
*/
inspector?: {
/**
* Enable inspector
*/
enabled?: boolean;
/**
* Port to run inspector on
*/
port?: number;
/**
* Host to run inspector on
*/
host?: string;
/**
* Wait for debugger to connect before running tests
*/
waitForDebugger?: boolean;
};
/**
* Define variables that will be returned from `inject` in the test environment.
* @example
* ```ts
* // vitest.config.ts
* export default defineConfig({
* test: {
* provide: {
* someKey: 'someValue'
* }
* }
* })
* ```
* ```ts
* // test file
* import { inject } from 'vitest'
* const value = inject('someKey') // 'someValue'
* ```
*/
provide?: Partial<ProvidedContext>;
/**
* Configuration options for expect() matches.
*/
expect?: {
/**
* Throw an error if tests don't have any expect() assertions.
*/
requireAssertions?: boolean;
/**
* Default options for expect.poll()
*/
poll?: {
/**
* Timeout in milliseconds
* @default 1000
*/
timeout?: number;
/**
* Polling interval in milliseconds
* @default 50
*/
interval?: number;
};
};
/**
* Modify default Chai config. Vitest uses Chai for `expect` and `assert` matches.
* https://github.com/chaijs/chai/blob/4.x.x/lib/chai/config.js
*/
chaiConfig?: ChaiConfig;
/**
* Stop test execution when given number of tests have failed.
*/
bail?: number;
/**
* Retry the test specific number of times if it fails.
*
* @default 0
*/
retry?: number;
/**
* Show full diff when snapshot fails instead of a patch.
*/
expandSnapshotDiff?: boolean;
/**
* By default, Vitest automatically intercepts console logging during tests for extra formatting of test file, test title, etc...
* This is also required for console log preview on Vitest UI.
* However, disabling such interception might help when you want to debug a code with normal synchronous terminal console logging.
*
* This option has no effect on browser pool since Vitest preserves original logging on browser devtools.
*
* @default false
*/
disableConsoleIntercept?: boolean;
/**
* Always print console stack traces.
*
* @default false
*/
printConsoleTrace?: boolean;
/**
* Include "location" property inside the test definition
*
* @default false
*/
includeTaskLocation?: boolean;
/**
* Directory path for storing attachments created by `context.annotate`
*
* @default '.vitest-attachments'
*/
attachmentsDir?: string;
/**
* Experimental features
*
* @experimental
*/
experimental?: {
/**
* Enable caching of modules on the file system between reruns.
*/
fsModuleCache?: boolean;
/**
* Path relative to the root of the project where the fs module cache will be stored.
* @default node_modules/.experimental-vitest-cache
*/
fsModuleCachePath?: string;
/**
* {@link https://vitest.dev/guide/open-telemetry}
*/
openTelemetry?: {
enabled: boolean;
sdkPath?: string;
browserSdkPath?: string;
};
/**
* Show imports (top 10) that take a long time.
*
* Enabling this will also show a breakdown by default in UI, but you can always press a button to toggle it.
*/
printImportBreakdown?: boolean;
};
}
interface TypecheckConfig {
/**
* Run typechecking tests alongside regular tests.
*/
enabled?: boolean;
/**
* When typechecking is enabled, only run typechecking tests.
*/
only?: boolean;
/**
* What tools to use for type checking.
*
* @default 'tsc'
*/
checker: "tsc" | "vue-tsc" | (string & Record<never, never>);
/**
* Pattern for files that should be treated as test files
*
* @default ['**\/*.{test,spec}-d.?(c|m)[jt]s?(x)']
*/
include: string[];
/**
* Pattern for files that should not be treated as test files
*
* @default ['**\/node_modules/**', '**\/dist/**', '**\/cypress/**', '**\/.{idea,git,cache,output,temp}/**', '**\/{karma,rollup,webpack,vite,vitest,jest,ava,babel,nyc,cypress,tsup,build,eslint,prettier}.config.*']
*/
exclude: string[];
/**
* Check JS files that have `@ts-check` comment.
* If you have it enabled in tsconfig, this will not overwrite it.
*/
allowJs?: boolean;
/**
* Do not fail, if Vitest found errors outside the test files.
*/
ignoreSourceErrors?: boolean;
/**
* Path to tsconfig, relative to the project root.
*/
tsconfig?: string;
/**
* Minimum time in milliseconds it takes to spawn the typechecker.
* @default 10_000
*/
spawnTimeout?: number;
}
interface UserConfig extends InlineConfig {
/**
* Path to the config file.
*
* Default resolving to `vitest.config.*`, `vite.config.*`
*
* Setting to `false` will disable config resolving.
*/
config?: string | false | undefined;
/**
* Do not run tests when Vitest starts.
*
* Vitest will only run tests if it's called programmatically or the test file changes.
*
* If CLI file filters are passed, standalone mode is ignored.
*/
standalone?: boolean;
/**
* Use happy-dom
*/
dom?: boolean;
/**
* Run tests that cover a list of source files
*/
related?: string[] | string;
/**
* Overrides Vite mode
* @default 'test'
*/
mode?: string;
/**
* Runs tests that are affected by the changes in the repository, or between specified branch or commit hash
* Requires initialized git repository
* @default false
*/
changed?: boolean | string;
/**
* Test suite shard to execute in a format of <index>/<count>.
* Will divide tests into a `count` numbers, and run only the `indexed` part.
* Cannot be used with enabled watch.
* @example --shard=2/3
*/
shard?: string;
/**
* Name of the project or projects to run.
*/
project?: string | string[];
/**
* Additional exclude patterns
*/
cliExclude?: string[];
/**
* Override vite config's clearScreen from cli
*/
clearScreen?: boolean;
/**
* benchmark.compare option exposed at the top level for cli
*/
compare?: string;
/**
* benchmark.outputJson option exposed at the top level for cli
*/
outputJson?: string;
/**
* Directory of blob reports to merge
* @default '.vitest-reports'
*/
mergeReports?: string;
/**
* Delete all Vitest caches, including `experimental.fsModuleCache`.
* @experimental
*/
clearCache?: boolean;
}
type OnUnhandledErrorCallback = (error: (TestError | Error) & {
type: string;
}) => boolean | void;
interface ResolvedConfig extends Omit<Required<UserConfig>, "project" | "config" | "filters" | "browser" | "coverage" | "testNamePattern" | "related" | "api" | "reporters" | "resolveSnapshotPath" | "benchmark" | "shard" | "cache" | "sequence" | "typecheck" | "runner" | "pool" | "cliExclude" | "diff" | "setupFiles" | "snapshotEnvironment" | "bail" | "name" | "vmMemoryLimit" | "fileParallelism"> {
mode: VitestRunMode;
name: ProjectName["label"];
color?: ProjectName["color"];
base?: string;
diff?: string | SerializedDiffOptions;
bail?: number;
setupFiles: string[];
snapshotEnvironment?: string;
config?: string;
filters?: string[];
testNamePattern?: RegExp;
related?: string[];
coverage: ResolvedCoverageOptions;
snapshotOptions: SnapshotStateOptions;
browser: ResolvedBrowserOptions;
pool: Pool;
poolRunner?: PoolRunnerInitializer;
reporters: (InlineReporter | ReporterWithOptions)[];
defines: Record<string, any>;
viteDefine: Record<string, any>;
api: ApiConfig & {
token: string;
};
cliExclude?: string[];
project: string[];
benchmark?: Required<Omit<BenchmarkUserOptions, "outputFile" | "compare" | "outputJson">> & Pick<BenchmarkUserOptions, "outputFile" | "compare" | "outputJson">;
shard?: {
index: number;
count: number;
};
cache: {
/**
* @deprecated
*/
dir: string;
} | false;
sequence: {
sequencer: TestSequencerConstructor;
hooks: SequenceHooks;
setupFiles: SequenceSetupFiles;
shuffle?: boolean;
concurrent?: boolean;
seed: number;
groupOrder: number;
};
typecheck: Omit<TypecheckConfig, "enabled"> & {
enabled: boolean;
};
runner?: string;
maxWorkers: number;
vmMemoryLimit?: UserConfig["vmMemoryLimit"];
dumpDir?: string;
}
type NonProjectOptions = "shard" | "watch" | "run" | "cache" | "update" | "reporters" | "outputFile" | "teardownTimeout" | "silent" | "forceRerunTriggers" | "testNamePattern" | "ui" | "open" | "uiBase" | "snapshotFormat" | "resolveSnapshotPath" | "passWithNoTests" | "onConsoleLog" | "onStackTrace" | "dangerouslyIgnoreUnhandledErrors" | "slowTestThreshold" | "inspect" | "inspectBrk" | "coverage" | "watchTriggerPatterns";
interface ServerDepsOptions {
/**
* Externalize means that Vite will bpass the package to native Node.
*
* Externalized dependencies will not be applied Vite's transformers and resolvers.
* And does not support HMR on reload.
*
* Typically, packages under `node_modules` are externalized.
*/
external?: (string | RegExp)[];
/**
* Vite will process inlined modules.
*
* This could be helpful to handle packages that ship `.js` in ESM format (that Node can't handle).
*
* If `true`, every dependency will be inlined
*/
inline?: (string | RegExp)[] | true;
/**
* Try to guess the CJS version of a package when it's invalid ESM
* @default false
*/
fallbackCJS?: boolean;
}
type ProjectConfig = Omit<InlineConfig, NonProjectOptions | "sequencer" | "deps"> & {
mode?: string;
sequencer?: Omit<SequenceOptions, "sequencer" | "seed">;
deps?: Omit<DepsOptions, "moduleDirectories">;
};
type ResolvedProjectConfig = Omit<ResolvedConfig, Exclude<NonProjectOptions, "coverage" | "watch">>;
interface UserWorkspaceConfig extends UserConfig$1 {
test?: ProjectConfig;
}
type UserProjectConfigFn = (env: ConfigEnv) => UserWorkspaceConfig | Promise<UserWorkspaceConfig>;
type UserProjectConfigExport = UserWorkspaceConfig | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
type TestProjectInlineConfiguration = (UserWorkspaceConfig & {
/**
* Relative path to the extendable config. All other options will be merged with this config.
* If `true`, the project will inherit all options from the root config.
* @example '../vite.config.ts'
*/
extends?: string | true;
});
type TestProjectConfiguration = string | TestProjectInlineConfiguration | Promise<UserWorkspaceConfig> | UserProjectConfigFn;
export { CoverageMap as C, TestSuite as K, Logger as L, experimental_getRunnerTask as Q, TestProject as T, Vitest as V, BenchmarkReporter as aE, BenchmarkReportsMap as aF, DefaultReporter as aG, DotReporter as aH, GithubActionsReporter as aI, HangingProcessReporter as aJ, JsonReporter as aK, JUnitReporter as aL, ReportersMap as aM, TapFlatReporter as aN, TapReporter as aO, VerboseBenchmarkReporter as aP, VerboseReporter as aQ, BaseReporter as aR, TestSpecification as k, VitestPackageInstaller as p, TestCase as v, TestCollection as w, TestModule as y };
export type { BrowserCommand as $, ApiConfig as A, TestResult as B, TestResultFailed as D, TestResultPassed as E, TestResultSkipped as F, TestState as G, HTMLOptions as H, InlineConfig as I, JsonOptions as J, ModuleDiagnostic as M, TestSuiteState as N, OnServerRestartHandler as O, PoolWorker as P, ResolvedCoverageOptions as R, SerializedTestProject as S, UserWorkspaceConfig as U, WatcherTriggerPattern as W, TestSequencerConstructor as X, BenchmarkUserOptions as Y, BrowserBuiltinProvider as Z, _BrowserNames as _, ReportContext as a, BrowserCommandContext as a0, BrowserConfigOptions as a1, BrowserInstanceOption as a2, BrowserModuleMocker as a3, BrowserOrchestrator as a4, BrowserProvider as a5, BrowserProviderOption as a6, BrowserScript as a7, BrowserServerFactory as a8, BrowserServerOptions as a9, TestRunResult as aA, ReportedHookContext as aB, Reporter as aC, TestRunEndReason as aD, BenchmarkBuiltinReporters as aS, BuiltinReporterOptions as aT, BuiltinReporters as aU, JsonAssertionResult as aV, JsonTestResult as aW, JsonTestResults as aX, BrowserServerState as aa, BrowserServerStateSession as ab, CDPSession as ac, ParentProjectBrowser as ad, ProjectBrowser as ae, ResolvedBrowserOptions as af, ToMatchScreenshotComparators as ag, ToMatchScreenshotOptions as ah, BuiltinEnvironment as ai, CSSModuleScopeStrategy as aj, DepsOptimizationOptions as ak, EnvironmentOptions as al, Pool as am, ProjectConfig as an, ResolvedProjectConfig as ao, ResolveSnapshotPathHandler as ap, ResolveSnapshotPathHandlerContext as aq, TypecheckConfig as ar, VitestEnvironment as as, BaseCoverageOptions as at, CoverageIstanbulOptions as au, CoverageOptions as av, CoverageProvider as aw, CoverageProviderModule as ax, CoverageReporter as ay, CustomProviderOptions as az, TestProjectConfiguration as b, CoverageV8Options as c, UserProjectConfigFn as d, UserProjectConfigExport as e, UserConfig as f, TestProjectInlineConfiguration as g, ResolvedConfig as h, VitestRunMode as i, VitestOptions as j, PoolOptions as l, WorkerRequest as m, TestSequencer as n, OnTestsRerunHandler as o, PoolRunnerInitializer as q, PoolTask as r, WorkerResponse as s, JUnitOptions as t, TaskOptions as u, TestDiagnostic as x, TestModuleState as z };
|