-
Notifications
You must be signed in to change notification settings - Fork 3.9k
/
test-amp-subscriptions-google.js
877 lines (787 loc) · 27.5 KB
/
test-amp-subscriptions-google.js
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
/**
* Copyright 2018 The AMP HTML Authors. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS-IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import {
Action,
ActionStatus,
SubscriptionAnalytics,
} from '../../../amp-subscriptions/0.1/analytics';
import {
ConfiguredRuntime,
Entitlements,
SubscribeResponse,
Entitlement as SwgEntitlement,
} from '../../../../third_party/subscriptions-project/swg';
import {
Entitlement,
GrantReason,
} from '../../../amp-subscriptions/0.1/entitlement';
import {
GoogleSubscriptionsPlatform,
getAmpFetcherClassForTesting,
} from '../amp-subscriptions-google';
import {PageConfig} from '../../../../third_party/subscriptions-project/config';
import {ServiceAdapter} from '../../../amp-subscriptions/0.1/service-adapter';
import {Services} from '../../../../src/services';
import {SubscriptionsScoreFactor} from '../../../amp-subscriptions/0.1/constants';
import {WindowInterface} from '../../../../src/window-interface';
import {toggleExperiment} from '../../../../src/experiments';
const PLATFORM_ID = 'subscribe.google.com';
const AMP_URL = 'myAMPurl.amp';
describes.realWin('AmpFetcher', {amp: true}, (env) => {
let fetcher;
let xhr;
const sentUrl = 'url';
const sentArray = [
'embed',
'tx',
'refer',
'utmS',
'utmC',
'utmM',
'sku',
true,
['exp1', 'exp2'],
'version',
'baseUrl',
];
const sentMessage = {
toArray: function () {
return sentArray;
},
};
const contentType = 'application/x-www-form-urlencoded;charset=UTF-8';
const expectedBodyString = 'f.req=' + JSON.stringify(sentArray);
const AmpFetcher = getAmpFetcherClassForTesting();
beforeEach(() => {
const {win} = env.ampdoc;
fetcher = new AmpFetcher(win);
xhr = Services.xhrFor(win);
});
it('should support beacon when beacon supported', async () => {
const expectedBlob = new Blob([expectedBodyString], {type: contentType});
env.sandbox.stub(WindowInterface, 'getSendBeacon').callsFake(() => {
return (url, body) => {
expect(url).to.equal(sentUrl);
expect(body).to.deep.equal(expectedBlob);
};
});
fetcher.sendBeacon(sentUrl, sentMessage);
});
it('should support beacon when beacon not supported', async () => {
env.sandbox.stub(WindowInterface, 'getSendBeacon').callsFake(() => null);
env.sandbox.stub(xhr, 'fetch').callsFake((url, init) => {
expect(url).to.equal(sentUrl);
expect(init).to.deep.equal({
method: 'POST',
headers: {'Content-Type': contentType},
credentials: 'include',
body: expectedBodyString,
});
});
fetcher.sendBeacon(sentUrl, sentMessage);
});
});
describes.realWin('amp-subscriptions-google', {amp: true}, (env) => {
let ampdoc;
let pageConfig;
let platform;
let serviceAdapter;
let serviceAdapterMock;
let getEncryptedDocumentKeyStub;
let analyticsMock;
let viewer;
let xhr;
let callbacks;
let methods;
let ackStub;
let element;
let entitlementResponse;
let win;
beforeEach(() => {
win = env.win;
ampdoc = env.ampdoc;
element = env.win.document.createElement('script');
element.id = 'amp-subscriptions';
env.win.document.head.appendChild(element);
env.sandbox.stub(ampdoc, 'getUrl').callsFake(() => AMP_URL);
pageConfig = new PageConfig('example.org:basic', true);
xhr = Services.xhrFor(env.win);
viewer = Services.viewerForDoc(ampdoc);
ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
serviceAdapter = new ServiceAdapter(null);
serviceAdapterMock = env.sandbox.mock(serviceAdapter);
env.sandbox
.stub(serviceAdapter, 'getPageConfig')
.callsFake(() => pageConfig);
const analytics = new SubscriptionAnalytics(ampdoc.getRootNode());
env.sandbox.stub(serviceAdapter, 'getAnalytics').callsFake(() => analytics);
analyticsMock = env.sandbox.mock(analytics);
getEncryptedDocumentKeyStub = env.sandbox
.stub(serviceAdapter, 'getEncryptedDocumentKey')
.callsFake(() => {
return null;
});
entitlementResponse = {
source: 'google',
products: ['example.org:basic'],
subscriptionToken: 'tok1',
};
callbacks = {
loginRequest: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnLoginRequest'
),
linkComplete: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnLinkComplete'
),
flowStarted: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnFlowStarted'
),
flowCanceled: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnFlowCanceled'
),
subscribeRequest: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnNativeSubscribeRequest'
),
subscribeResponse: env.sandbox.stub(
ConfiguredRuntime.prototype,
'setOnPaymentResponse'
),
};
methods = {
reset: env.sandbox.stub(ConfiguredRuntime.prototype, 'reset'),
showContributionOptions: env.sandbox.stub(
ConfiguredRuntime.prototype,
'showContributionOptions'
),
showOffers: env.sandbox.stub(ConfiguredRuntime.prototype, 'showOffers'),
showAbbrvOffer: env.sandbox.stub(
ConfiguredRuntime.prototype,
'showAbbrvOffer'
),
linkAccount: env.sandbox.stub(ConfiguredRuntime.prototype, 'linkAccount'),
};
ackStub = env.sandbox.stub(Entitlements.prototype, 'ack');
toggleExperiment(win, 'swg-gpay-api', true);
toggleExperiment(win, 'nonswgexp', true);
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
});
afterEach(() => {
serviceAdapterMock.verify();
analyticsMock.verify();
toggleExperiment(win, 'swg-gpay-api', false);
});
function callback(stub) {
return stub.args[0][0];
}
it('should set the current URL in analytics', () => {
const swgAnalytics = platform.runtime_.analytics();
expect(swgAnalytics.getContext().getUrl()).to.equal(AMP_URL);
});
it('should reset runtime on platform reset', () => {
expect(methods.reset).to.not.be.called;
platform.reset();
expect(methods.reset).to.be.calledOnce.calledWithExactly();
});
it('should listen on callbacks', () => {
expect(callbacks.loginRequest).to.be.calledOnce;
});
it('should scope the runtime to one ampdoc', () => {
expect(platform.runtime_.doc_.ampdoc_).to.equal(ampdoc);
});
it('should propagate experiment', () => {
expect(platform.runtime_.payClient_.getType()).to.equal('PAYJS');
expect(platform.runtime_.config()['experiments']).to.have.members([
'gpay-api',
]);
});
it('should proxy fetch via AMP fetcher', async () => {
const fetchStub = env.sandbox
.stub(xhr, 'fetchJson')
.callsFake((url, init) => {
expect(url).to.match(/publication\/example.org/);
expect(init).to.deep.equal({
credentials: 'include',
prerenderSafe: true,
});
return Promise.resolve({
json: () => Promise.resolve({entitlements: entitlementResponse}),
});
});
const ents = await platform.getEntitlements();
expect(ents.service).to.equal(PLATFORM_ID);
expect(fetchStub).to.be.calledOnce;
});
it('should proxy fetch non-granting response', async () => {
const fetchStub = env.sandbox
.stub(xhr, 'fetchJson')
.callsFake((url, init) => {
expect(url).to.match(/publication\/example.org/);
expect(init).to.deep.equal({
credentials: 'include',
prerenderSafe: true,
});
return Promise.resolve({
json: () =>
Promise.resolve({
entitlements: {
source: 'subscribe.google.com',
products: ['example.org:registered_user'],
subscriptionToken: 'tok1',
},
}),
});
});
const ents = await platform.getEntitlements();
expect(ents.source).to.equal(PLATFORM_ID);
expect(ents.granted).to.be.false;
expect(fetchStub).to.be.calledOnce;
});
it('should proxy fetch empty response', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () =>
Promise.resolve({
entitlements: {},
}),
})
);
const ents = await platform.getEntitlements();
expect(ents).to.be.null;
});
it('should ack matching entitlements', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: entitlementResponse}),
})
);
await platform.getEntitlements();
expect(ackStub).to.be.calledOnce;
});
it('should NOT ack non-matching entitlements', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () =>
Promise.resolve({
entitlements: {},
}),
})
);
await platform.getEntitlements();
expect(ackStub).to.not.be.called;
});
it('should ignore activate when granted', () => {
platform.activate(
new Entitlement({
service: PLATFORM_ID,
granted: true,
grantReason: GrantReason.SUBSCRIBER,
})
);
expect(methods.showOffers).to.not.be.called;
expect(methods.showAbbrvOffer).to.not.be.called;
});
it('should show offers on activate when not granted', () => {
platform.activate(new Entitlement({service: PLATFORM_ID, granted: false}));
expect(methods.showOffers).to.be.calledOnce.calledWithExactly({
list: 'amp',
});
expect(methods.showAbbrvOffer).to.not.be.called;
});
it('should show abbrv offer on activate when granted non-subscriber', () => {
platform.activate(
new Entitlement({
service: PLATFORM_ID,
granted: true,
grantReason: GrantReason.METERING,
})
);
expect(methods.showAbbrvOffer).to.be.calledOnce.calledWithExactly({
list: 'amp',
});
expect(methods.showOffers).to.not.be.called;
});
it('should override show offers with the grant for subscriber', () => {
const entitlement = new Entitlement({service: PLATFORM_ID, granted: false});
const grantEntitlement = new Entitlement({
service: 'local',
granted: true,
grantReason: GrantReason.SUBSCRIBER,
});
platform.activate(entitlement, grantEntitlement);
expect(methods.showOffers).to.not.be.called;
expect(methods.showAbbrvOffer).to.not.be.called;
});
it('should override show offers with the grant non-subscriber', () => {
const entitlement = new Entitlement({service: PLATFORM_ID, granted: false});
const grantEntitlement = new Entitlement({
service: 'local',
granted: true,
grantReason: GrantReason.METERING,
});
platform.activate(entitlement, grantEntitlement);
expect(methods.showOffers).to.not.be.called;
expect(methods.showAbbrvOffer).to.be.calledOnce;
});
it('should start linking flow when requested', async () => {
serviceAdapterMock
.expects('getReaderId')
.withExactArgs('local')
.returns(Promise.resolve('ari1'))
.once();
serviceAdapterMock.expects('delegateActionToLocal').never();
callback(callbacks.loginRequest)({linkRequested: true});
await 'Event loop tick';
expect(methods.linkAccount).to.be.calledOnce.calledWithExactly({
ampReaderId: 'ari1',
});
});
it('should delegate login when linking not requested', () => {
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.LOGIN)
.returns(Promise.resolve(false))
.once();
callback(callbacks.loginRequest)({linkRequested: false});
expect(methods.linkAccount).to.not.be.called;
});
it('should delegate login for a non-google viewer', () => {
platform.isGoogleViewer_ = false;
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.LOGIN)
.returns(Promise.resolve(false))
.once();
callback(callbacks.loginRequest)({linkRequested: true});
expect(methods.linkAccount).to.not.be.called;
});
it('should not allow prerender for non-google viewer', () => {
platform.isGoogleViewer_ = false;
expect(platform.isPrerenderSafe()).to.be.false;
});
it('should reauthorize on complete linking', () => {
analyticsMock
.expects('actionEvent')
.withExactArgs(PLATFORM_ID, Action.LINK, ActionStatus.SUCCESS)
.once();
serviceAdapterMock.expects('resetPlatforms').once();
callback(callbacks.linkComplete)();
});
it('should reauthorize on canceled linking', () => {
analyticsMock
.expects('actionEvent')
.withExactArgs(PLATFORM_ID, Action.LINK, ActionStatus.REJECTED)
.once();
serviceAdapterMock.expects('resetPlatforms').once();
callback(callbacks.flowCanceled)({flow: 'linkAccount'});
});
describe('should log subscribe start', () => {
let productId;
let data;
afterEach(() => {
analyticsMock
.expects('actionEvent')
.withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.STARTED, {
active: true,
product: productId,
})
.once();
callback(callbacks.flowStarted)({flow: Action.SUBSCRIBE, data});
});
it('should work without a productId', () => {
productId = 'unknown productId';
});
it('should work with a productId', () => {
productId = 'PRODUCTID';
data = {
product: productId,
};
});
});
it('should log subscribe cancel', () => {
analyticsMock
.expects('actionEvent')
.withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.REJECTED)
.once();
callback(callbacks.flowCanceled)({flow: Action.SUBSCRIBE});
});
describe('should reauthorize on complete subscribe', () => {
let productId;
let entitlements;
const serviceId = 'serviceId';
afterEach(() => {
analyticsMock
.expects('actionEvent')
.withExactArgs(PLATFORM_ID, Action.SUBSCRIBE, ActionStatus.SUCCESS, {
active: true,
product: productId,
})
.once();
const promise = Promise.resolve();
const response = new SubscribeResponse(
null,
null,
null,
entitlements,
productId,
() => promise,
null
);
const resetPlatformsPromise = new Promise((resolve) => {
env.sandbox.stub(serviceAdapter, 'resetPlatforms').callsFake(() => {
resolve();
});
});
callback(callbacks.subscribeResponse)(Promise.resolve(response));
expect(methods.reset).to.not.be.called;
return resetPlatformsPromise;
});
it('should work without entitlements', () => {
productId = 'unknown subscriptionToken';
entitlements = null;
});
it('should work with poorly formatted entitlements', () => {
productId = 'unknown subscriptionToken';
entitlements = new Entitlements(
serviceId,
null,
[new SwgEntitlement(null, [productId], null)],
productId
);
});
it('should work with Google formatted entitlements', () => {
productId = 'myProduct';
const token = JSON.stringify({
productId,
});
entitlements = new Entitlements(
serviceId,
null,
[new SwgEntitlement('google', [productId], token)],
productId
);
});
});
it('should delegate native subscribe request', () => {
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.SUBSCRIBE)
.returns(Promise.resolve(false))
.once();
callback(callbacks.subscribeRequest)();
});
it('should reset on successful login', async () => {
const loginResult = Promise.resolve(true);
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.LOGIN)
.returns(loginResult)
.once();
callback(callbacks.loginRequest)({linkRequested: false});
await loginResult;
expect(methods.reset).to.be.calledOnce.calledWithExactly();
});
it('should NOT reset on failed login', async () => {
const loginResult = Promise.resolve(false);
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.LOGIN)
.returns(loginResult)
.once();
callback(callbacks.loginRequest)({linkRequested: false});
await loginResult;
expect(methods.reset).to.not.be.called;
});
it('should reset on successful subscribe', async () => {
const loginResult = Promise.resolve(true);
serviceAdapterMock
.expects('delegateActionToLocal')
.withExactArgs(Action.SUBSCRIBE)
.returns(loginResult)
.once();
callback(callbacks.subscribeRequest)();
await loginResult;
expect(methods.reset).to.be.calledOnce.calledWithExactly();
});
it('should infer the viewer from viewerUrl', () => {
delete ampdoc.params_['viewerUrl'];
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
expect(platform.isGoogleViewer_).to.be.false;
ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
expect(platform.isGoogleViewer_).to.be.true;
});
it('should infer the viewer from origin', async () => {
delete ampdoc.params_['viewerUrl'];
let viewerOrigin = null;
env.sandbox.stub(viewer, 'getViewerOrigin').callsFake(() => viewerOrigin);
await 'Event loop tick';
viewerOrigin = Promise.resolve('');
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
await viewerOrigin;
expect(platform.isGoogleViewer_).to.be.false;
// Other origin.
viewerOrigin = Promise.resolve('https://other.com');
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
await viewerOrigin;
expect(platform.isGoogleViewer_).to.be.false;
// Google origin.
viewerOrigin = Promise.resolve('https://google.com');
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
await viewerOrigin;
expect(platform.isGoogleViewer_).to.be.true;
});
it('should allow prerender if in a google viewer', () => {
ampdoc.params_['viewerUrl'] = 'https://www.google.com/other';
platform = new GoogleSubscriptionsPlatform(ampdoc, {}, serviceAdapter);
expect(platform.isPrerenderSafe()).to.be.true;
});
it('should attach button given to decorateUI', () => {
const elem = env.win.document.createElement('div');
const decorateStub = env.sandbox.stub(
platform.runtime_.buttonApi_,
'attach'
);
elem.textContent = 'some html';
platform.decorateUI(elem, 'subscribe');
expect(elem.textContent).to.be.equal('');
expect(decorateStub).to.be.calledWith(elem);
});
it('should attach smartbutton given to decorateUI', () => {
const elem = env.win.document.createElement('div');
const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
elem.textContent = 'some html';
elem.setAttribute('subscriptions-lang', 'en');
platform.decorateUI(elem, 'subscribe-smartbutton');
expect(elem.textContent).to.be.equal('');
expect(attachStub).to.be.calledWith(elem, {lang: 'en', theme: 'light'});
});
it('should use light smartbutton theme', () => {
const elem = env.win.document.createElement('div');
const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
elem.textContent = 'some html';
elem.setAttribute('subscriptions-lang', 'en');
platform.decorateUI(elem, 'subscribe-smartbutton-light');
expect(elem.textContent).to.be.equal('');
expect(attachStub).to.be.calledWith(elem, {theme: 'light', lang: 'en'});
});
it('should use dark smartbutton theme', () => {
const elem = env.win.document.createElement('div');
const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
elem.textContent = 'some html';
elem.setAttribute('subscriptions-lang', 'en');
platform.decorateUI(elem, 'subscribe-smartbutton-dark');
expect(elem.textContent).to.be.equal('');
expect(attachStub).to.be.calledWith(elem, {theme: 'dark', lang: 'en'});
});
it('should use message text color', () => {
const elem = env.win.document.createElement('div');
const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
elem.textContent = 'some html';
elem.setAttribute('subscriptions-lang', 'en');
elem.setAttribute('subscriptions-message-text-color', '#09f');
platform.decorateUI(elem, 'subscribe-smartbutton');
expect(elem.textContent).to.be.equal('');
expect(attachStub).to.be.calledWith(elem, {
lang: 'en',
messageTextColor: '#09f',
theme: 'light',
});
});
it('should use message number', () => {
const elem = env.win.document.createElement('div');
const attachStub = env.sandbox.stub(platform.runtime_, 'attachSmartButton');
elem.textContent = 'some html';
elem.setAttribute('subscriptions-lang', 'en');
elem.setAttribute('subscriptions-message-number', 1);
platform.decorateUI(elem, 'subscribe-smartbutton');
expect(attachStub).to.be.calledWith(elem, {
lang: 'en',
theme: 'light',
messageNumber: '1', // Message is 'Subscribe with just a few taps' on smartbox button.
});
});
it('should throw if smartButton language is missing', () => {
//expectAsyncConsoleError(/must have a language attrbiute/);
const elem = env.win.document.createElement('div');
elem.textContent = 'some html';
expect(() => {
allowConsoleError(() => {
platform.decorateUI(elem, 'subscribe-smartbutton');
});
}).to.throw(/language/);
});
it('should show offers if subscribe action is delegated', () => {
const executeStub = platform.runtime_.showOffers;
platform.executeAction(Action.SUBSCRIBE);
expect(executeStub).to.be.calledWith({list: 'amp', isClosable: true});
});
it('should show contributions if contribute action is delegated', () => {
const executeStub = platform.runtime_.showContributionOptions;
platform.executeAction(Action.CONTRIBUTE);
expect(executeStub).to.be.calledWith({list: 'amp', isClosable: true});
});
it('should link accounts if login action is delegated', async () => {
serviceAdapterMock
.expects('getReaderId')
.withExactArgs('local')
.returns(Promise.resolve('ari1'))
.once();
const executeStub = platform.runtime_.linkAccount;
platform.executeAction(Action.LOGIN);
await 'Event loop tick';
expect(executeStub).to.be.calledWith();
});
describe('getEntitlements', () => {
it('should convert granted entitlements to internal shape', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: entitlementResponse}),
})
);
const entitlement = await platform.getEntitlements();
expect(entitlement.source).to.be.equal('google');
expect(entitlement.granted).to.be.equal(true);
expect(entitlement.grantReason).to.be.equal(GrantReason.SUBSCRIBER);
expect(entitlement.data).to.deep.equal(entitlementResponse);
});
it('should convert non granted internal shape with granted == false', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () =>
Promise.resolve({
entitlements: {
source: 'google',
products: ['example.org:premium'],
subscriptionToken: '',
},
}),
})
);
const entitlement = await platform.getEntitlements();
expect(entitlement.source).to.be.equal('google');
expect(entitlement.granted).to.be.equal(false);
expect(entitlement.grantReason).to.be.null;
});
});
describe('isReadyToPay', () => {
// #TODO(jpettitt) remove fake entitlements when swj.js
// isReadyToPay is available
/**
* return a fake entitlements object
* @param {boolean} isReadyToPay
* @return {Object}
*/
function fakeEntitlements(isReadyToPay) {
return {
isReadyToPay,
entitlements: {},
getEntitlementForThis: () => {},
};
}
it('should treat missing isReadyToPay as false', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: entitlementResponse}),
})
);
await platform.getEntitlements();
expect(
platform.getSupportedScoreFactor(
SubscriptionsScoreFactor.IS_READY_TO_PAY
)
).to.equal(0);
});
it('should handle isReadyToPay true', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () =>
Promise.resolve({
isReadyToPay: true,
entitlements: entitlementResponse,
}),
})
);
//#TODO(jpettitt) remove stub when swj.js isRadyToPay is available
env.sandbox
.stub(platform.runtime_, 'getEntitlements')
.resolves(fakeEntitlements(true));
await platform.getEntitlements();
expect(
platform.getSupportedScoreFactor(
SubscriptionsScoreFactor.IS_READY_TO_PAY
)
).to.equal(1);
});
it('should handle isReadyToPay false', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () =>
Promise.resolve({
isReadyToPay: false,
entitlements: entitlementResponse,
}),
})
);
//#TODO(jpettitt) remove stub when swj.js isRadyToPay is available
env.sandbox
.stub(platform.runtime_, 'getEntitlements')
.resolves(fakeEntitlements(false));
await platform.getEntitlements();
expect(
platform.getSupportedScoreFactor(
SubscriptionsScoreFactor.IS_READY_TO_PAY
)
).to.equal(0);
});
it('should call getEncryptedDocumentKey with google.com', async () => {
env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: {}}),
})
);
await platform.getEntitlements();
expect(getEncryptedDocumentKeyStub).to.be.calledWith('google.com');
});
it('should not add encryptedDocumentKey parameter to url', async () => {
const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: {}}),
})
);
await platform.getEntitlements();
expect(fetchStub).to.be.calledWith(
'https://news.google.com/swg/_/api/v1/publication/example.org/entitlements'
);
});
it('should add encryptedDocumentKey parameter to url', async () => {
const fetchStub = env.sandbox.stub(xhr, 'fetchJson').callsFake(() =>
Promise.resolve({
json: () => Promise.resolve({entitlements: {}}),
})
);
getEncryptedDocumentKeyStub.callsFake(() => 'encryptedDocumentKey');
await platform.getEntitlements();
expect(fetchStub).to.be.calledWith(
'https://news.google.com/swg/_/api/v1/publication/example.org/entitlements?crypt=encryptedDocumentKey'
);
});
});
});