@@ -639,7 +639,7 @@ Deno.test("AuthService comprehensive test", async (t) => {
639639 { status: 200 , headers: { " Content-Type" : " application/json" } },
640640 );
641641
642- const fetchStub = stub (
642+ using fetchStub = stub (
643643 globalThis ,
644644 " fetch" ,
645645 (_url : string | URL | Request , options ? : RequestInit ) => {
@@ -653,19 +653,16 @@ Deno.test("AuthService comprehensive test", async (t) => {
653653 },
654654 );
655655
656- try {
657- const token = await authService .login (" testuser" , " password123" );
658- assertEquals (token , " fake-jwt-token" );
659- } finally {
660- fetchStub .restore ();
661- }
656+ const token = await authService .login (" testuser" , " password123" );
657+ assertEquals (token , " fake-jwt-token" );
658+ assertSpyCalls (fetchStub , 1 );
662659 });
663660
664661 await t .step (" token expiration should work correctly" , async () => {
665662 using time = new FakeTime (new Date (" 2023-01-01T12:00:00Z" ));
666663 const authService = new AuthService ();
667664
668- const fetchStub = stub (
665+ using fetchStub = stub (
669666 globalThis ,
670667 " fetch" ,
671668 () =>
@@ -677,27 +674,23 @@ Deno.test("AuthService comprehensive test", async (t) => {
677674 ),
678675 );
679676
680- const getTokenSpy = spy (authService , " getToken" );
677+ using getTokenSpy = spy (authService , " getToken" );
681678
682- try {
683- await authService .login (" user" , " pass" );
684- assertEquals (authService .getToken (), " fake-token" );
685- assertSpyCalls (getTokenSpy , 1 );
686-
687- // Advance time past expiration
688- time .tick (61 * 60 * 1000 );
689-
690- // Token should now be expired
691- assertThrows (
692- () => authService .getToken (),
693- Error ,
694- " Token expired" ,
695- );
696- assertSpyCalls (getTokenSpy , 2 );
697- } finally {
698- fetchStub .restore ();
699- getTokenSpy .restore ();
700- }
679+ await authService .login (" user" , " pass" );
680+ assertEquals (authService .getToken (), " fake-token" );
681+ assertSpyCalls (getTokenSpy , 1 );
682+
683+ // Advance time past expiration
684+ time .tick (61 * 60 * 1000 );
685+
686+ // Token should now be expired
687+ assertThrows (
688+ () => authService .getToken (),
689+ Error ,
690+ " Token expired" ,
691+ );
692+ assertSpyCalls (getTokenSpy , 2 );
693+ assertSpyCalls (fetchStub , 1 );
701694 });
702695});
703696```
@@ -711,7 +704,7 @@ functionalities:
711704- Logout - Clears the token and expiration
712705
713706The testing structure is organized as a single main test with three logical
714- ** steps** , each testing a different aspect of the service; credential
707+ ** steps** , each testing a different aspect of the service: credential
715708validation, API call handling, and token expiration.
716709
717710🦕 Effective mocking is essential for writing reliable, maintainable unit tests.
0 commit comments