@@ -8,6 +8,7 @@ import { LoginState } from "../session/session-states/login-state.enum";
88import { KeycloakAuthService } from "../session/auth/keycloak/keycloak-auth.service" ;
99import { HttpStatusCode } from "@angular/common/http" ;
1010import PouchDB from "pouchdb-browser" ;
11+ import { Subject } from "rxjs" ;
1112
1213describe ( "SyncService" , ( ) => {
1314 let service : SyncService ;
@@ -28,6 +29,15 @@ describe("SyncService", () => {
2829 loginState = TestBed . inject ( LoginStateSubject ) ;
2930 } ) ;
3031
32+ /**
33+ * ensure the interval for sync is stopped at end of test to avoid errors.
34+ * Somehow this does not work in afterEach().
35+ */
36+ function stopPeriodicTimer ( ) {
37+ service . liveSyncEnabled = false ;
38+ tick ( SyncService . SYNC_INTERVAL + 500 ) ;
39+ }
40+
3141 it ( "should be created" , ( ) => {
3242 expect ( service ) . toBeTruthy ( ) ;
3343 } ) ;
@@ -59,8 +69,7 @@ describe("SyncService", () => {
5969 tick ( SyncService . SYNC_INTERVAL ) ;
6070 expect ( mockLocalDb . sync ) . toHaveBeenCalled ( ) ;
6171
62- service . liveSyncEnabled = false ;
63- tick ( SyncService . SYNC_INTERVAL ) ;
72+ stopPeriodicTimer ( ) ;
6473 } ) ) ;
6574
6675 it ( "should try auto-login if fetch fails and fetch again" , fakeAsync ( ( ) => {
@@ -101,7 +110,31 @@ describe("SyncService", () => {
101110 expect ( mockAuthService . login ) . toHaveBeenCalled ( ) ;
102111 expect ( mockAuthService . addAuthHeader ) . toHaveBeenCalledTimes ( 2 ) ;
103112
104- service . liveSyncEnabled = false ;
105- tick ( SyncService . SYNC_INTERVAL ) ;
113+ stopPeriodicTimer ( ) ;
114+ } ) ) ;
115+
116+ it ( "should sync immediately when local db has changes" , fakeAsync ( ( ) => {
117+ const mockLocalDb = jasmine . createSpyObj ( [ "sync" ] ) ;
118+ const db = TestBed . inject ( Database ) as PouchDatabase ;
119+ spyOn ( db , "getPouchDB" ) . and . returnValue ( mockLocalDb ) ;
120+ const mockChanges = new Subject ( ) ;
121+ spyOn ( db , "changes" ) . and . returnValue ( mockChanges ) ;
122+
123+ loginState . next ( LoginState . LOGGED_IN ) ;
124+
125+ service . startSync ( ) ;
126+
127+ mockLocalDb . sync . and . resolveTo ( { } ) ;
128+ tick ( 1000 ) ;
129+ expect ( mockLocalDb . sync ) . toHaveBeenCalled ( ) ;
130+ mockLocalDb . sync . calls . reset ( ) ;
131+ expect ( mockLocalDb . sync ) . not . toHaveBeenCalled ( ) ;
132+
133+ // simulate local doc written
134+ mockChanges . next ( { } ) ;
135+ tick ( 500 ) ; // sync has a short debounce time
136+ expect ( mockLocalDb . sync ) . toHaveBeenCalled ( ) ;
137+
138+ stopPeriodicTimer ( ) ;
106139 } ) ) ;
107140} ) ;
0 commit comments