11import test from "ava" ;
2+ import nock from "nock" ;
23import sinon , { SinonSandbox } from "sinon" ;
34import { TestEnvironment , HttpHttpsEnvironment } from "../../support/sdk/TestEnvironment" ;
45import { UpdateManager } from "../../../src/managers/UpdateManager" ;
@@ -8,6 +9,7 @@ import OneSignalApiShared from "../../../src/OneSignalApiShared";
89import MainHelper from "../../../src/helpers/MainHelper" ;
910import { SubscriptionStateKind } from "../../../src/models/SubscriptionStateKind" ;
1011import { PushDeviceRecord } from "../../../src/models/PushDeviceRecord" ;
12+ import { Subscription } from '../../../src/models/Subscription' ;
1113
1214// manually create and restore the sandbox
1315const sandbox : SinonSandbox = sinon . sandbox . create ( ) ;
@@ -98,6 +100,29 @@ test("sendOnSessionUpdate triggers on_session for existing subscribed user if ha
98100 t . is ( OneSignal . context . updateManager . onSessionAlreadyCalled ( ) , true ) ;
99101} ) ;
100102
103+ test ( "on_session saves new player id if returned from onesignal.com" , async t => {
104+ // 1. Setup existing player id in indexDB
105+ const playerId = Random . getRandomUuid ( ) ;
106+ const subscription = new Subscription ( ) ;
107+ subscription . deviceId = playerId ;
108+ await Database . setSubscription ( subscription ) ;
109+
110+ // 2. Mock on_session endpoint to give a new player_id
111+ const newPlayerId = Random . getRandomUuid ( ) ;
112+ nock ( 'https://onesignal.com' )
113+ . post ( `/api/v1/players/${ playerId } /on_session` )
114+ . reply ( 200 , { success : true , id : newPlayerId } ) ;
115+
116+ // 3. Make on_session call
117+ sandbox . stub ( OneSignal . context . sessionManager , "isFirstPageView" ) . returns ( true ) ;
118+ sandbox . stub ( MainHelper , "getCurrentNotificationType" ) . resolves ( SubscriptionStateKind . Subscribed ) ;
119+ await OneSignal . context . updateManager . sendOnSessionUpdate ( ) ;
120+
121+ // 4. Ensure we have the new playe_id saved in indexDB
122+ const newSubscription = await Database . getSubscription ( ) ;
123+ t . is ( newSubscription . deviceId , newPlayerId ) ;
124+ } ) ;
125+
101126test ( "sendOnSessionUpdate triggers on_session for existing unsubscribed user if hasn't done so already and if enableOnSession flag is present" , async t => {
102127 sandbox . stub ( Database , "getSubscription" ) . resolves ( { deviceId : Random . getRandomUuid ( ) } ) ;
103128 sandbox . stub ( OneSignal . context . sessionManager , "isFirstPageView" ) . returns ( true ) ;
0 commit comments