-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathjs-testing.html
More file actions
1666 lines (1387 loc) · 88.7 KB
/
js-testing.html
File metadata and controls
1666 lines (1387 loc) · 88.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>JS/TS Testing - Better Dev</title>
<link rel="stylesheet" href="style.css">
</head>
<body>
<header class="topbar">
<button class="sidebar-toggle" aria-label="Open navigation" aria-expanded="false">
<span class="hamburger-icon"></span>
</button>
<a href="index.html" class="logo">Better Dev</a>
</header>
<div class="sidebar-backdrop" aria-hidden="true"></div>
<aside class="sidebar" aria-label="Site navigation">
<div class="sidebar-header">
<span class="sidebar-title">Navigation</span>
<button class="sidebar-close" aria-label="Close navigation">×</button>
</div>
<div class="sidebar-search">
<input type="text" class="sidebar-search-input" placeholder="Search topics..." aria-label="Search topics">
<div class="sidebar-search-results"></div>
</div>
<nav class="sidebar-nav">
<div class="sidebar-group">
<a href="index.html">Home</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Mathematics</div>
<a href="pre-algebra.html">Pre-Algebra</a>
<a href="algebra.html">Algebra</a>
<a href="sequences-series.html">Sequences & Series</a>
<a href="geometry.html">Geometry</a>
<a href="calculus.html">Calculus</a>
<a href="discrete-math.html">Discrete Math</a>
<a href="linear-algebra.html">Linear Algebra</a>
<a href="probability.html">Probability & Statistics</a>
<a href="binary-systems.html">Binary & Number Systems</a>
<a href="number-theory.html">Number Theory for CP</a>
<a href="computational-geometry.html">Computational Geometry</a>
<a href="game-theory.html">Game Theory</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Data Structures & Algorithms</div>
<a href="dsa-foundations.html">DSA Foundations</a>
<a href="arrays.html">Arrays & Strings</a>
<a href="stacks-queues.html">Stacks & Queues</a>
<a href="hashmaps.html">Hash Maps & Sets</a>
<a href="linked-lists.html">Linked Lists</a>
<a href="trees.html">Trees & BST</a>
<a href="graphs.html">Graphs</a>
<a href="sorting.html">Sorting & Searching</a>
<a href="patterns.html">LeetCode Patterns</a>
<a href="dp.html">Dynamic Programming</a>
<a href="advanced.html">Advanced Topics</a>
<a href="string-algorithms.html">String Algorithms</a>
<a href="advanced-graphs.html">Advanced Graphs</a>
<a href="advanced-dp.html">Advanced DP</a>
<a href="advanced-ds.html">Advanced Data Structures</a>
<a href="leetcode-650.html">The 650 Problems</a>
<a href="competitive-programming.html">CP Roadmap</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">Languages & Systems</div>
<a href="cpp.html">C++</a>
<a href="golang.html">Go</a>
<a href="javascript.html">JavaScript Deep Dive</a>
<a href="typescript.html">TypeScript</a>
<a href="nodejs.html">Node.js Internals</a>
<a href="os.html">Operating Systems</a>
<a href="linux.html">Linux</a>
<a href="git.html">Git</a>
<a href="backend.html">Backend</a>
<a href="system-design.html">System Design</a>
<a href="networking.html">Networking</a>
<a href="cloud.html">Cloud & Infrastructure</a>
<a href="docker.html">Docker & Compose</a>
<a href="kubernetes.html">Kubernetes</a>
<a href="message-queues.html">Queues & Pub/Sub</a>
<a href="selfhosting.html">VPS & Self-Hosting</a>
<a href="databases.html">PostgreSQL & MySQL</a>
<a href="stripe.html">Stripe & Payments</a>
<a href="distributed-systems.html">Distributed Systems</a>
<a href="backend-engineering.html">Backend Engineering</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">JS/TS Ecosystem</div>
<a href="js-tooling.html">Tooling & Bundlers</a>
<a href="js-testing.html">Testing</a>
<a href="ts-projects.html">Building with TS</a>
</div>
<div class="sidebar-group">
<div class="sidebar-group-label">More</div>
<a href="seans-brain.html">Sean's Brain</a>
</div>
</nav>
</aside>
<div class="container">
<div class="page-header">
<div class="breadcrumb"><a href="index.html">Home</a> / Testing</div>
<h1>JS/TS Testing -- The Complete Guide</h1>
<p>Everything about testing JavaScript and TypeScript: the test doubles vocabulary (mocks, spies, stubs, fakes), dependency injection for testable code, Jest and Jasmine in depth, Vitest, real-world mocking patterns, async testing, HTTP API testing, TDD, E2E with Playwright, and CI integration.</p>
</div>
<div class="toc">
<h4>Table of Contents</h4>
<a href="#why-test">1. Why Test & Types of Tests</a>
<a href="#test-doubles">2. Test Doubles: Mocks, Spies, Stubs, Fakes</a>
<a href="#dependency-injection">3. Dependency Injection (DI) for Testable Code</a>
<a href="#jest-deep">4. Jest Deep Dive</a>
<a href="#jasmine">5. Jasmine</a>
<a href="#vitest">6. Vitest -- The Modern Runner</a>
<a href="#assertions">7. Assertions & Matchers</a>
<a href="#mocking-deep">8. Mocking Deep Dive -- Real Patterns</a>
<a href="#spies-deep">9. Spies Deep Dive</a>
<a href="#async-testing">10. Testing Async Code</a>
<a href="#testing-examples">11. Real-World Testing Examples</a>
<a href="#http-testing">12. Testing HTTP APIs</a>
<a href="#snapshots">13. Snapshot Testing</a>
<a href="#coverage">14. Code Coverage</a>
<a href="#tdd">15. TDD (Test-Driven Development)</a>
<a href="#e2e">16. E2E Testing with Playwright</a>
<a href="#ci">17. Testing in CI</a>
</div>
<!-- ───────────── SECTION 1 ───────────── -->
<section id="why-test">
<h2>1. Why Test & Types of Tests</h2>
<pre><code><span class="lang-label">Text</span>
Testing Pyramid:
/ E2E \ ← Slow, expensive, few of these
/ ———— \
/ Integration\ ← Tests modules working together
/ —————— \
/ Unit Tests \ ← Fast, isolated, many of these
/ ———————— \
</code></pre>
<pre><code><span class="lang-label">Text</span>
Type Scope Speed Tools
—————————————————————————————
Unit Single function/class Fast Vitest, Jest, Jasmine
Integration Multiple modules together Medium Vitest, Jest + DB
E2E Full app from user's view Slow Playwright, Cypress
</code></pre>
<div class="tip-box">
<strong>What makes a good test:</strong>
<ul>
<li><strong>Tests behavior, not implementation</strong> -- test what something does, not how it does it</li>
<li><strong>Fails when behavior breaks,</strong> passes when it's correct</li>
<li><strong>Fast and deterministic</strong> -- no flaky tests, no network calls, no randomness</li>
<li><strong>Readable</strong> -- serves as documentation for what the code should do</li>
<li><strong>Isolated</strong> -- one test failing shouldn't make others fail</li>
</ul>
</div>
<h3>The AAA Pattern</h3>
<p>Every test follows this structure:</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="function">it</span>(<span class="string">"calculates total with tax"</span>, () => {
<span class="comment">// ARRANGE -- set up the data and dependencies</span>
<span class="keyword">const</span> cart = <span class="keyword">new</span> <span class="function">Cart</span>();
cart.add({ name: <span class="string">"Widget"</span>, price: <span class="number">100</span> });
<span class="comment">// ACT -- do the thing you're testing</span>
<span class="keyword">const</span> total = cart.totalWithTax(<span class="number">0.1</span>);
<span class="comment">// ASSERT -- check the result</span>
expect(total).toBe(<span class="number">110</span>);
});
</code></pre>
</section>
<!-- ───────────── SECTION 2 ───────────── -->
<section id="test-doubles">
<h2>2. Test Doubles: Mocks, Spies, Stubs, Fakes</h2>
<p>"Test double" is the umbrella term for any object you substitute for a real dependency in tests. There are 5 kinds, and most people mix up the names. Here's the actual vocabulary.</p>
<pre><code><span class="lang-label">Text</span>
Type What it does Example
——————————————————————————————————
Dummy Passed around but never used Placeholder to fill a parameter
Stub Returns pre-programmed values getUser() always returns { name: "Sean" }
Spy Records calls (who, what, when) Wraps real method, tracks calls
Mock Pre-programmed with expectations Verifies it was called correctly
Fake Working implementation, simplified In-memory database instead of Postgres
</code></pre>
<h3>Dummy</h3>
<p>An object that exists just to satisfy a type signature. You don't care what it does.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// We need a Logger to create UserService, but this test doesn't care about logging</span>
<span class="keyword">const</span> dummyLogger: Logger = {
info: () => {},
error: () => {},
warn: () => {},
};
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">UserService</span>(db, dummyLogger);
</code></pre>
<h3>Stub</h3>
<p>Returns canned answers. You control the output so you can test how your code handles different scenarios.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Stub: always returns the same user, no real DB call</span>
<span class="keyword">const</span> stubUserRepo = {
findById: <span class="keyword">async</span> (id: <span class="keyword">string</span>) => ({ id, name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> }),
save: <span class="keyword">async</span> () => {},
};
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">UserService</span>(stubUserRepo);
<span class="keyword">const</span> user = <span class="keyword">await</span> service.getUser(<span class="string">"123"</span>);
expect(user.name).toBe(<span class="string">"Sean"</span>);
</code></pre>
<h3>Spy</h3>
<p>Wraps a real (or fake) function and <strong>records every call</strong>: arguments, return value, how many times.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">const</span> spy = vi.fn(); <span class="comment">// or jest.fn()</span>
<span class="function">spy</span>(<span class="string">"hello"</span>, <span class="number">42</span>);
<span class="function">spy</span>(<span class="string">"world"</span>);
expect(spy).toHaveBeenCalledTimes(<span class="number">2</span>);
expect(spy).toHaveBeenCalledWith(<span class="string">"hello"</span>, <span class="number">42</span>);
expect(spy).toHaveBeenLastCalledWith(<span class="string">"world"</span>);
expect(spy.mock.calls).toEqual([[<span class="string">"hello"</span>, <span class="number">42</span>], [<span class="string">"world"</span>]]);
</code></pre>
<h3>Mock</h3>
<p>A mock is a spy with <strong>built-in expectations</strong>. It verifies the interaction itself: "was this method called with these args?"</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Mock: we verify that sendEmail was called, not just what it returns</span>
<span class="keyword">const</span> mockEmailService = {
sendEmail: vi.fn().mockResolvedValue(<span class="keyword">undefined</span>),
};
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">RegistrationService</span>(userRepo, mockEmailService);
<span class="keyword">await</span> service.register({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> });
<span class="comment">// The test is about the INTERACTION -- did it send the welcome email?</span>
expect(mockEmailService.sendEmail).toHaveBeenCalledWith(
<span class="string">"sean@test.com"</span>,
expect.stringContaining(<span class="string">"Welcome"</span>)
);
</code></pre>
<h3>Fake</h3>
<p>A fully working but simplified implementation. Unlike stubs/mocks, fakes have real logic.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Fake: an in-memory implementation instead of a real database</span>
<span class="keyword">class</span> <span class="function">FakeUserRepo</span> <span class="keyword">implements</span> UserRepository {
<span class="keyword">private</span> users: Map<<span class="keyword">string</span>, User> = <span class="keyword">new</span> Map();
<span class="keyword">async</span> <span class="function">save</span>(user: User) {
<span class="keyword">this</span>.users.set(user.id, user);
}
<span class="keyword">async</span> <span class="function">findById</span>(id: <span class="keyword">string</span>) {
<span class="keyword">return</span> <span class="keyword">this</span>.users.get(id) ?? <span class="keyword">null</span>;
}
<span class="keyword">async</span> <span class="function">findAll</span>() {
<span class="keyword">return</span> [...<span class="keyword">this</span>.users.values()];
}
}
<span class="comment">// Use in tests -- it actually stores and retrieves, just in memory</span>
<span class="keyword">const</span> repo = <span class="keyword">new</span> <span class="function">FakeUserRepo</span>();
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">UserService</span>(repo);
<span class="keyword">await</span> service.createUser({ name: <span class="string">"Sean"</span> });
<span class="keyword">const</span> found = <span class="keyword">await</span> service.getUser(<span class="string">"sean-id"</span>);
expect(found).not.toBeNull();
</code></pre>
<div class="warning-box">
<strong>When to use which:</strong>
<ul>
<li><strong>Dummy</strong> -- when a parameter is required but irrelevant to the test</li>
<li><strong>Stub</strong> -- when you need to control what a dependency returns</li>
<li><strong>Spy</strong> -- when you want to verify something was called</li>
<li><strong>Mock</strong> -- when the interaction IS the thing you're testing</li>
<li><strong>Fake</strong> -- for integration-style tests where you need real behavior without real infrastructure</li>
</ul>
</div>
</section>
<!-- ───────────── SECTION 3 ───────────── -->
<section id="dependency-injection">
<h2>3. Dependency Injection (DI) for Testable Code</h2>
<p>Dependency Injection means <strong>passing dependencies in from outside</strong> instead of creating them inside. This is the #1 pattern that makes code testable.</p>
<h3>The Problem: Hard-Coded Dependencies</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// ❌ BAD -- impossible to test without a real database</span>
<span class="keyword">class</span> <span class="function">UserService</span> {
<span class="keyword">private</span> db = <span class="keyword">new</span> <span class="function">PostgresClient</span>(<span class="string">"postgres://localhost:5432/mydb"</span>);
<span class="keyword">async</span> <span class="function">getUser</span>(id: <span class="keyword">string</span>) {
<span class="keyword">return</span> <span class="keyword">this</span>.db.query(<span class="string">"SELECT * FROM users WHERE id = $1"</span>, [id]);
}
}
<span class="comment">// How do you test this? You'd need a running Postgres.
// What if the DB is down? What if you want to test the error path?
// You can't swap it out because it's created INSIDE the class.</span>
</code></pre>
<h3>The Solution: Constructor Injection</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// ✅ GOOD -- dependency is passed in, easy to swap for tests</span>
<span class="keyword">interface</span> <span class="function">UserRepository</span> {
findById(id: <span class="keyword">string</span>): Promise<User | <span class="keyword">null</span>>;
save(user: User): Promise<<span class="keyword">void</span>>;
}
<span class="keyword">class</span> <span class="function">UserService</span> {
<span class="keyword">constructor</span>(<span class="keyword">private</span> repo: UserRepository) {}
<span class="keyword">async</span> <span class="function">getUser</span>(id: <span class="keyword">string</span>): Promise<User> {
<span class="keyword">const</span> user = <span class="keyword">await</span> <span class="keyword">this</span>.repo.findById(id);
<span class="keyword">if</span> (!user) <span class="keyword">throw new</span> Error(<span class="string">"User not found"</span>);
<span class="keyword">return</span> user;
}
}
<span class="comment">// Production: real database</span>
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">UserService</span>(<span class="keyword">new</span> <span class="function">PostgresUserRepo</span>(pool));
<span class="comment">// Tests: stub, mock, or fake -- your choice</span>
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">UserService</span>(stubUserRepo);
</code></pre>
<h3>Full DI Example: Service with Multiple Dependencies</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Define interfaces for each dependency</span>
<span class="keyword">interface</span> <span class="function">UserRepository</span> {
findById(id: <span class="keyword">string</span>): Promise<User | <span class="keyword">null</span>>;
save(user: User): Promise<<span class="keyword">void</span>>;
}
<span class="keyword">interface</span> <span class="function">EmailService</span> {
send(to: <span class="keyword">string</span>, subject: <span class="keyword">string</span>, body: <span class="keyword">string</span>): Promise<<span class="keyword">void</span>>;
}
<span class="keyword">interface</span> <span class="function">Logger</span> {
info(msg: <span class="keyword">string</span>): <span class="keyword">void</span>;
error(msg: <span class="keyword">string</span>, err?: Error): <span class="keyword">void</span>;
}
<span class="comment">// Service depends on INTERFACES, not concrete classes</span>
<span class="keyword">class</span> <span class="function">RegistrationService</span> {
<span class="keyword">constructor</span>(
<span class="keyword">private</span> users: UserRepository,
<span class="keyword">private</span> email: EmailService,
<span class="keyword">private</span> log: Logger,
) {}
<span class="keyword">async</span> <span class="function">register</span>(input: { name: <span class="keyword">string</span>; email: <span class="keyword">string</span> }) {
<span class="keyword">const</span> user: User = { id: crypto.randomUUID(), ...input };
<span class="keyword">await</span> <span class="keyword">this</span>.users.save(user);
<span class="keyword">await</span> <span class="keyword">this</span>.email.send(input.email, <span class="string">"Welcome!"</span>, <span class="string">`Hi ${input.name}`</span>);
<span class="keyword">this</span>.log.info(<span class="string">`Registered user ${user.id}`</span>);
<span class="keyword">return</span> user;
}
}
</code></pre>
<h3>Testing the DI'd Service</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">import</span> { describe, it, expect, vi } <span class="keyword">from</span> <span class="string">"vitest"</span>;
<span class="function">describe</span>(<span class="string">"RegistrationService"</span>, () => {
<span class="comment">// Create test doubles for each dependency</span>
<span class="keyword">function</span> <span class="function">setup</span>() {
<span class="keyword">const</span> mockRepo: UserRepository = {
findById: vi.fn(),
save: vi.fn().mockResolvedValue(<span class="keyword">undefined</span>),
};
<span class="keyword">const</span> mockEmail: EmailService = {
send: vi.fn().mockResolvedValue(<span class="keyword">undefined</span>),
};
<span class="keyword">const</span> mockLog: Logger = {
info: vi.fn(),
error: vi.fn(),
};
<span class="keyword">const</span> service = <span class="keyword">new</span> <span class="function">RegistrationService</span>(mockRepo, mockEmail, mockLog);
<span class="keyword">return</span> { service, mockRepo, mockEmail, mockLog };
}
<span class="function">it</span>(<span class="string">"saves the user"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> { service, mockRepo } = <span class="function">setup</span>();
<span class="keyword">await</span> service.register({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> });
expect(mockRepo.save).toHaveBeenCalledWith(
expect.objectContaining({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> })
);
});
<span class="function">it</span>(<span class="string">"sends a welcome email"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> { service, mockEmail } = <span class="function">setup</span>();
<span class="keyword">await</span> service.register({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> });
expect(mockEmail.send).toHaveBeenCalledWith(
<span class="string">"sean@test.com"</span>,
<span class="string">"Welcome!"</span>,
expect.stringContaining(<span class="string">"Sean"</span>)
);
});
<span class="function">it</span>(<span class="string">"logs the registration"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> { service, mockLog } = <span class="function">setup</span>();
<span class="keyword">const</span> user = <span class="keyword">await</span> service.register({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> });
expect(mockLog.info).toHaveBeenCalledWith(
expect.stringContaining(user.id)
);
});
<span class="function">it</span>(<span class="string">"still saves user if email fails"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> { service, mockEmail, mockRepo } = <span class="function">setup</span>();
mockEmail.send = vi.fn().mockRejectedValue(<span class="keyword">new</span> Error(<span class="string">"SMTP down"</span>));
<span class="keyword">await</span> expect(service.register({ name: <span class="string">"Sean"</span>, email: <span class="string">"sean@test.com"</span> }))
.rejects.toThrow(<span class="string">"SMTP down"</span>);
<span class="comment">// User was saved BEFORE the email step</span>
expect(mockRepo.save).toHaveBeenCalled();
});
});
</code></pre>
<div class="tip-box">
<strong>DI without a framework:</strong> You don't need NestJS or InversifyJS for DI. Just pass dependencies through constructors or function parameters. The pattern is the important part, not the framework.
</div>
<h3>Function-Based DI (No Classes Needed)</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// You can do DI with plain functions too</span>
<span class="keyword">type</span> <span class="function">Deps</span> = {
getUser: (id: <span class="keyword">string</span>) => Promise<User | <span class="keyword">null</span>>;
sendEmail: (to: <span class="keyword">string</span>, body: <span class="keyword">string</span>) => Promise<<span class="keyword">void</span>>;
};
<span class="keyword">export function</span> <span class="function">createRegistrationHandler</span>(deps: Deps) {
<span class="keyword">return async function</span> <span class="function">register</span>(name: <span class="keyword">string</span>, email: <span class="keyword">string</span>) {
<span class="comment">// ... use deps.getUser, deps.sendEmail</span>
};
}
<span class="comment">// Production</span>
<span class="keyword">const</span> register = <span class="function">createRegistrationHandler</span>({ getUser: dbGetUser, sendEmail: smtpSend });
<span class="comment">// Test</span>
<span class="keyword">const</span> register = <span class="function">createRegistrationHandler</span>({ getUser: vi.fn(), sendEmail: vi.fn() });
</code></pre>
</section>
<!-- ───────────── SECTION 4 ───────────── -->
<section id="jest-deep">
<h2>4. Jest Deep Dive</h2>
<p>Jest is the most widely used JS test framework. Created by Facebook, batteries-included: runner, assertions, mocking, coverage, snapshots all built in.</p>
<pre><code><span class="lang-label">Bash</span>
<span class="comment"># Install for TypeScript</span>
pnpm add -D jest @types/jest ts-jest
<span class="comment"># Initialize config</span>
npx ts-jest config:init
<span class="comment"># Run</span>
npx jest <span class="comment"># run all tests</span>
npx jest --watch <span class="comment"># watch mode</span>
npx jest --coverage <span class="comment"># with coverage report</span>
npx jest path/to/file.test <span class="comment"># run specific file</span>
npx jest -t "user" <span class="comment"># run tests matching name</span>
</code></pre>
<h3>Jest Config</h3>
<pre><code><span class="lang-label">JavaScript</span>
<span class="comment">// jest.config.js</span>
<span class="keyword">export default</span> {
preset: <span class="string">"ts-jest"</span>,
testEnvironment: <span class="string">"node"</span>,
roots: [<span class="string">"<rootDir>/src"</span>],
testMatch: [<span class="string">"**/*.test.ts"</span>],
collectCoverageFrom: [<span class="string">"src/**/*.ts"</span>, <span class="string">"!src/**/*.d.ts"</span>],
coverageThreshold: {
global: { branches: <span class="number">80</span>, functions: <span class="number">80</span>, lines: <span class="number">80</span>, statements: <span class="number">80</span> },
},
clearMocks: <span class="keyword">true</span>, <span class="comment">// auto-clear mock state between tests</span>
};
</code></pre>
<h3>Lifecycle Hooks</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="function">describe</span>(<span class="string">"UserService"</span>, () => {
<span class="keyword">let</span> service: UserService;
<span class="keyword">let</span> db: FakeDB;
<span class="comment">// Runs ONCE before all tests in this describe</span>
<span class="function">beforeAll</span>(<span class="keyword">async</span> () => {
db = <span class="keyword">await</span> FakeDB.connect();
});
<span class="comment">// Runs before EACH test</span>
<span class="function">beforeEach</span>(() => {
service = <span class="keyword">new</span> <span class="function">UserService</span>(db);
});
<span class="comment">// Runs after EACH test</span>
<span class="function">afterEach</span>(<span class="keyword">async</span> () => {
<span class="keyword">await</span> db.clear(); <span class="comment">// clean state between tests</span>
});
<span class="comment">// Runs ONCE after all tests</span>
<span class="function">afterAll</span>(<span class="keyword">async</span> () => {
<span class="keyword">await</span> db.disconnect();
});
<span class="function">it</span>(<span class="string">"creates a user"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> user = <span class="keyword">await</span> service.create({ name: <span class="string">"Sean"</span> });
expect(user.id).toBeDefined();
});
});
</code></pre>
<h3>Parameterized Tests: describe.each / it.each</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Run the same test with different data</span>
describe.each([
{ input: <span class="string">"hello"</span>, expected: <span class="string">"HELLO"</span> },
{ input: <span class="string">"world"</span>, expected: <span class="string">"WORLD"</span> },
{ input: <span class="string">""</span>, expected: <span class="string">""</span> },
])(<span class="string">"toUpperCase($input)"</span>, ({ input, expected }) => {
<span class="function">it</span>(<span class="string">`returns "${expected}"`</span>, () => {
expect(input.toUpperCase()).toBe(expected);
});
});
<span class="comment">// Shorter: table format</span>
it.each([
[<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>],
[<span class="number">0</span>, <span class="number">0</span>, <span class="number">0</span>],
[-<span class="number">1</span>, <span class="number">1</span>, <span class="number">0</span>],
])(<span class="string">"add(%i, %i) = %i"</span>, (a, b, expected) => {
expect(<span class="function">add</span>(a, b)).toBe(expected);
});
</code></pre>
<h3>Skipping & Focusing Tests</h3>
<pre><code><span class="lang-label">TypeScript</span>
it.skip(<span class="string">"this test is skipped"</span>, () => { <span class="comment">/* ... */</span> });
it.only(<span class="string">"ONLY this test runs"</span>, () => { <span class="comment">/* ... */</span> });
it.todo(<span class="string">"write this test later"</span>);
describe.skip(<span class="string">"skip entire group"</span>, () => { <span class="comment">/* ... */</span> });
describe.only(<span class="string">"only this group runs"</span>, () => { <span class="comment">/* ... */</span> });
</code></pre>
<h3>Jest Mock Functions</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// jest.fn() creates a spy/mock function</span>
<span class="keyword">const</span> mockFn = jest.fn();
<span class="keyword">const</span> mockWithImpl = jest.fn((x: <span class="keyword">number</span>) => x * <span class="number">2</span>);
<span class="keyword">const</span> mockAsync = jest.fn().mockResolvedValue({ id: <span class="string">"1"</span> });
<span class="comment">// jest.spyOn() wraps an existing method</span>
<span class="keyword">const</span> spy = jest.spyOn(myObject, <span class="string">"myMethod"</span>);
spy.mockReturnValue(<span class="string">"fake"</span>);
<span class="comment">// jest.mock() replaces an entire module</span>
jest.mock(<span class="string">"./database"</span>);
jest.mock(<span class="string">"axios"</span>);
<span class="comment">// Manual mock: create __mocks__/database.ts alongside database.ts</span>
<span class="comment">// Jest auto-uses it when you call jest.mock("./database")</span>
</code></pre>
<h3>Jest Module Mocking Patterns</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Mock with custom implementation</span>
jest.mock(<span class="string">"./database"</span>, () => ({
getUser: jest.fn().mockResolvedValue({ id: <span class="string">"1"</span>, name: <span class="string">"Sean"</span> }),
saveUser: jest.fn(),
}));
<span class="comment">// Partial mock: keep real implementation, mock specific exports</span>
jest.mock(<span class="string">"./utils"</span>, () => ({
...jest.requireActual(<span class="string">"./utils"</span>),
sendEmail: jest.fn(), <span class="comment">// only mock this one</span>
}));
<span class="comment">// Access the mocked module to change behavior per test</span>
<span class="keyword">import</span> { getUser } <span class="keyword">from</span> <span class="string">"./database"</span>;
<span class="keyword">const</span> mockedGetUser = getUser <span class="keyword">as</span> jest.MockedFunction<<span class="keyword">typeof</span> getUser>;
<span class="function">it</span>(<span class="string">"handles not found"</span>, <span class="keyword">async</span> () => {
mockedGetUser.mockResolvedValueOnce(<span class="keyword">null</span>);
<span class="keyword">await</span> expect(service.getUser(<span class="string">"bad-id"</span>)).rejects.toThrow(<span class="string">"Not found"</span>);
});
</code></pre>
<div class="tip-box">
<strong>Vitest vs Jest API mapping:</strong> They're almost identical.<br>
<code>jest.fn()</code> = <code>vi.fn()</code><br>
<code>jest.spyOn()</code> = <code>vi.spyOn()</code><br>
<code>jest.mock()</code> = <code>vi.mock()</code><br>
<code>jest.useFakeTimers()</code> = <code>vi.useFakeTimers()</code><br>
If you know one, you know the other.
</div>
</section>
<!-- ───────────── SECTION 5 ───────────── -->
<section id="jasmine">
<h2>5. Jasmine</h2>
<p>Jasmine is the OG JavaScript test framework. It came before Jest and influenced its API. Angular still uses Jasmine by default. The syntax is very similar to Jest/Vitest but with some differences.</p>
<pre><code><span class="lang-label">Bash</span>
<span class="comment"># Install</span>
pnpm add -D jasmine @types/jasmine jasmine-ts
<span class="comment"># Initialize</span>
npx jasmine init
<span class="comment"># Run</span>
npx jasmine
</code></pre>
<h3>Jasmine Syntax vs Jest</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Jasmine uses the same describe/it/expect pattern</span>
<span class="function">describe</span>(<span class="string">"Calculator"</span>, () => {
<span class="keyword">let</span> calc: Calculator;
<span class="function">beforeEach</span>(() => {
calc = <span class="keyword">new</span> <span class="function">Calculator</span>();
});
<span class="function">it</span>(<span class="string">"adds numbers"</span>, () => {
expect(calc.add(<span class="number">2</span>, <span class="number">3</span>)).toBe(<span class="number">5</span>);
});
<span class="function">it</span>(<span class="string">"throws on divide by zero"</span>, () => {
expect(() => calc.divide(<span class="number">1</span>, <span class="number">0</span>)).toThrowError(<span class="string">"Cannot divide by zero"</span>);
});
});
</code></pre>
<h3>Jasmine Spies</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Create a spy on an existing method</span>
spyOn(calculator, <span class="string">"add"</span>).and.returnValue(<span class="number">42</span>);
calculator.add(<span class="number">1</span>, <span class="number">2</span>); <span class="comment">// returns 42, not 3</span>
expect(calculator.add).toHaveBeenCalledWith(<span class="number">1</span>, <span class="number">2</span>);
<span class="comment">// Create a standalone spy (like jest.fn())</span>
<span class="keyword">const</span> callback = jasmine.createSpy(<span class="string">"callback"</span>);
callback(<span class="string">"hello"</span>);
expect(callback).toHaveBeenCalledWith(<span class="string">"hello"</span>);
<span class="comment">// Spy strategies (what happens when the spy is called)</span>
spyOn(obj, <span class="string">"method"</span>).and.callThrough(); <span class="comment">// call the real method</span>
spyOn(obj, <span class="string">"method"</span>).and.returnValue(<span class="number">42</span>); <span class="comment">// return a value</span>
spyOn(obj, <span class="string">"method"</span>).and.callFake((x) => x); <span class="comment">// custom implementation</span>
spyOn(obj, <span class="string">"method"</span>).and.throwError(<span class="string">"nope"</span>); <span class="comment">// throw</span>
spyOn(obj, <span class="string">"method"</span>).and.returnValues(<span class="number">1</span>,<span class="number">2</span>,<span class="number">3</span>); <span class="comment">// different each call</span>
</code></pre>
<h3>Jasmine Spy Matchers</h3>
<pre><code><span class="lang-label">TypeScript</span>
expect(spy).toHaveBeenCalled();
expect(spy).toHaveBeenCalledTimes(<span class="number">3</span>);
expect(spy).toHaveBeenCalledWith(<span class="string">"arg1"</span>, <span class="string">"arg2"</span>);
expect(spy).toHaveBeenCalledOnceWith(<span class="string">"arg"</span>);
expect(spy).not.toHaveBeenCalled();
<span class="comment">// Inspect call details</span>
spy.calls.count(); <span class="comment">// how many times</span>
spy.calls.argsFor(<span class="number">0</span>); <span class="comment">// args of first call</span>
spy.calls.allArgs(); <span class="comment">// args of all calls</span>
spy.calls.mostRecent(); <span class="comment">// last call details</span>
spy.calls.reset(); <span class="comment">// clear tracking</span>
</code></pre>
<h3>Jasmine Custom Matchers</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="function">beforeEach</span>(() => {
jasmine.addMatchers({
<span class="function">toBeValidEmail</span>() {
<span class="keyword">return</span> {
<span class="function">compare</span>(actual: <span class="keyword">string</span>) {
<span class="keyword">const</span> pass = /^[^\s@]+@[^\s@]+\.[^\s@]+$/.test(actual);
<span class="keyword">return</span> {
pass,
message: pass
? <span class="string">`Expected "${actual}" not to be a valid email`</span>
: <span class="string">`Expected "${actual}" to be a valid email`</span>,
};
},
};
},
});
});
<span class="function">it</span>(<span class="string">"validates email"</span>, () => {
expect(<span class="string">"sean@test.com"</span>).toBeValidEmail();
expect(<span class="string">"not-an-email"</span>).not.toBeValidEmail();
});
</code></pre>
<h3>Jasmine Async</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// async/await works the same as Jest</span>
<span class="function">it</span>(<span class="string">"fetches data"</span>, <span class="keyword">async</span> () => {
<span class="keyword">const</span> data = <span class="keyword">await</span> <span class="function">fetchData</span>();
expect(data).toBeDefined();
});
<span class="comment">// Jasmine also supports done() callback (older style)</span>
<span class="function">it</span>(<span class="string">"fetches data"</span>, (done) => {
<span class="function">fetchData</span>().then((data) => {
expect(data).toBeDefined();
<span class="function">done</span>();
});
});
</code></pre>
<pre><code><span class="lang-label">Text</span>
Feature Jest Jasmine Vitest
—————————————————————————————
Spies jest.fn() jasmine.createSpy vi.fn()
Spy on method jest.spyOn() spyOn() vi.spyOn()
Module mocking jest.mock() ❌ manual only vi.mock()
Snapshot tests ✅ built-in ❌ plugin ✅ built-in
Timer mocking jest.useFakeTimers jasmine.clock() vi.useFakeTimers
Speed (w/ TS) Slow (ts-jest) Medium Fast (native ESM)
Used by React, Node Angular Vite projects
</code></pre>
</section>
<!-- ───────────── SECTION 6 ───────────── -->
<section id="vitest">
<h2>6. Vitest -- The Modern Runner</h2>
<p>Vitest is a Vite-native test runner. It understands TypeScript, ESM, and JSX out of the box with zero config. Same API as Jest.</p>
<pre><code><span class="lang-label">Bash</span>
pnpm add -D vitest
npx vitest <span class="comment"># watch mode (default)</span>
npx vitest run <span class="comment"># single run (CI)</span>
npx vitest run --reporter=verbose
</code></pre>
<h3>Config</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// vitest.config.ts</span>
<span class="keyword">import</span> { defineConfig } <span class="keyword">from</span> <span class="string">"vitest/config"</span>;
<span class="keyword">export default</span> <span class="function">defineConfig</span>({
test: {
globals: <span class="keyword">true</span>, <span class="comment">// no need to import describe/it/expect</span>
environment: <span class="string">"node"</span>, <span class="comment">// or "jsdom" for browser APIs</span>
coverage: {
provider: <span class="string">"v8"</span>,
reporter: [<span class="string">"text"</span>, <span class="string">"html"</span>],
},
include: [<span class="string">"src/**/*.test.ts"</span>],
clearMocks: <span class="keyword">true</span>, <span class="comment">// auto-reset mocks between tests</span>
},
});
</code></pre>
<h3>File Naming</h3>
<pre><code><span class="lang-label">Text</span>
Vitest finds: **/*.test.ts **/*.spec.ts **/__tests__/**
</code></pre>
</section>
<!-- ───────────── SECTION 7 ───────────── -->
<section id="assertions">
<h2>7. Assertions & Matchers</h2>
<p>These work in Jest, Vitest, and mostly in Jasmine too.</p>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// ── Equality ──</span>
expect(<span class="number">1</span> + <span class="number">1</span>).toBe(<span class="number">2</span>); <span class="comment">// strict === (primitives)</span>
expect({ a: <span class="number">1</span> }).toEqual({ a: <span class="number">1</span> }); <span class="comment">// deep equality (objects)</span>
expect(obj).toStrictEqual(other); <span class="comment">// deep + checks undefined props</span>
<span class="comment">// ── Truthiness ──</span>
expect(value).toBeTruthy();
expect(value).toBeFalsy();
expect(value).toBeNull();
expect(value).toBeUndefined();
expect(value).toBeDefined();
<span class="comment">// ── Numbers ──</span>
expect(<span class="number">10</span>).toBeGreaterThan(<span class="number">5</span>);
expect(<span class="number">10</span>).toBeGreaterThanOrEqual(<span class="number">10</span>);
expect(<span class="number">10</span>).toBeLessThan(<span class="number">20</span>);
expect(<span class="number">0.1</span> + <span class="number">0.2</span>).toBeCloseTo(<span class="number">0.3</span>); <span class="comment">// floating point safe</span>
<span class="comment">// ── Strings ──</span>
expect(<span class="string">"hello world"</span>).toContain(<span class="string">"world"</span>);
expect(<span class="string">"hello"</span>).toMatch(/^hel/);
<span class="comment">// ── Arrays ──</span>
expect([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]).toContain(<span class="number">2</span>);
expect([<span class="number">1</span>, <span class="number">2</span>, <span class="number">3</span>]).toHaveLength(<span class="number">3</span>);
expect([{ id: <span class="number">1</span> }, { id: <span class="number">2</span> }]).toContainEqual({ id: <span class="number">1</span> });
expect([<span class="number">3</span>, <span class="number">1</span>, <span class="number">2</span>]).toEqual(expect.arrayContaining([<span class="number">1</span>, <span class="number">2</span>]));
<span class="comment">// ── Objects ──</span>
expect(obj).toHaveProperty(<span class="string">"key"</span>);
expect(obj).toHaveProperty(<span class="string">"nested.deep.key"</span>);
expect(obj).toMatchObject({ name: <span class="string">"Sean"</span> }); <span class="comment">// partial match</span>
expect(obj).toEqual(expect.objectContaining({ name: <span class="string">"Sean"</span> }));
<span class="comment">// ── Exceptions ──</span>
expect(() => <span class="function">throwingFn</span>()).toThrow();
expect(() => <span class="function">throwingFn</span>()).toThrow(<span class="string">"specific message"</span>);
expect(() => <span class="function">throwingFn</span>()).toThrow(TypeError);
<span class="comment">// ── Negation ──</span>
expect(<span class="number">1</span>).not.toBe(<span class="number">2</span>);
<span class="comment">// ── Asymmetric matchers (inside other matchers) ──</span>
expect(obj).toEqual({
id: expect.any(String),
name: expect.stringContaining(<span class="string">"Sean"</span>),
tags: expect.arrayContaining([<span class="string">"admin"</span>]),
createdAt: expect.any(Date),
});
</code></pre>
</section>
<!-- ───────────── SECTION 8 ───────────── -->
<section id="mocking-deep">
<h2>8. Mocking Deep Dive -- Real Patterns</h2>
<h3>Mock Functions: The Complete API</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="keyword">const</span> fn = vi.fn(); <span class="comment">// or jest.fn()</span>
<span class="comment">// ── Return values ──</span>
fn.mockReturnValue(<span class="string">"always this"</span>);
fn.mockReturnValueOnce(<span class="string">"first call"</span>);
fn.mockResolvedValue({ data: <span class="number">1</span> }); <span class="comment">// async: resolves</span>
fn.mockResolvedValueOnce({ data: <span class="number">1</span> }); <span class="comment">// async: resolves once</span>
fn.mockRejectedValue(<span class="keyword">new</span> Error(<span class="string">"fail"</span>)); <span class="comment">// async: rejects</span>
fn.mockRejectedValueOnce(<span class="keyword">new</span> Error()); <span class="comment">// async: rejects once</span>
<span class="comment">// ── Custom implementation ──</span>
fn.mockImplementation((x) => x * <span class="number">2</span>);
fn.mockImplementationOnce((x) => x * <span class="number">10</span>);
<span class="comment">// ── Chain them for different behavior per call ──</span>
<span class="keyword">const</span> getUserMock = vi.fn()
.mockResolvedValueOnce({ id: <span class="string">"1"</span>, name: <span class="string">"Sean"</span> }) <span class="comment">// 1st call</span>
.mockResolvedValueOnce(<span class="keyword">null</span>) <span class="comment">// 2nd call</span>
.mockRejectedValue(<span class="keyword">new</span> Error(<span class="string">"DB down"</span>)); <span class="comment">// all after</span>
<span class="comment">// ── Inspect calls ──</span>
fn.mock.calls; <span class="comment">// [[arg1, arg2], [arg3]]</span>
fn.mock.calls[<span class="number">0</span>]; <span class="comment">// args of first call</span>
fn.mock.results; <span class="comment">// [{ type: "return", value: ... }]</span>
fn.mock.lastCall; <span class="comment">// args of most recent call</span>
<span class="comment">// ── Reset ──</span>
fn.mockClear(); <span class="comment">// clear calls & results (keep implementation)</span>
fn.mockReset(); <span class="comment">// clear everything (implementation becomes () => undefined)</span>
fn.mockRestore(); <span class="comment">// restore original (only for spyOn)</span>
</code></pre>
<h3>Mocking Modules</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// ── Full module mock ──</span>
vi.mock(<span class="string">"./database"</span>, () => ({
getUser: vi.fn().mockResolvedValue({ id: <span class="string">"1"</span>, name: <span class="string">"Sean"</span> }),
saveUser: vi.fn(),
}));
<span class="comment">// ── Partial module mock (keep real exports, mock some) ──</span>
vi.mock(<span class="string">"./utils"</span>, <span class="keyword">async</span> (importOriginal) => {
<span class="keyword">const</span> actual = <span class="keyword">await</span> <span class="function">importOriginal</span>();
<span class="keyword">return</span> {
...actual,
sendEmail: vi.fn(), <span class="comment">// only mock this one export</span>
};
});
<span class="comment">// ── Mock a third-party package ──</span>
vi.mock(<span class="string">"axios"</span>, () => ({
<span class="keyword">default</span>: {
get: vi.fn().mockResolvedValue({ data: { users: [] } }),
post: vi.fn().mockResolvedValue({ data: { id: <span class="string">"new"</span> } }),
},
}));
</code></pre>
<h3>Mocking fetch / Network Requests</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Mock global fetch</span>
<span class="keyword">const</span> mockFetch = vi.fn();
global.fetch = mockFetch;
<span class="function">beforeEach</span>(() => {
mockFetch.mockReset();
});
<span class="function">it</span>(<span class="string">"fetches users"</span>, <span class="keyword">async</span> () => {
mockFetch.mockResolvedValue({
ok: <span class="keyword">true</span>,
json: <span class="keyword">async</span> () => [{ id: <span class="string">"1"</span>, name: <span class="string">"Sean"</span> }],
});
<span class="keyword">const</span> users = <span class="keyword">await</span> <span class="function">getUsers</span>();
expect(mockFetch).toHaveBeenCalledWith(<span class="string">"https://api.example.com/users"</span>);
expect(users).toHaveLength(<span class="number">1</span>);
});
<span class="function">it</span>(<span class="string">"handles network error"</span>, <span class="keyword">async</span> () => {
mockFetch.mockRejectedValue(<span class="keyword">new</span> Error(<span class="string">"Network failed"</span>));
<span class="keyword">await</span> expect(<span class="function">getUsers</span>()).rejects.toThrow(<span class="string">"Network failed"</span>);
});
<span class="function">it</span>(<span class="string">"handles non-OK response"</span>, <span class="keyword">async</span> () => {
mockFetch.mockResolvedValue({
ok: <span class="keyword">false</span>,
status: <span class="number">500</span>,
statusText: <span class="string">"Internal Server Error"</span>,
});
<span class="keyword">await</span> expect(<span class="function">getUsers</span>()).rejects.toThrow();
});
</code></pre>
<h3>Mocking Timers</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="function">beforeEach</span>(() => { vi.useFakeTimers(); });
<span class="function">afterEach</span>(() => { vi.useRealTimers(); });
<span class="function">it</span>(<span class="string">"debounces calls"</span>, () => {
<span class="keyword">const</span> callback = vi.fn();
<span class="keyword">const</span> debounced = <span class="function">debounce</span>(callback, <span class="number">300</span>);
<span class="function">debounced</span>();
<span class="function">debounced</span>();
<span class="function">debounced</span>();
expect(callback).not.toHaveBeenCalled(); <span class="comment">// not yet</span>
vi.advanceTimersByTime(<span class="number">300</span>);
expect(callback).toHaveBeenCalledTimes(<span class="number">1</span>); <span class="comment">// only once</span>
});
<span class="function">it</span>(<span class="string">"runs setInterval"</span>, () => {
<span class="keyword">const</span> callback = vi.fn();
setInterval(callback, <span class="number">1000</span>);
vi.advanceTimersByTime(<span class="number">3000</span>);
expect(callback).toHaveBeenCalledTimes(<span class="number">3</span>);
});
<span class="comment">// Other timer controls</span>
vi.runAllTimers(); <span class="comment">// fast-forward until all timers fire</span>
vi.runOnlyPendingTimers(); <span class="comment">// run currently pending timers only</span>
vi.advanceTimersToNextTimer(); <span class="comment">// jump to next timer</span>
vi.setSystemTime(<span class="keyword">new</span> Date(<span class="string">"2025-01-01"</span>)); <span class="comment">// mock Date.now()</span>
</code></pre>
<h3>Mocking Classes</h3>
<pre><code><span class="lang-label">TypeScript</span>
<span class="comment">// Automatically mock all methods of a class</span>
vi.mock(<span class="string">"./EmailService"</span>);
<span class="keyword">import</span> { EmailService } <span class="keyword">from</span> <span class="string">"./EmailService"</span>;