-
Notifications
You must be signed in to change notification settings - Fork 123
/
Copy pathproduct-component.js
2569 lines (2192 loc) · 89.3 KB
/
product-component.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
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import Product from '../../../src/components/product';
import Checkout from '../../../src/components/checkout';
import Cart from '../../../src/components/cart';
import Template from '../../../src/template';
import Component from '../../../src/component';
import ProductView from '../../../src/views/product';
import ProductUpdater from '../../../src/updaters/product';
import windowUtils from '../../../src/utils/window-utils';
import ShopifyBuy from '../../../src/buybutton';
import shopFixture from '../../fixtures/shop-info';
import productFixture from '../../fixtures/product-fixture';
import * as normalizeConfig from '../../../src/utils/normalize-config';
import * as formatMoney from '../../../src/utils/money';
import * as browserFeatures from '../../../src/utils/detect-features';
import * as getUnitPriceBaseUnit from '../../../src/utils/unit-price';
const rootImageURI = 'https://cdn.shopify.com/s/files/1/0014/8583/2214/products/';
describe('Product Component class', () => {
let product;
let dateNowStub;
const mockTime = 123;
beforeEach(() => {
dateNowStub = sinon.stub(Date, 'now').returns(mockTime);
});
afterEach(() => {
dateNowStub.restore();
});
describe('constructor', () => {
let normalizeConfigStub;
const props = {};
const constructorConfig = {
id: 123,
node: document.createElement('div'),
storefrontVariantId: 456,
option: {
templates: '<div>div</div>',
contents: {},
order: {},
},
};
beforeEach(() => {
normalizeConfigStub = sinon.stub(normalizeConfig, 'default').callsFake((oldConfig) => {
oldConfig.storefrontId = 'normalizedId';
return oldConfig;
});
product = new Product(constructorConfig, props);
});
afterEach(() => {
normalizeConfigStub.restore();
});
it('normalizes config', () => {
assert.calledOnce(normalizeConfigStub);
assert.calledWith(normalizeConfigStub, constructorConfig);
assert.equal(constructorConfig.storefrontId, 'normalizedId');
});
it('sets typeKey to product', () => {
assert.equal(product.typeKey, 'product');
});
it('sets defaultStorefrontVariantId to config\'s storefrontVariantId', () => {
assert.equal(product.defaultStorefrontVariantId, constructorConfig.storefrontVariantId);
});
it('sets cachedImage, cart, modal, and selectedImage to null', () => {
assert.isNull(product.cachedImage);
assert.isNull(product.cart);
assert.isNull(product.modal);
assert.isNull(product.selectedImage);
});
it('creates a childTemplate for options', () => {
assert.instanceOf(product.childTemplate, Template);
});
it('sets imgStyle to an empty string', () => {
assert.equal(product.imgStyle, '');
});
it('sets selectedQuantity to 1', () => {
assert.equal(product.selectedQuantity, 1);
});
it('sets selectedVariant and selectedOptions to an empty object', () => {
assert.deepEqual(product.selectedVariant, {});
assert.deepEqual(product.selectedOptions, {});
});
it('creates a new updater', () => {
assert.instanceOf(product.updater, ProductUpdater);
});
it('creates a new view', () => {
assert.instanceOf(product.view, ProductView);
});
it('sets modalProduct to false if it is not provided in the config', () => {
assert.equal(product.modalProduct, false);
});
it('sets modalProduct to true if it is set to true in the config', () => {
const modalProductConfig = Object.assign({}, constructorConfig);
modalProductConfig.modalProduct = true;
product = new Product(modalProductConfig, props);
assert.equal(product.modalProduct, true);
});
});
describe('prototype methods', () => {
let props;
const config = {
id: 123,
node: document.getElementById('qunit-fixture'),
options: {
product: {
viewData: {
test: 'test string',
},
},
},
};
const fetchData = {};
const fetchHandleData = {};
let testProductCopy;
let configCopy;
let trackSpy;
let trackMethodStub;
let closeModalSpy;
let setActiveElSpy;
let fetchInfoStub;
let fetchStub;
let fetchByHandleStub;
beforeEach(() => {
trackSpy = sinon.spy();
trackMethodStub = sinon.stub().callsFake((fn) => {
return function(...params) {
fn(...params);
};
});
closeModalSpy = sinon.spy();
setActiveElSpy = sinon.spy();
props = {
client: ShopifyBuy.buildClient({
domain: 'test.myshopify.com',
storefrontAccessToken: 123,
}),
browserFeatures: {
transition: true,
animation: true,
transform: true,
},
tracker: {
trackMethod: trackMethodStub,
track: trackSpy,
},
createCart() {
return Promise.resolve(new Cart(config, {
tracker: {
trackMethod: (fn) => {
return function(...params) {
fn(...params);
};
},
},
}));
},
closeModal: closeModalSpy,
setActiveEl: setActiveElSpy,
};
configCopy = Object.assign({}, config);
configCopy.node = document.createElement('div');
configCopy.node.setAttribute('id', 'fixture');
document.body.appendChild(configCopy.node);
testProductCopy = Object.assign({}, productFixture);
product = new Product(configCopy, props);
fetchInfoStub = sinon.stub(props.client.shop, 'fetchInfo').resolves(shopFixture);
fetchStub = sinon.stub(product.props.client.product, 'fetch').resolves(fetchData);
fetchByHandleStub = sinon.stub(product.props.client.product, 'fetchByHandle').resolves(fetchHandleData);
});
afterEach(() => {
fetchInfoStub.restore();
fetchStub.restore();
fetchByHandleStub.restore();
document.body.removeChild(configCopy.node);
});
describe('stopPropagation()', () => {
let event;
let stopImmediatePropagationSpy;
beforeEach(() => {
stopImmediatePropagationSpy = sinon.spy();
event = {
stopImmediatePropagation: stopImmediatePropagationSpy,
};
});
it('stops propagation of event if component is a button', () => {
product = Object.defineProperty(product, 'isButton', {
value: true,
});
product.stopPropagation(event);
assert.calledOnce(stopImmediatePropagationSpy);
});
it('does not stop propagation of event if component is not a button', () => {
product = Object.defineProperty(product, 'isButton', {
value: false,
});
product.stopPropagation(event);
assert.notCalled(stopImmediatePropagationSpy);
});
});
describe('openOnlineStore()', () => {
let userEventStub;
let windowOpenStub;
beforeEach(() => {
product = Object.defineProperty(product, 'onlineStoreURL', {
value: 'test.com',
});
userEventStub = sinon.stub(product, '_userEvent');
windowOpenStub = sinon.stub(window, 'open');
product.openOnlineStore();
});
afterEach(() => {
userEventStub.restore();
windowOpenStub.restore();
});
it('calls userEvent with openOnlineStore', () => {
assert.calledOnce(userEventStub);
assert.calledWith(userEventStub, 'openOnlineStore');
});
it('opens window with online store url', () => {
assert.calledOnce(windowOpenStub);
assert.calledWith(windowOpenStub, product.onlineStoreURL);
});
});
describe('init()', () => {
let createCartStub;
let renderStub;
const cartMock = {
node: {},
view: {},
template: {},
};
beforeEach(() => {
createCartStub = sinon.stub(product.props, 'createCart').resolves(cartMock);
renderStub = sinon.stub(product.view, 'render');
});
afterEach(() => {
createCartStub.restore();
renderStub.restore();
});
describe('successful model', () => {
let superInitStub;
const modelMock = {model: {}};
beforeEach(async () => {
superInitStub = sinon.stub(Component.prototype, 'init').resolves(modelMock);
await product.init('test');
});
afterEach(() => {
superInitStub.restore();
});
it('creates a cart then initializes component', () => {
assert.equal(product.cart, cartMock);
assert.calledOnce(createCartStub);
assert.calledOnce(superInitStub);
assert.calledWith(superInitStub, 'test');
});
it('renders view if model is returned from init', () => {
assert.calledOnce(renderStub);
});
it('returns the model', async () => {
assert.equal(await product.init('test'), modelMock);
});
});
it('does not render view if model is not returned from init', async () => {
const superInitStub = sinon.stub(Component.prototype, 'init').resolves(null);
await product.init('test');
assert.notCalled(renderStub);
superInitStub.restore();
});
});
describe('createCart()', () => {
let createCartStub;
beforeEach(() => {
createCartStub = sinon.stub(props, 'createCart').returns('cart');
});
afterEach(() => {
createCartStub.restore();
});
it('calls props createCart with correct config', () => {
product.globalConfig = {
globalConfig: 'globalConfig',
};
const expectedObj = {
globalConfig: product.globalConfig.globalConfig,
node: product.globalConfig.cartNode,
options: product.config,
};
product.createCart();
assert.calledOnce(createCartStub);
assert.calledWith(createCartStub, expectedObj);
});
it('returns props createCart return value', () => {
assert.equal(product.createCart(), 'cart');
});
});
describe('setupModel()', () => {
let superSetupModelStub;
let setDefaultVariantStub;
let modelMock;
let data;
beforeEach(() => {
data = {
id: '1',
title: 'hat',
};
modelMock = {
id: '2',
title: 'top',
};
superSetupModelStub = sinon.stub(Component.prototype, 'setupModel').resolves(modelMock);
setDefaultVariantStub = sinon.stub(product, 'setDefaultVariant').resolves(productFixture);
});
afterEach(() => {
superSetupModelStub.restore();
setDefaultVariantStub.restore();
});
it('calls parents setupModel and sets default varint with returned model', async () => {
await product.setupModel(data);
assert.calledOnce(superSetupModelStub);
assert.calledWith(superSetupModelStub, data);
assert.calledOnce(setDefaultVariantStub);
assert.calledWith(setDefaultVariantStub, modelMock);
});
it('returns setDefaultVariant value', async () => {
assert.equal(await product.setupModel(data), productFixture);
});
});
describe('sdkFetch()', () => {
it('fetches and returns data with fetch using the first product storefront id if storefront id is passed in as an array', async () => {
product.storefrontId = ['Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzEyMzQ1'];
const data = await product.sdkFetch();
assert.calledOnce(fetchStub);
assert.calledWith(fetchStub, 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzEyMzQ1');
assert.equal(data, fetchData);
});
it('fetches and returns data with fetch using product storefront id', async () => {
product.storefrontId = 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzEyMzQ1';
const data = await product.sdkFetch();
assert.calledOnce(fetchStub);
assert.calledWith(fetchStub, 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0LzEyMzQ1');
assert.equal(data, fetchData);
});
it('fetches and returns data with fetchByHandle using product handle', async () => {
product.storefrontId = null;
product.handle = 'hat';
const data = await product.sdkFetch();
assert.calledOnce(fetchByHandleStub);
assert.calledWith(fetchByHandleStub, 'hat');
assert.equal(data, fetchHandleData);
});
it('rejects if there is an empty storefrontId array and no handle', async () => {
product.storefrontId = [];
product.handle = null;
try {
await product.sdkFetch();
assert.fail();
} catch (err) {
assert.equal(err.message, 'SDK Fetch Failed');
}
});
it('rejects if there is a falsey storefrontId array [null] and no handle', async () => {
product.storefrontId = [null];
product.handle = null;
try {
await product.sdkFetch();
assert.fail();
} catch (err) {
assert.equal(err.message, 'SDK Fetch Failed');
}
});
it('rejects if there is a falsey storefrontId array [""] and no handle', async () => {
product.storefrontId = [""];
product.handle = null;
try {
await product.sdkFetch();
assert.fail();
} catch (err) {
assert.equal(err.message, 'SDK Fetch Failed');
}
});
it('rejects if there is a falsey storefrontId array [0] and no handle', async () => {
product.storefrontId = [0];
product.handle = null;
try {
await product.sdkFetch();
assert.fail();
} catch (err) {
assert.equal(err.message, 'SDK Fetch Failed');
}
});
it('rejects if there is no storefrontId or handle', async () => {
product.storefrontId = null;
product.handle = null;
try {
await product.sdkFetch();
assert.fail();
} catch (err) {
assert.equal(err.message, 'SDK Fetch Failed');
}
});
});
describe('fetchData', () => {
describe('if sdkFetch returns a model', () => {
let sdkFetchStub;
const modelMock = {
id: '1',
handle: 'hat',
};
beforeEach(() => {
sdkFetchStub = sinon.stub(product, 'sdkFetch').resolves(modelMock);
});
afterEach(() => {
sdkFetchStub.restore();
});
it('sets storefront id and handle to the respective params in the model returned by sdkFetch', async () => {
await product.fetchData();
assert.equal(product.storefrontId, modelMock.id);
assert.equal(product.handle, modelMock.handle);
});
it('returns the model returned by sdkFetch', async () => {
assert.equal(await product.fetchData(), modelMock);
});
});
it('throws a Not Found error if sdkFetch does not return a model', async () => {
const sdkFetchStub = sinon.stub(product, 'sdkFetch').resolves();
try {
await product.fetchData();
} catch (error) {
assert.equal(error, 'Error: Not Found');
}
assert.throws(product.fetchData, Error);
sdkFetchStub.restore();
});
});
describe('onButtonClick()', () => {
let stopPropagationStub;
let userEventStub;
const evt = new Event('click shopify-buy__btn--parent');
const target = 'shopify-buy__btn--parent';
beforeEach(async () => {
const newProduct = await product.init(testProductCopy);
newProduct.cart.model.lineItems = [];
newProduct.cart.props.client = newProduct.props.client;
stopPropagationStub = sinon.stub(Event.prototype, 'stopPropagation');
userEventStub = sinon.stub(product, '_userEvent');
});
afterEach(() => {
stopPropagationStub.restore();
userEventStub.restore();
});
it('stops propagation', () => {
product.config.product.buttonDestination = () => { return; };
product.onButtonClick(evt, target);
assert.calledOnce(stopPropagationStub);
});
it('calls buttonDestination if it is a function', () => {
const buttonDestinationSpy = sinon.spy();
product.config.product.buttonDestination = buttonDestinationSpy;
product.onButtonClick(evt, target);
assert.calledOnce(buttonDestinationSpy);
assert.calledWith(buttonDestinationSpy, product);
});
describe('if button destination is cart', () => {
let addToCartStub;
beforeEach(() => {
product.config.product.buttonDestination = 'cart';
addToCartStub = sinon.stub(product.cart, 'addVariantToCart');
});
it('closes modal', () => {
product.onButtonClick(evt, target);
assert.calledOnce(closeModalSpy);
});
it('calls userEvent with addVariantToCart', () => {
product.onButtonClick(evt, target);
assert.calledOnce(userEventStub);
assert.calledWith(userEventStub, 'addVariantToCart');
});
it('tracks addVariantToCart', () => {
product.onButtonClick(evt, target);
assert.calledOnce(trackMethodStub);
assert.calledWith(trackMethodStub, sinon.match.func, 'Update Cart', product.selectedVariantTrackingInfo);
assert.calledOnce(addToCartStub);
trackMethodStub.getCall(0).args[0]();
assert.calledTwice(addToCartStub);
});
it('adds variant to cart with the right quantity of selected variant', () => {
product.selectedQuantity = 1111;
product.onButtonClick(evt, target);
assert.calledOnce(addToCartStub);
assert.calledWith(addToCartStub, product.selectedVariant, 1111);
addToCartStub.restore();
});
it('sets the active element to the target if it is not a modal product', () => {
product.modalProduct = false;
product.onButtonClick(evt, target);
assert.calledOnce(setActiveElSpy);
assert.calledWith(setActiveElSpy, target);
});
it('does not set the active element if it is a modal product', () => {
product.modalProduct = true;
product.onButtonClick(evt, target);
assert.notCalled(setActiveElSpy);
});
});
describe('if button destination is modal', () => {
let openModalStub;
beforeEach(() => {
product.config.product.buttonDestination = 'modal';
openModalStub = sinon.stub(product, 'openModal');
product.onButtonClick(evt, target);
});
afterEach(() => {
openModalStub.restore();
});
it('sets active element to target', () => {
assert.calledOnce(setActiveElSpy);
assert.calledWith(setActiveElSpy, target);
});
it('tracks open modal', () => {
assert.calledOnce(trackSpy);
assert.calledWith(trackSpy, 'Open modal', product.productTrackingInfo);
});
it('opens modal', () => {
assert.calledOnce(openModalStub);
});
});
it('opens online store if button destination is online store', () => {
const openOnlineStoreStub = sinon.stub(product, 'openOnlineStore');
product.config.product.buttonDestination = 'onlineStore';
product.onButtonClick(evt, target);
assert.calledOnce(openOnlineStoreStub);
openOnlineStoreStub.restore();
});
describe('if button destination is checkout', () => {
let createCheckoutStub;
let openWindowStub;
const checkoutMock = {id: 1, webUrl: window.location.href};
beforeEach(() => {
product.config.product.buttonDestination = 'checkout';
createCheckoutStub = sinon.stub(product.props.client.checkout, 'create').returns(Promise.resolve(checkoutMock));
openWindowStub = sinon.stub(window, 'open').returns({location: ''});
});
afterEach(() => {
openWindowStub.restore();
createCheckoutStub.restore();
});
it('calls userEvent with openCheckout', () => {
product.onButtonClick(evt, target);
assert.calledOnce(userEventStub);
assert.calledWith(userEventStub, 'openCheckout');
});
it('tracks Direct Checkout', () => {
product.onButtonClick(evt, target);
assert.calledOnce(trackSpy);
assert.calledWith(trackSpy, 'Direct Checkout', {});
});
it('opens checkout in a new window if cart popup in config is true and browser supports window.open', () => {
product.config.cart.popup = true;
const browserFeaturesStub = sinon.stub(browserFeatures, 'default').value({
windowOpen: () => true,
});
const checkout = new Checkout(product.config);
product.onButtonClick(evt, target);
assert.calledOnce(openWindowStub);
assert.calledWith(openWindowStub, '', 'checkout', checkout.params);
browserFeaturesStub.restore();
});
it('does not open checkout in a new window if browser does not support window.open', () => {
product.config.cart.popup = true;
const browserFeaturesStub = sinon.stub(browserFeatures, 'default').value({
windowOpen: () => false,
});
createCheckoutStub.rejects();
product.onButtonClick(evt, target);
assert.notCalled(openWindowStub);
browserFeaturesStub.restore();
});
it('creates checkout with line items', () => {
const selectedQuantity = 2;
product.selectedQuantity = selectedQuantity;
product.onButtonClick(evt, target);
assert.calledOnce(createCheckoutStub);
assert.calledWith(createCheckoutStub, {lineItems: [{
variantId: 'Z2lkOi8vc2hvcGlmeS9Qcm9kdWN0VmFyaWFudC8xMjM0NQ==',
quantity: selectedQuantity,
customAttributes: [],
}]});
});
});
});
describe('onBlockButtonKeyup()', () => {
let event;
let onButtonClickStub;
const target = {};
beforeEach(() => {
event = {};
onButtonClickStub = sinon.stub(product, 'onButtonClick');
});
afterEach(() => {
onButtonClickStub.restore();
});
it('calls onButtonClick if event keycode is the enter key', () => {
event.keyCode = 13; // enter key
product.onBlockButtonKeyup(event, target);
assert.calledOnce(onButtonClickStub);
assert.calledWith(onButtonClickStub, event, target);
});
it('does not call onButtonClick if event keycode is not the enter key', () => {
event.keyCode = 99;
product.onBlockButtonKeyup(event, target);
assert.notCalled(onButtonClickStub);
});
});
describe('onOptionSelect()', () => {
it('calls updateVariant with event target name and value', () => {
const updateVariantStub = sinon.stub(product, 'updateVariant');
const event = {
target: {
getAttribute(arg) {
return arg;
},
selectedIndex: 'index',
options: {
index: {
value: 'targetValue',
},
},
},
};
product.onOptionSelect(event);
assert.calledOnce(updateVariantStub);
assert.calledWith(updateVariantStub, 'name', 'targetValue');
updateVariantStub.restore();
});
});
describe('onQuantityBlur()', () => {
it('calls updateQuantity with function to parse target value', () => {
const target = {
value: '10',
};
const event = {};
const updateQuantityStub = sinon.stub(product, 'updateQuantity');
product.onQuantityBlur(event, target);
assert.calledOnce(updateQuantityStub);
const callbackValue = updateQuantityStub.getCall(0).args[0]();
assert.equal(callbackValue, 10);
updateQuantityStub.restore();
});
});
describe('onQuantityIncrement()', () => {
it('calls updateQuantity with function to add previous quantity with quantity param', () => {
const updateQuantityStub = sinon.stub(product, 'updateQuantity');
product.onQuantityIncrement(3);
assert.calledOnce(updateQuantityStub);
const callbackValue = updateQuantityStub.getCall(0).args[0](2);
assert.equal(callbackValue, 5);
updateQuantityStub.restore();
});
});
describe('closeCartOnBgClick()', () => {
let closeSpy;
beforeEach(() => {
closeSpy = sinon.spy();
product.cart = {
close: closeSpy,
};
});
it('closes cart if it is visible', () => {
product.cart.isVisible = true;
product.closeCartOnBgClick();
assert.calledOnce(closeSpy);
});
it('does not close cart if is not visible', () => {
product.cart.isVisible = false;
product.closeCartOnBgClick();
assert.notCalled(closeSpy);
});
});
describe('onCarouselItemClick()', () => {
let preventDefaultStub;
let renderStub;
let event;
let target;
beforeEach(() => {
event = new Event('click');
target = document.createElement('div');
preventDefaultStub = sinon.stub(event, 'preventDefault');
renderStub = sinon.stub(product.view, 'render');
product.model = productFixture;
});
afterEach(() => {
renderStub.restore();
});
it('prevents the event\'s default', () => {
product.onCarouselItemClick(event, target);
assert.calledOnce(preventDefaultStub);
});
it('sets selected and cached image to image if the image clicked exists in the model', () => {
target.setAttribute('data-image-id', '1');
const expectedImage = {
id: '1',
src: `${rootImageURI}image-one.jpg`,
};
product.onCarouselItemClick(event, target);
assert.deepEqual(product.selectedImage, expectedImage);
assert.deepEqual(product.cachedImage, expectedImage);
});
it('keeps old selected and cached image if the image clicked does not exist in model', () => {
target.setAttribute('data-image-id', 'not a valid id');
const expectedImage = {
id: '2',
src: `${rootImageURI}image-two.jpeg`,
};
product.selectedImage = expectedImage;
product.cachedImage = expectedImage;
product.onCarouselItemClick(event, target);
assert.equal(product.selectedImage, expectedImage);
assert.equal(product.cachedImage, expectedImage);
});
it('renders the view', () => {
product.onCarouselItemClick(event, target);
assert.calledOnce(renderStub);
});
});
describe('nextIndex()', () => {
beforeEach(() => {
product.model = {
images: [1, 2, 3, 4, 5, 6],
};
});
it('returns the sum of the two params if it is above zero and less than the number of images in the model', () => {
assert.equal(product.nextIndex(2, 3), 5);
});
it('returns 0 if the sum of the two params is equal to the number of images in the model', () => {
assert.equal(product.nextIndex(3, 3), 0);
});
it('returns 0 if the sum of the two params is greater than the number of images in the model', () => {
assert.equal(product.nextIndex(3, 4), 0);
});
it('returns one less than the number of images in the model if the sum of the two params is below zero', () => {
assert.equal(product.nextIndex(-3, 2), product.model.images.length - 1);
});
});
describe('onCarouselChange()', () => {
let renderStub;
let nextIndexStub;
beforeEach(async () => {
await product.init(testProductCopy);
renderStub = sinon.stub(product.view, 'render');
nextIndexStub = sinon.stub(product, 'nextIndex').returns(1);
});
afterEach(() => {
renderStub.restore();
nextIndexStub.restore();
});
it('sets selected image based on offset determined by nextIndex()', () => {
assert.equal(product.selectedImage.id, 1);
product.onCarouselChange(3);
assert.calledOnce(nextIndexStub);
assert.calledWith(nextIndexStub, 0, 3);
assert.equal(product.selectedImage.id, 2);
});
it('renders the view', () => {
product.onCarouselChange(1);
assert.calledOnce(renderStub);
});
it('sets cached image to selected image', () => {
product.onCarouselChange(1);
assert.equal(product.cachedImage, product.selectedImage);
});
});
describe('openModal()', () => {
let userEventStub;
let modalInitStub;
let createModalStub;
const modalMock = {};
beforeEach(() => {
modalInitStub = sinon.stub().returns(modalMock);
createModalStub = sinon.stub().returns({
init: modalInitStub,
});
userEventStub = sinon.stub(product, '_userEvent');
product.props.createModal = createModalStub;
});
afterEach(() => {
userEventStub.restore();
});
describe('if modal exists', () => {
beforeEach(() => {
product.modal = {
init: modalInitStub,
};
});
it('re-initializes modal with model', () => {
product.openModal();
assert.calledOnce(modalInitStub);
assert.calledWith(modalInitStub, product.model);
});
});
describe('if modal does not exist', () => {
beforeEach(() => {
product.modal = null;
});
it('creates a new modal with correct config', () => {
product.globalConfig = {
globalConfig: 'config',
modalNode: 'node',
};
product.config = {
config: 'config',
modal: {
modal: 'modal',
},
};
product = Object.defineProperty(product, 'modalProductConfig', {
value: {},
});
const expectedObj = {
globalConfig: product.globalConfig.globalConfig,
node: product.globalConfig.modalNode,
modalNode: product.globalConfig.modalNode,
options: {
config: product.config.config,
product: product.modalProductConfig,
modal: {
modal: product.config.modal.modal,
googleFonts: product.options.googleFonts,
},
},
};
product.openModal();
assert.calledOnce(createModalStub);
assert.calledWith(createModalStub, expectedObj, product.props);
});
it('initializes the newly created modal using the product model', () => {
product.openModal();
assert.calledOnce(modalInitStub);
assert.calledWith(modalInitStub, product.model);
});
});
it('calls userEvent with openModal', () => {
product.modal = {
init: modalInitStub,
};
product.openModal();
assert.calledOnce(userEventStub);
assert.calledWith(userEventStub, 'openModal');
});
it('returns the init value', () => {
assert.equal(product.openModal(), modalMock);
});
});
describe('updateQuantity()', () => {
let funcStub;
let userEventStub;
let renderStub;
beforeEach(() => {
funcStub = sinon.stub().callsFake((oldQty) => oldQty + 1);
userEventStub = sinon.stub(product, '_userEvent');
renderStub = sinon.stub(product.view, 'render');
});
afterEach(() => {