@@ -5,7 +5,7 @@ SPDX-License-Identifier: AGPL-3.0-only OR LicenseRef-Element-Commercial
55Please see LICENSE files in the repository root for full details.
66*/
77
8- import { expect , test , vitest } from "vitest" ;
8+ import { expect , test , vi , vitest } from "vitest" ;
99
1010import { Watchable } from "./watchable" ;
1111
@@ -56,3 +56,44 @@ test("when value is an object, shallow comparison works", () => {
5656
5757 watchable . unwatch ( listener ) ; // Clean up after the test
5858} ) ;
59+
60+ test ( "onFirstWatch and onLastWatch are called when appropriate" , ( ) => {
61+ const onFirstWatch = vi . fn ( ) ;
62+ const onLastWatch = vi . fn ( ) ;
63+ class CustomWatchable extends Watchable < number > {
64+ protected onFirstWatch ( ) : void {
65+ onFirstWatch ( ) ;
66+ }
67+ protected onLastWatch ( ) : void {
68+ onLastWatch ( ) ;
69+ }
70+ }
71+
72+ const watchable = new CustomWatchable ( 10 ) ;
73+ // No listeners yet, so expect no calls
74+ expect ( onFirstWatch ) . not . toHaveBeenCalled ( ) ;
75+ expect ( onLastWatch ) . not . toHaveBeenCalled ( ) ;
76+
77+ // Let's say that we have three listeners
78+ const listeners = [ vi . fn ( ) , vi . fn ( ) , vi . fn ( ) ] ;
79+
80+ // Let's add all of them via watch
81+ for ( const listener of listeners ) {
82+ watchable . watch ( listener ) ;
83+ }
84+
85+ // Only expect onFirstWatch() to have been called once
86+ expect ( onFirstWatch ) . toHaveBeenCalledOnce ( ) ;
87+
88+ // Let's remove all the listeners
89+ for ( const listener of listeners ) {
90+ watchable . unwatch ( listener ) ;
91+ }
92+
93+ // Only expect onLastWatch to have been called once
94+ expect ( onLastWatch ) . toHaveBeenCalledOnce ( ) ;
95+
96+ // Should call onFirstWatch again once we have more listeners
97+ watchable . watch ( vi . fn ( ) ) ;
98+ expect ( onFirstWatch ) . toHaveBeenCalledTimes ( 2 ) ;
99+ } ) ;
0 commit comments