@shopgate/pwa-common-commerce 6.22.0-beta.2 → 6.22.0-beta.4

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (31) hide show
  1. package/CHANGELOG.md +182 -0
  2. package/package.json +3 -3
  3. package/cart/helpers/config.spec.js +0 -1
  4. package/cart/helpers/shipping.spec.js +0 -1
  5. package/cart/helpers/tax.spec.js +0 -1
  6. package/cart/streams/index.spec.js +0 -1
  7. package/cart/subscriptions/index.spec.js +0 -1
  8. package/category/selectors/index.spec.js +0 -1
  9. package/checkout/actions/fetchCheckoutUrl.spec.js +0 -1
  10. package/favorites/actions/addFavorites.spec.js +0 -5
  11. package/favorites/actions/fetchFavorites.spec.js +0 -2
  12. package/favorites/actions/removeFavorites.spec.js +0 -5
  13. package/favorites/actions/toggleFavorites.spec.js +0 -1
  14. package/filter/actions/helpers/buildRequestFilters.spec.js +0 -1
  15. package/filter/subscriptions/index.spec.js +0 -1
  16. package/product/reducers/helpers/formatOptions.spec.js +0 -1
  17. package/product/selectors/page.spec.js +0 -5
  18. package/product/selectors/price.spec.js +0 -23
  19. package/product/selectors/product.spec.js +0 -2
  20. package/product/selectors/relations.spec.js +0 -4
  21. package/product/selectors/variants.spec.js +0 -2
  22. package/product/streams/index.spec.js +0 -8
  23. package/product/subscriptions/index.spec.js +0 -1
  24. package/scanner/actions/handleBarCode.spec.js +0 -1
  25. package/scanner/actions/handleNoResults.spec.js +0 -1
  26. package/scanner/actions/handleQrCode.spec.js +0 -1
  27. package/scanner/actions/handleSearch.spec.js +0 -1
  28. package/scanner/helpers/index.spec.js +0 -1
  29. package/scanner/streams/index.spec.js +0 -1
  30. package/scanner/subscriptions/index.spec.js +0 -7
  31. package/search/selectors/index.spec.js +0 -1
package/CHANGELOG.md ADDED
@@ -0,0 +1,182 @@
1
+
2
+ # Changelog
3
+ ---
4
+ ### [3.0.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.5.0...v3.0.0) - February 07, 2018
5
+ #### Added
6
+ - Extended favorites event streams with favoritesWillRemoveItem$.
7
+ - Process appConfig.productPropertiesFilter in the properties selector. This will filter the properties by whitelisting or blacklisting properties according to the setting.
8
+
9
+ #### Changed
10
+ - renamed `getTemporaryFiltersWithRoudedDisplayAmounts` selector to `getTemporaryFiltersWithRoundedDisplayAmounts`
11
+
12
+ #### Fixed
13
+ - Apply filter didn't work
14
+
15
+ ---
16
+ ### [2.5.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.4.0...v2.5.0) - February 06, 2018
17
+ #### Added
18
+ - Observable `favoritesWillFetch`
19
+ - Observable `favoritesDidFetch`
20
+ - `getProducts` action now includes a `includeFilters` parameter.
21
+
22
+ #### Changed
23
+ - Extended `addFavorites` action with `immediate` variable that bypasses throttling of the action.
24
+
25
+ #### Fixed
26
+ - Fixed `getFavorites` selector object property check.
27
+
28
+ ---
29
+ ### [2.4.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.3.0...v2.4.0) - February 05, 2018
30
+ #### Added
31
+ - Added a `includeFilter` option to `getProducts` action
32
+
33
+ #### Changed
34
+ - The `getSearchResults` action now uses the `getSearchPhrase` history selector from `pwa-common` instead of the navigator selector from `pwa-common-commerce`
35
+
36
+ ---
37
+ ### [2.3.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.2.0...v2.3.0) - January 30, 2018
38
+ #### Added
39
+ - `PRODUCT_ITEM_NAME_BEFORE` portal ID.
40
+
41
+ ---
42
+ ### [2.2.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.1.0...v2.2.0) - January 29, 2018
43
+ #### Added
44
+ - Add/Remove favorites actions, subscriptions and stream.
45
+ #### Changed
46
+ - Favorites reducers react on Add/Remove favorites actions by adding/removing a product to/from redux store on request action.
47
+ ---
48
+
49
+ ### [2.1.0](https://github.com/shopgate/pwa-common-commerce/compare/v2.0.0...v2.1.0) - January 25, 2018
50
+ #### Added
51
+ - Redux actions, reducer and selectors for favourites feature
52
+
53
+ ---
54
+
55
+ ### [2.0.0](https://github.com/shopgate/pwa-common-commerce/compare/v1.2.2...v2.0.0) - January 24, 2018
56
+ #### Changed
57
+ - Updated the `getCheckoutUrl` action to use the refactored "url" action creators from "pwa-common".
58
+ - The input param of the `getVariantsByProductId` selector, to reflect the default reselect signature.
59
+
60
+ #### Fixed
61
+ - `getVariantsByProductId` selector returns now the correct redux state instead of just a function.
62
+
63
+ ---
64
+
65
+ ### [1.2.2](https://github.com/shopgate/pwa-common-commerce/compare/v1.2.1...v1.2.2) - January 17, 2018
66
+ #### Fixed
67
+ - The reset of the currentProduct state when navigating through pages that belong to the product route.
68
+
69
+ #### Added
70
+ - Added constants for filtertypes `range` and `multiselect`
71
+
72
+
73
+ ---
74
+
75
+ ### [1.2.0](https://github.com/shopgate/pwa-common-commerce/compare/v1.1.4...v1.2.0) - January 08, 2018
76
+
77
+ #### Removed
78
+ - `CHECKOUT_PATH` constant
79
+
80
+ ---
81
+
82
+ ### [1.1.4](https://github.com/shopgate/pwa-common-commerce/compare/v1.1.3...v1.1.4) - January 05, 2018
83
+
84
+ #### Added
85
+ - Highlighting symbols around search suggestions are removed from pipeline response
86
+
87
+ ---
88
+
89
+ ### [1.1.3](https://github.com/shopgate/pwa-common-commerce/compare/v1.1.2...v1.1.3) - December 28, 2017
90
+
91
+ #### Changed
92
+ - Updated `@shopgate/pwa-common` to ^1.1.3
93
+
94
+ ---
95
+
96
+ ### [1.1.2](https://github.com/shopgate/pwa-common-commerce/compare/v1.1.1...v1.1.2) - December 22, 2017
97
+
98
+ #### Added
99
+ - Products with options can now be added to the cart
100
+ - Constants for options types (`OPTION_TYPE_SELECT` and `OPTION_TYPE_TEXT`)
101
+ - Selector `getAddToCartMetadata`
102
+ - Selector `getAddToCartOptions `
103
+
104
+ #### Changed
105
+ - Updated `@shopgate/pwa-common` to ^1.1.2
106
+ - Updated `@shopgate/pwa-core` to ^1.1.0
107
+
108
+ ---
109
+
110
+ ### [1.1.1](https://github.com/shopgate/pwa-common-commerce/compare/v1.1.0...v1.1.1) - December 22, 2017
111
+
112
+ #### Added
113
+ - React 16 support
114
+ - Dependency `react-hammerjs` ^0.5.3
115
+
116
+ #### Changed
117
+ - Updated `react` to ^16.2.0
118
+ - Updated `react-dom` to ^16.2.0
119
+
120
+ ---
121
+
122
+ ### [1.1.0](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.6...v1.1.0) - December 22, 2017
123
+
124
+ #### Changed
125
+ - Updated `@shopgate/eslint-vonfig` to ^1.0.3
126
+ - Updated `@shopgate/pwa-common` to ^1.1.1
127
+ - Updated `@shopgate/pwa-unit-test` to ^1.3.0
128
+
129
+ ---
130
+
131
+ ### [1.0.6](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.5...v1.0.6) - December 21, 2017
132
+
133
+ #### Changed
134
+ - Updated `@shopgate/pwa-common` to ^1.0.12
135
+ - Updated `@shopgate/pwa-core` to ^1.0.5
136
+
137
+ ---
138
+
139
+ ### [1.0.5](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.4...v1.0.5) - December 15, 2017
140
+
141
+ #### Changed
142
+ - Updated `@shopgate/pwa-common` to ^1.0.11
143
+ - The getProduct action will now check if product data is available before attempting to process it
144
+
145
+ ---
146
+
147
+ ### [1.0.4](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.3...v1.0.4) - December 11, 2017
148
+
149
+ #### Changed
150
+ - Updated `@shopgate/pwa-common` to ^1.0.5
151
+ - Updated `@shopgate/pwa-core` to ^1.0.4
152
+
153
+ ---
154
+
155
+ ### [1.0.3](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.2...v1.0.3) - December 11, 2017
156
+
157
+ #### Added
158
+ - Callback for checkoutSuccess event that will reset the browser history and fetch a new cart
159
+
160
+ #### Changed
161
+ - Updated `@shopgate/pwa-common` to ^1.0.4
162
+ - Updated `@shopgate/pwa-core` to ^1.0.3
163
+ - The getFilters action will now abort when pipeline parameters are invalid
164
+
165
+ ---
166
+
167
+ ### [1.0.2](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.1...v1.0.2) - December 7, 2017
168
+
169
+ #### Changed
170
+ - Updated `@shopgate/pwa-common` to ^1.0.3
171
+
172
+ ---
173
+
174
+ ### [1.0.1](https://github.com/shopgate/pwa-common-commerce/compare/v1.0.0...v1.0.1) - December 7, 2017
175
+
176
+ #### Changed
177
+ - Updated `@shopgate/pwa-common` to ^1.0.2
178
+ - Updated `@shopgate/pwa-core` to ^1.0.0
179
+ - Product rating and review selectors now reference the base product
180
+
181
+ #### Fixed
182
+ - Missing sort parameter added to getProducts pipeline when performing a search
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@shopgate/pwa-common-commerce",
3
- "version": "6.22.0-beta.2",
3
+ "version": "6.22.0-beta.4",
4
4
  "description": "Commerce library for the Shopgate Connect PWA.",
5
5
  "license": "Apache-2.0",
6
6
  "author": "Shopgate <support@shopgate.com>",
@@ -18,8 +18,8 @@
18
18
  "reselect": "^3.0.1"
19
19
  },
20
20
  "devDependencies": {
21
- "@shopgate/pwa-common": "6.22.0-beta.2",
22
- "@shopgate/pwa-core": "6.22.0-beta.2",
21
+ "@shopgate/pwa-common": "6.22.0-beta.4",
22
+ "@shopgate/pwa-core": "6.22.0-beta.4",
23
23
  "lodash": "^4.17.4",
24
24
  "react": "~16.12.0",
25
25
  "react-dom": "~16.12.0"
@@ -1 +0,0 @@
1
- import{getCartConfig}from"./config";jest.mock('@shopgate/pwa-common/helpers/config',function(){return{cartShippingHideAnonymousLegacy:true,cartShippingTextAnonymousLegacy:'cartShippingTextAnonymousLegacy',cartTaxText:'cartTaxText',cart:{hideTotal:false,hideShipping:false,hideTax:false,shipping:{hideFreeShipping:false,hideAnonymous:null,textForAnonymousUsers:null,textForFreeShipping:null,textForNoShipping:null,hint:null},tax:{text:null,hint:null}}};});describe('Cart helper config',function(){it('should create config',function(){expect(getCartConfig()).toEqual({hideTotal:false,hideShipping:false,hideTax:false,shipping:{hideFreeShipping:false,hideAnonymous:true,textForAnonymousUsers:'cartShippingTextAnonymousLegacy',textForFreeShipping:null,textForNoShipping:null,hint:null},tax:{text:'cartTaxText',hint:null}});});});
@@ -1 +0,0 @@
1
- function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}/* eslint-disable extra-rules/no-single-line-objects */import{getShippingLine}from"./shipping";describe('Cart helper shipping',function(){var cartConfig={hideShipping:false,shipping:{hideFreeShipping:false,hideAnonymous:null,textForAnonymousUsers:null,textForFreeShipping:null,textForNoShipping:null,hint:'(incl)'}};describe('Should return null',function(){it('should return null on empty shipping cost',function(){expect(getShippingLine(cartConfig)).toBeNull();});it('should return null on hideShipping',function(){expect(getShippingLine({hideShipping:true},false,{})).toBeNull();});it('should return null on hideAnonymous',function(){expect(getShippingLine(_extends({},cartConfig,{shipping:_extends({},cartConfig.shipping,{hideAnonymous:true})}),false,{})).toBeNull();});it('should return null for no shipping',function(){expect(getShippingLine(cartConfig,false,{amount:null})).toBeNull();});it('should return null for hideFreeShipping',function(){expect(getShippingLine(_extends({},cartConfig,{shipping:_extends({},cartConfig.shipping,{hideFreeShipping:true})}),false,{amount:0})).toBeNull();});});describe('Should return shipping',function(){it('should return textForAnonymousUsers',function(){expect(getShippingLine(_extends({},cartConfig,{shipping:_extends({},cartConfig.shipping,{textForAnonymousUsers:'textForAnonymousUsers'})}),false,{})).toEqual({label:'textForAnonymousUsers'});});it('should return textForNoShipping',function(){expect(getShippingLine(_extends({},cartConfig,{shipping:_extends({},cartConfig.shipping,{textForNoShipping:'textForNoShipping'})}),false,{amount:null})).toEqual({label:'textForNoShipping'});});it('should return textForFreeShipping',function(){expect(getShippingLine(_extends({},cartConfig,{shipping:_extends({},cartConfig.shipping,{textForFreeShipping:'textForFreeShipping'})}),false,{amount:0})).toEqual({label:'titles.shipping',amount:'textForFreeShipping',hint:'(incl)'});});it('should return free shipping',function(){expect(getShippingLine(cartConfig,false,{amount:0})).toEqual({label:'titles.shipping',amount:'shipping.free_short',hint:'(incl)'});});it('should return shipping',function(){expect(getShippingLine(cartConfig,false,{label:'DHL',amount:5})).toEqual({label:'DHL',amount:5,hint:'(incl)'});});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}/* eslint-disable extra-rules/no-single-line-objects */import{getTaxLine}from"./tax";describe('Cart helper tax',function(){var cartConfig={hideTax:false,tax:{text:null,hint:'(incl)'}};describe('Should return null',function(){it('should return null on empty tax cost',function(){expect(getTaxLine(cartConfig)).toBeNull();});it('should return null on empty tax amount',function(){expect(getTaxLine(cartConfig,{amount:0})).toBeNull();});it('should return null on hideTax',function(){expect(getTaxLine({hideTax:true},{})).toBeNull();});});describe('Should return tax',function(){it('should return custom text',function(){expect(getTaxLine(_extends({},cartConfig,{tax:_extends({},cartConfig.tax,{text:'taxText'})}),{amount:5})).toEqual({amount:'taxText',hint:'(incl)'});});it('should return tax',function(){expect(getTaxLine(cartConfig,{amount:5,label:'incl 19%'})).toEqual({label:'incl 19%',amount:5,hint:'(incl)'});});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import{createMockStore}from'@shopgate/pwa-common/store';import{ACTION_PUSH,ACTION_POP,ACTION_REPLACE}from'@virtuous/conductor';import{CART_PATH}from'@shopgate/pwa-common-commerce/cart/constants';import{routeWillEnter,navigate}from'@shopgate/pwa-common/action-creators/router';import receiveCart from'@shopgate/pwa-common-commerce/cart/action-creators/receiveCart';import{getCurrentPathname}from'@shopgate/pwa-common/selectors/router';import{routeWithCouponWillEnter$,cartUpdatedWhileVisible$,routeAddProductNavigate$}from"./index";jest.mock('@shopgate/pwa-common/selectors/router',function(){return{getCurrentPathname:jest.fn()};});describe('Cart streams',function(){var dispatch;beforeEach(function(){jest.clearAllMocks();var _createMockStore=createMockStore();dispatch=_createMockStore.dispatch;});describe('routeWithCouponWillEnter$',function(){var subscriber;beforeEach(function(){subscriber=jest.fn();routeWithCouponWillEnter$.subscribe(subscriber);});it('should emit when a route will enter that has a coupon in its query',function(){dispatch(routeWillEnter({query:{coupon:'10PERCENTOFF'}},ACTION_PUSH));expect(subscriber).toHaveBeenCalledTimes(1);});it('should emit when a route will enter that has a coupon in its query',function(){dispatch(routeWillEnter({query:{coupon:'10PERCENTOFF'}},ACTION_REPLACE));expect(subscriber).toHaveBeenCalledTimes(1);});it('should not emit when a route will enter without a coupon in its query',function(){dispatch(routeWillEnter({query:{}},ACTION_PUSH));expect(subscriber).not.toHaveBeenCalled();});it('should not emit when a route will enter by a ACTION_POP history action',function(){dispatch(routeWillEnter({query:{coupon:'10PERCENTOFF'}},ACTION_POP));expect(subscriber).not.toHaveBeenCalled();});});describe('cartUpdatedWhileVisible$',function(){var subscriber;beforeEach(function(){subscriber=jest.fn();cartUpdatedWhileVisible$.subscribe(subscriber);});it('should not emit when updated while different page is visible',function(){getCurrentPathname.mockReturnValue('/something');dispatch(receiveCart({}));expect(subscriber).not.toHaveBeenCalled();});it('should emit when updated while cart page is visible',function(){getCurrentPathname.mockReturnValue(CART_PATH);dispatch(receiveCart({}));expect(subscriber).toHaveBeenCalled();});});describe('routeAddProductNavigate$',function(){var subscriber;beforeEach(function(){subscriber=jest.fn();routeAddProductNavigate$.subscribe(subscriber);});it('should not emit when navigate does not map pattern',function(){dispatch(navigate({pathname:'/some_path'}));expect(subscriber).not.toHaveBeenCalled();});it('should emit and map event correctly',function(){dispatch(navigate({pathname:'/cart_add_product/345%2F34%23/TEST-CODE'}));expect(subscriber).toHaveBeenCalledTimes(1);expect(subscriber).toHaveBeenCalledWith(expect.objectContaining({action:expect.objectContaining({productId:'345/34#',couponCode:'TEST-CODE'})}));});it('should emit and map event without coupon correctly',function(){dispatch(navigate({pathname:'/cart_add_product/345%2F34%23'}));expect(subscriber).toHaveBeenCalledTimes(1);expect(subscriber).toHaveBeenCalledWith(expect.objectContaining({action:expect.objectContaining({productId:'345/34#',couponCode:undefined})}));});});});
@@ -1 +0,0 @@
1
- function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import{redirects}from'@shopgate/pwa-common/collections';import{appWillStart$}from'@shopgate/pwa-common/streams/app';import{hasProductVariety}from'@shopgate/pwa-common-commerce/product';import{historyReplace}from'@shopgate/pwa-common/actions/router';import addCouponsToCart from"../actions/addCouponsToCart";import addProductsToCart from"../actions/addProductsToCart";import{CART_PATH,DEEPLINK_CART_ADD_COUPON_PATTERN,DEEPLINK_CART_ADD_PRODUCT_PATTERN}from"../constants";import{routeAddProductNavigate$,routeWithCouponWillEnter$}from"../streams";import subscription from"./index";jest.mock('@shopgate/pwa-common-commerce/product',function(){return{getProductRoute:jest.fn(function(productId){return productId;}),hasProductVariety:jest.fn()};});jest.mock('@shopgate/pwa-common/actions/router',function(){return{historyReplace:jest.fn()};});jest.mock("../actions/addCouponsToCart",function(){return jest.fn();});jest.mock("../actions/addProductsToCart",function(){return jest.fn();});describe('Cart subscriptions',function(){var subscribe=jest.fn();var dispatch=jest.fn().mockImplementation(function(action){return action;});var getState=jest.fn();beforeEach(function(){jest.clearAllMocks();subscription(subscribe);});describe('appWillStart$',function(){var stream;var callback;var redirectsSetSpy=jest.spyOn(redirects,'set');beforeEach(function(){var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,1);var _subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);stream=_subscribe$mock$calls2[0];callback=_subscribe$mock$calls2[1];});it('should subscribe as expected',function(){expect(stream).toEqual(appWillStart$);expect(callback).toBeInstanceOf(Function);});it('should setup a redirect handler for cart_add_coupon deeplinks',function(){callback();expect(redirectsSetSpy).toHaveBeenCalledTimes(2);expect(redirectsSetSpy.mock.calls).toEqual([[DEEPLINK_CART_ADD_COUPON_PATTERN,expect.any(Function)],[DEEPLINK_CART_ADD_PRODUCT_PATTERN,expect.any(Function)]]);});it('should dispatch the addCouponsToCart action when a cart_add_coupon deeplink was opened',function(){callback();var coupon='10PERCENTOFF';var action={params:{pathname:"/cart_add_coupon/".concat(coupon,"?get=parameter")}};var handlerResult=redirects.get(DEEPLINK_CART_ADD_COUPON_PATTERN)({dispatch:dispatch,action:action});expect(handlerResult).toBeNull();expect(dispatch).toHaveBeenCalledTimes(1);expect(addCouponsToCart).toHaveBeenCalledTimes(1);expect(addCouponsToCart).toHaveBeenCalledWith([coupon]);});});describe('routeWithCouponWillEnter$',function(){var stream;var callback;beforeEach(function(){var _subscribe$mock$calls3=_slicedToArray(subscribe.mock.calls,8);var _subscribe$mock$calls4=_slicedToArray(_subscribe$mock$calls3[7],2);stream=_subscribe$mock$calls4[0];callback=_subscribe$mock$calls4[1];});it('should subscribe as expected',function(){expect(stream).toEqual(routeWithCouponWillEnter$);expect(callback).toBeInstanceOf(Function);});it('should dispatch the addCouponsToCart action',function(){var coupon='10PERCENTOFF';var action={route:{query:{coupon:coupon}}};callback({dispatch:dispatch,action:action});expect(dispatch).toHaveBeenCalledTimes(1);expect(addCouponsToCart).toHaveBeenCalledTimes(1);expect(addCouponsToCart).toHaveBeenCalledWith([coupon]);});});describe('routeAddProductNavigate$',function(){var stream;var callback;var action={productId:'prod1'};beforeEach(function(){var _subscribe$mock$calls5=_slicedToArray(subscribe.mock.calls,9);var _subscribe$mock$calls6=_slicedToArray(_subscribe$mock$calls5[8],2);stream=_subscribe$mock$calls6[0];callback=_subscribe$mock$calls6[1];});it('should subscribe as expected',function(){expect(stream).toEqual(routeAddProductNavigate$);expect(callback).toBeInstanceOf(Function);});it('should navigate to PDP when product has variety',function(){hasProductVariety.mockReturnValueOnce(true);callback({dispatch:dispatch,action:action,getState:getState});expect(dispatch).toHaveBeenCalledTimes(1);expect(historyReplace).toHaveBeenCalledTimes(1);expect(historyReplace).toHaveBeenCalledWith({pathname:action.productId});});it('should navigate to cart when product has no variety',function(){hasProductVariety.mockReturnValueOnce(false);callback({dispatch:dispatch,action:action,getState:getState});expect(dispatch).toHaveBeenCalledTimes(2);expect(addProductsToCart).toHaveBeenCalledWith([{productId:action.productId,quantity:1}]);expect(historyReplace).toHaveBeenCalledWith({pathname:CART_PATH});});});});
@@ -1 +0,0 @@
1
- function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import{getCurrentRoute,getCurrentParams}from'@shopgate/pwa-common/selectors/router';import{bin2hex}from'@shopgate/pwa-common/helpers/data';import{getCategoryId,getCategory,getRootCategories,getCategoryChildren,getCategoryChildCount,hasCategoryChildren,getCategoryProductCount,hasCategoryProducts,getCategoryName}from"./index";jest.mock('@shopgate/pwa-common/selectors/router',function(){return{getCurrentRoute:jest.fn(),getCurrentParams:jest.fn()};});var mockState={category:{categoriesById:{r1:{id:'r1',name:'Root Category One',childrenCount:10,productCount:10,isFetching:false,expires:123456},r2:{id:'r2',name:'Root Category Two',childrenCount:11,productCount:11,isFetching:false,expires:123456},c1:{id:'c1',name:'Category One',childrenCount:12,productCount:12,isFetching:false,expires:123456},c2:{id:'c2',name:'Category Two',childrenCount:13,productCount:13,isFetching:false,expires:123456},c3:{id:'c3',name:'Category Three',childrenCount:0,productCount:0,isFetching:false,expires:123456}},childrenByCategoryId:{r1:{children:['c1','c2'],isFetching:false,expires:123456},c1:{children:['c3'],isFetching:false,expires:123456}},rootCategories:{categories:['r1','r2'],expires:123456,isFetching:false}}};var _mockState$category=mockState.category,categoriesById=_mockState$category.categoriesById,childrenByCategoryId=_mockState$category.childrenByCategoryId;var propCategoryId='c2';var propCategory=categoriesById[propCategoryId];var propCategoryName=propCategory.name;var routeCategoryId='c1';var routeCategory=categoriesById[routeCategoryId];var routeCategoryName=routeCategory.name;describe('Category page selectors',function(){beforeAll(function(){getCurrentParams.mockReturnValue({categoryId:bin2hex(routeCategoryId)});getCurrentRoute.mockReturnValue({state:{title:routeCategoryName}});});beforeEach(function(){jest.clearAllMocks();});describe('getCategoryId()',function(){it('should return the categoryId from the props when present',function(){expect(getCategoryId({},{categoryId:routeCategoryId})).toBe(routeCategoryId);});it('should return the categoryId from the current route params',function(){expect(getCategoryId({})).toBe(routeCategoryId);});it('should return NULL when no categoryId is present within the props or the current route',function(){getCurrentParams.mockReturnValueOnce(undefined);expect(getCategoryId({})).toBeNull();getCurrentParams.mockReturnValueOnce({});expect(getCategoryId({})).toBeNull();});});describe('getCategory()',function(){it('should return the category from the props',function(){expect(getCategory(mockState,{categoryId:propCategoryId})).toBe(propCategory);});it('should return the category from the route',function(){expect(getCategory(mockState)).toBe(routeCategory);});it('should return NULL when the category from the props does not exist',function(){expect(getCategory(mockState,{categoryId:'invalid'})).toBeNull();});it('should return NULL when category data is not available yet',function(){expect(getCategory({})).toBeNull();});});describe('getRootCategories()',function(){it('should get the root categories',function(){expect(getRootCategories(mockState)).toEqual([categoriesById.r1,categoriesById.r2]);});it('should return NULL when the root categories state is empty',function(){expect(getRootCategories({category:_extends({},mockState.category,{rootCategories:{}})})).toBeNull();});it('should return NULL when no root categories are available yet',function(){expect(getRootCategories({category:_extends({},mockState.category,{rootCategories:_extends({},mockState.category.rootCategories,{categories:undefined})})})).toBeNull();});it('should return an empty array when no matching category data can be determined',function(){expect(getRootCategories({category:_extends({},mockState.category,{categoriesById:{}})})).toEqual([]);});});describe('getCategoryChildCount()',function(){it('should return the correct count for a categoryId within the props',function(){expect(getCategoryChildCount(mockState,{categoryId:propCategoryId})).toBe(propCategory.childrenCount);});it('should return the correct count for the categoryId within the route',function(){expect(getCategoryChildCount(mockState)).toBe(routeCategory.childrenCount);});it('should return NULL when no category can be determined',function(){expect(getCategoryChildCount(mockState,{categoryId:'invalid'})).toBeNull();});});describe('hasCategoryChildren()',function(){it('should return TRUE for a category from the props with children',function(){expect(hasCategoryChildren(mockState,{categoryId:propCategoryId})).toBe(true);});it('should return TRUE for a category from the route with children',function(){expect(hasCategoryChildren(mockState)).toBe(true);});it('should return FALSE for a category without children',function(){expect(hasCategoryChildren(mockState,{categoryId:'c4'})).toBe(false);});it('should return FALSE for an invalid category',function(){expect(hasCategoryChildren(mockState,{categoryId:'invalid'})).toBe(false);});});describe('getCategoryChildren()',function(){it('should return child categories for a category from the props',function(){var categoryId='r1';var expected=childrenByCategoryId[categoryId].children.map(function(childId){return categoriesById[childId];});expect(getCategoryChildren(mockState,{categoryId:categoryId})).toEqual(expected);});it('should return child categories for a category from the route',function(){var categoryId=routeCategoryId;var expected=childrenByCategoryId[categoryId].children.map(function(childId){return categoriesById[childId];});expect(getCategoryChildren(mockState)).toEqual(expected);});it('should return NULL when no child categories entry can be determined',function(){expect(getCategoryChildren(mockState,{categoryId:'invalid'})).toBeNull();});it('should return NULL when no child categories entry can be determined',function(){expect(getCategoryChildren({category:_extends({},mockState.category,{childrenByCategoryId:_extends({},mockState.category.childrenByCategoryId,_defineProperty({},routeCategoryId,_extends({},mockState.category.childrenByCategoryId[routeCategoryId],{children:undefined})))})},{category:routeCategoryId})).toBeNull();});});describe('getCategoryProductCount()',function(){it('should return the correct count for a categoryId within the props',function(){expect(getCategoryProductCount(mockState,{categoryId:propCategoryId})).toBe(propCategory.productCount);});it('should return the correct count for the categoryId within the route',function(){expect(getCategoryProductCount(mockState)).toBe(routeCategory.productCount);});it('should return NULL when no category can be determined',function(){expect(getCategoryProductCount(mockState,{categoryId:'invalid'})).toBeNull();});it('should return 0 when the category has no products',function(){expect(getCategoryProductCount(mockState,{categoryId:'c3'})).toBe(0);});});describe('hasCategoryProducts()',function(){it('should return TRUE for a category from the props with products',function(){expect(hasCategoryProducts(mockState,{categoryId:propCategoryId})).toBe(true);});it('should return TRUE for a category from the route with products',function(){expect(hasCategoryProducts(mockState)).toBe(true);});it('should return FALSE for a category without products',function(){expect(hasCategoryProducts(mockState,{categoryId:'c4'})).toBe(false);});it('should return FALSE for an invalid category',function(){expect(hasCategoryProducts(mockState,{categoryId:'invalid'})).toBe(false);});});describe('getCategoryName()',function(){it('should return the title from the route state when no categoryId is passed witin the props',function(){expect(getCategoryName(mockState)).toBe(routeCategoryName);});it('should return the name of a category from the props',function(){expect(getCategoryName(mockState,{categoryId:propCategoryId})).toBe(propCategoryName);});it('should return NULL when no category name can be determined',function(){getCurrentRoute.mockReturnValueOnce({state:{}});expect(getCategoryName(mockState,{categoryId:'invalid'})).toBeNull();});});});
@@ -1 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{mockedPipelineRequestFactory}from'@shopgate/pwa-core/classes/PipelineRequest/mock';import{FETCH_CHECKOUT_URL_TIMEOUT}from"../constants";import fetchCheckoutUrl from"./fetchCheckoutUrl";var mockedResolver;jest.mock('@shopgate/pwa-core/classes/PipelineRequest',function(){return mockedPipelineRequestFactory(function(mockInstance,resolve,reject){mockedResolver(mockInstance,resolve,reject);});});describe('fetchCheckoutUrl',function(){it('should call the pipeline and resolve',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var dispatch,url;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:dispatch=jest.fn();mockedResolver=function mockedResolver(mockInstance,resolve){expect(mockInstance.timeout).toBe(FETCH_CHECKOUT_URL_TIMEOUT);expect(mockInstance.retries).toBe(0);resolve({url:'https://example.com',expires:0});};_context.next=4;return fetchCheckoutUrl()(dispatch);case 4:url=_context.sent;expect(url).toBe('https://example.com');expect(dispatch).toHaveBeenCalledTimes(2);expect(dispatch.mock.calls[0][0].urlType).toBe('checkout');expect(dispatch.mock.calls[1][0].url).toBe('https://example.com');expect(dispatch.mock.calls[1][0].expires).toBe(0);case 10:case"end":return _context.stop();}}},_callee);})));it('should call the pipeline and reject',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var dispatch,error;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:expect.assertions(1);dispatch=jest.fn();error=new Error('Test');mockedResolver=function mockedResolver(mockInstance,resolve,reject){reject(error);};_context2.prev=4;_context2.next=7;return fetchCheckoutUrl()(dispatch);case 7:_context2.next=12;break;case 9:_context2.prev=9;_context2.t0=_context2["catch"](4);expect(_context2.t0).toBe(undefined);case 12:case"end":return _context2.stop();}}},_callee2,null,[[4,9]]);})));});
@@ -1,5 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import{mockedPipelineRequestFactory}from'@shopgate/pwa-core/classes/PipelineRequest/mock';import{SHOPGATE_USER_ADD_FAVORITES}from"../constants/Pipelines";import addFavorites from"./addFavorites";import{successAddFavorites,errorAddFavorites}from"../action-creators";// Forces the pipeline request to be mocked so each test can decide how it resolves
2
- var mockSuccessResponse;var mockErrorResponse;jest.mock('@shopgate/pwa-core/classes/PipelineRequest',function(){return mockedPipelineRequestFactory(function(mockInstance,resolve,reject){if(mockErrorResponse===undefined){resolve(_extends({},mockSuccessResponse,{mockInstance:mockInstance}));}else{reject(mockErrorResponse);}});});// Mock the config object using class getters
3
- jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get favoritesMode(){return{hasMultipleFavoritesLists:true};}};});var mockState={favorites:{lists:{expires:0,lists:[{id:'DEFAULT',name:'Wish List'}]}}};var mockedGetState=jest.fn(function(){return mockState;});describe('Favorites - actions',function(){describe(SHOPGATE_USER_ADD_FAVORITES,function(){beforeEach(function(){// Pipeline should succeed by default
4
- mockSuccessResponse={};mockErrorResponse=undefined;});it('should call the correct pipeline',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return addFavorites('test-123')(jest.fn(),mockedGetState);case 2:result=_context.sent;expect(result.mockInstance.name).toBe(SHOPGATE_USER_ADD_FAVORITES);case 4:case"end":return _context.stop();}}},_callee);})));it('should dispatch the correct action on pipeline success',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var mockedDispatch,productId;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:mockedDispatch=jest.fn();productId='test-123';_context2.next=4;return addFavorites(productId)(mockedDispatch,mockedGetState);case 4:expect(mockedDispatch).toHaveBeenCalledWith(successAddFavorites(productId,'DEFAULT'));case 5:case"end":return _context2.stop();}}},_callee2);})));it('should dispatch the correct action on pipeline failure',function(done){// Pipeline should fail this time
5
- mockErrorResponse={code:'EUNKNOWN',message:'Mocked pipeline failed'};var mockedDispatch=jest.fn();var productId='test-123';addFavorites(productId)(mockedDispatch,mockedGetState).then(function(){done('resolved!');})["catch"](function(){expect(mockedDispatch).toHaveBeenCalledWith(errorAddFavorites(productId,mockErrorResponse,'DEFAULT'));done();});});});});
@@ -1,2 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{mockedPipelineRequestFactory}from'@shopgate/pwa-core/classes/PipelineRequest/mock';import fetchFavorites from"./fetchFavorites";import{mockedList,mockedGetState}from"../mock";import{RECEIVE_FAVORITES,REQUEST_FAVORITES,ERROR_FETCH_FAVORITES}from"../constants";import{SHOPGATE_USER_GET_FAVORITES}from"../constants/Pipelines";var mockedResolver;jest.mock('@shopgate/pwa-core/classes/PipelineRequest',function(){return mockedPipelineRequestFactory(function(mockInstance,resolve,reject){mockedResolver(mockInstance,resolve,reject);});});// Prevent console output on pipeline error test scenario
2
- jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:jest.fn()}};});describe.skip('fetchFavorites()',function(){it('should call appropriate actions on *resolved* pipeline request',/*#__PURE__*/function(){var _ref=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(done){var mockedDispatch,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:mockedResolver=function mockedResolver(mockInstance,resolve){resolve(_extends({},mockedList,{mockInstance:mockInstance}));};mockedDispatch=jest.fn();_context.prev=2;_context.next=5;return fetchFavorites()(mockedDispatch,mockedGetState('then'));case 5:result=_context.sent;expect(result.mockInstance.name).toBe(SHOPGATE_USER_GET_FAVORITES);expect(mockedDispatch).toHaveBeenCalledTimes(2);expect(mockedDispatch.mock.calls[0][0].type).toBe(REQUEST_FAVORITES);expect(mockedDispatch.mock.calls[1][0].type).toBe(RECEIVE_FAVORITES);done();_context.next=16;break;case 13:_context.prev=13;_context.t0=_context["catch"](2);done(_context.t0);case 16:case"end":return _context.stop();}}},_callee,null,[[2,13]]);}));return function(_x){return _ref.apply(this,arguments);};}());it('should call appropriate action on *rejected* pipeline request',/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(done){var mockedDispatch,result;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:mockedResolver=function mockedResolver(mockInstance,resolve,reject){reject(_extends({},mockedList,{mockInstance:mockInstance}));};mockedDispatch=jest.fn();_context2.prev=2;_context2.next=5;return fetchFavorites()(mockedDispatch,mockedGetState('then'));case 5:result=_context2.sent;expect(result.mockInstance.name).toBe(SHOPGATE_USER_GET_FAVORITES);expect(mockedDispatch).toHaveBeenCalledTimes(2);expect(mockedDispatch.mock.calls[0][0].type).toBe(REQUEST_FAVORITES);expect(mockedDispatch.mock.calls[1][0].type).toBe(ERROR_FETCH_FAVORITES);done();_context2.next=16;break;case 13:_context2.prev=13;_context2.t0=_context2["catch"](2);done(_context2.t0);case 16:case"end":return _context2.stop();}}},_callee2,null,[[2,13]]);}));return function(_x2){return _ref2.apply(this,arguments);};}());it('should not call pipeline when data is cached and valid',function(done){var mockedDispatch=jest.fn();var promise=fetchFavorites()(mockedDispatch,mockedGetState('then',{validCache:true}));promise.then(function(result){expect(result).toBe(null);expect(mockedDispatch.mock.calls.length).toBe(0);done();});});});
@@ -1,5 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import{mockedPipelineRequestFactory}from'@shopgate/pwa-core/classes/PipelineRequest/mock';import{SHOPGATE_USER_DELETE_FAVORITES}from"../constants/Pipelines";import removeFavorites from"./removeFavorites";import{successRemoveFavorites,errorRemoveFavorites}from"../action-creators";// Forces the pipeline request to be mocked so each test can decide how it resolves
2
- var mockSuccessResponse;var mockErrorResponse;jest.mock('@shopgate/pwa-core/classes/PipelineRequest',function(){return mockedPipelineRequestFactory(function(mockInstance,resolve,reject){if(mockErrorResponse===undefined){resolve(_extends({},mockSuccessResponse,{mockInstance:mockInstance}));}else{reject(mockErrorResponse);}});});// Mock the config object using class getters
3
- jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get favoritesMode(){return{hasMultipleFavoritesLists:true};}};});var mockState={favorites:{lists:{expires:0,lists:[{id:'DEFAULT',name:'Wish List'}]}}};var mockedGetState=jest.fn(function(){return mockState;});describe('Favorites - actions',function(){describe(SHOPGATE_USER_DELETE_FAVORITES,function(){beforeEach(function(){// Pipeline should succeed by default
4
- mockSuccessResponse={};mockErrorResponse=undefined;});it('should call the correct pipeline',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return removeFavorites('test-123')(jest.fn(),mockedGetState);case 2:result=_context.sent;expect(result.mockInstance.name).toBe(SHOPGATE_USER_DELETE_FAVORITES);case 4:case"end":return _context.stop();}}},_callee);})));it('should dispatch the correct action on pipeline success',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var mockedDispatch,productId;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:mockedDispatch=jest.fn();productId='test-123';_context2.next=4;return removeFavorites(productId)(mockedDispatch,mockedGetState);case 4:expect(mockedDispatch).toHaveBeenCalledWith(successRemoveFavorites(productId,'DEFAULT'));case 5:case"end":return _context2.stop();}}},_callee2);})));it('should dispatch the correct action on pipeline failure',function(done){// Pipeline should fail this time
5
- mockErrorResponse={code:'EUNKNOWN',message:'Mocked pipeline failed'};var mockedDispatch=jest.fn();var productId='test-123';removeFavorites(productId)(mockedDispatch,mockedGetState).then(function(){done('resolved!');})["catch"](function(){expect(mockedDispatch).toHaveBeenCalledWith(errorRemoveFavorites(productId,'DEFAULT',mockErrorResponse));done();});});});});
@@ -1 +0,0 @@
1
- import configureMockStore from'redux-mock-store';import thunk from'redux-thunk';import{addFavorite,removeFavorites,requestSync}from"./toggleFavorites";import{mockedGetState,mockedDefaultListId as listId}from"../mock";import{ADD_PRODUCT_TO_FAVORITES,REMOVE_PRODUCT_FROM_FAVORITES,REQUEST_FLUSH_FAVORITES_BUFFER}from"../constants";var middlewares=[thunk];var mockStore=configureMockStore(middlewares);describe('Favorites - actions',function(){describe('Add Favorites',function(){it('should add',function(done){var productId='product';var expectedActions=[{type:ADD_PRODUCT_TO_FAVORITES,productId:productId,listId:listId}];var store=mockStore(mockedGetState('then',{withProducts:true}));store.dispatch(addFavorite(productId));setTimeout(function(){expect(store.getActions()).toEqual(expectedActions);done();},0);});});describe('remove favorites',function(){it('should remove without relatives',function(done){var productId='product';var expectedActions=[{type:REMOVE_PRODUCT_FROM_FAVORITES,productId:productId,withRelatives:false,listId:listId}];var store=mockStore(mockedGetState('then',{withProducts:true}));store.dispatch(removeFavorites(productId));setTimeout(function(){expect(store.getActions()).toEqual(expectedActions);done();},0);});it('should remove with relatives',function(done){var productId='SG118';var expectedActions=[{type:REMOVE_PRODUCT_FROM_FAVORITES,productId:productId,withRelatives:true,listId:listId}];var store=mockStore(mockedGetState('then',{withProducts:true}));store.dispatch(removeFavorites(productId,true));setTimeout(function(){expect(store.getActions()).toEqual(expectedActions);done();},0);});it('should trigger an instant sync (flush add/remove action buffer)',function(done){var store=mockStore({});store.dispatch(requestSync());setTimeout(function(){expect(store.getActions()).toEqual([{type:REQUEST_FLUSH_FAVORITES_BUFFER}]);done();},0);});});});
@@ -1 +0,0 @@
1
- import{FILTER_TYPE_SINGLE_SELECT,FILTER_TYPE_MULTISELECT,FILTER_TYPE_RANGE}from'@shopgate/pwa-common-commerce/filter/constants';import buildRequestFilters from"./buildRequestFilters";var input={display_amount:{id:'display_amount',label:'Price',type:FILTER_TYPE_RANGE,value:[1337,4711]},manufacturer:{id:'manufacturer',label:'Manufacturer Label',source:'manufacturer',type:FILTER_TYPE_MULTISELECT,value:[{id:'With+special+characters',label:'With special characters'},{id:'Some Id',label:'Label of some id'}]},'Single Select Filter':{id:'Single Select Filter',label:'Single Select Filter Label',source:'properties',type:FILTER_TYPE_SINGLE_SELECT,value:[{id:'Value One ID',label:'Value One Label'}]}};var output={display_amount:{label:'Price',minimum:1337,maximum:4711,type:FILTER_TYPE_RANGE},manufacturer:{label:'Manufacturer Label',source:'manufacturer',type:FILTER_TYPE_MULTISELECT,values:['With+special+characters','Some Id']},'Single Select Filter':{label:'Single Select Filter Label',source:'properties',type:FILTER_TYPE_SINGLE_SELECT,value:'Value One ID'}};describe('buildRequestFilters()',function(){it('should build the filters as expected',function(){expect(buildRequestFilters(input)).toEqual(output);});it('should return undefined when no valid filters are passed',function(){expect(buildRequestFilters(null)).toBeUndefined();});it('should return an empty object if empty filters are passed',function(){expect(buildRequestFilters({})).toEqual({});});});
@@ -1 +0,0 @@
1
- function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}import fetchFilters from"../actions/fetchFilters";import{filterDidEnter$}from"../streams";import subscriptions from"./index";jest.mock("../actions/fetchFilters",function(){return jest.fn().mockReturnValue('fetchFilters');});describe('Filter subscriptions',function(){var subscribe=jest.fn();var dispatch=jest.fn();beforeEach(function(){jest.clearAllMocks();subscriptions(subscribe);});it('should subscribe as expected',function(){expect(subscribe).toHaveBeenCalledTimes(1);});describe('filterDidEnter$',function(){var stream;var callback;beforeEach(function(){var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,1);var _subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);stream=_subscribe$mock$calls2[0];callback=_subscribe$mock$calls2[1];});it('should setup as expected',function(){expect(stream).toEqual(filterDidEnter$);expect(callback).toBeInstanceOf(Function);});it('should call get filters when stream emits',function(){callback({dispatch:dispatch});expect(fetchFilters).toHaveBeenCalledTimes(1);expect(fetchFilters).toHaveBeenCalledWith();expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(fetchFilters());});});});
@@ -1 +0,0 @@
1
- import{OPTION_TYPE_SELECT,OPTION_TYPE_TEXT}from"../../constants";import formatOptions from"./formatOptions";describe('libraries/commerce/product/reducers/helpers/formatOptions.js',function(){it('should format options with unitPriceModifier',function(){var expected=[{id:10,type:OPTION_TYPE_SELECT,label:'Select option',values:[{id:100,unitPriceModifier:1}]},{id:11,type:OPTION_TYPE_TEXT,label:'Text option',unitPriceModifier:2}];var options=[{id:10,type:OPTION_TYPE_SELECT,label:'Select option',values:[{id:100,unitPriceModifier:1}]},{id:11,type:OPTION_TYPE_TEXT,label:'Text option',unitPriceModifier:2}];expect(formatOptions(options)).toEqual(expected);});it('should format options without unitPriceModifier',function(){var expected=[{id:10,type:OPTION_TYPE_SELECT,label:'Select option',values:[{id:100,unitPriceModifier:0}]},{id:11,type:OPTION_TYPE_TEXT,label:'Text option',unitPriceModifier:0}];var options=[{id:10,type:OPTION_TYPE_SELECT,label:'Select option',values:[{id:100}]},{id:11,type:OPTION_TYPE_TEXT,label:'Text option'}];expect(formatOptions(options)).toEqual(expected);});});
@@ -1,5 +0,0 @@
1
- import{mockedState as mockedProductState,mockedVariantStateAllFetching,mockedVariantStateVariantDataFetching,mockedVariantStateVariantsFetching,mockedVariantStateComplete}from"./product.mock";import{isProductPageLoading}from"./page";/**
2
- * Creates a deep copy of a passed to avoid unintended selector caching.
3
- * @param {Object} mockedState A mocked state.
4
- * @return {Object}
5
- */var createState=function createState(mockedState){return JSON.parse(JSON.stringify(mockedState));};describe('Product page selectors',function(){var propsBase={productId:'product_1'};var propsFull={productId:'product_1',variantId:'product_2'};var mockedDefaultState;beforeEach(function(){mockedDefaultState=JSON.parse(JSON.stringify(mockedProductState));jest.clearAllMocks();});describe('isProductPageLoading()',function(){describe('Simple products without variants',function(){it('should return true if the product is fetching',function(){var productId='product_4';expect(isProductPageLoading(mockedDefaultState,{productId:productId})).toBe(true);});it('should return false if the product is loaded',function(){var productId='product_5';expect(isProductPageLoading(mockedDefaultState,{productId:productId})).toBe(false);});});describe('Products with variants',function(){it('should return true if the base product is fetching',function(){var state=createState(mockedVariantStateAllFetching);expect(isProductPageLoading(state,propsBase)).toBe(true);});it('should return true if the variant data is fetching',function(){var state=createState(mockedVariantStateVariantDataFetching);expect(isProductPageLoading(state,propsBase)).toBe(true);});it('should return false if basic data is loaded, but no variant product is selected yet',function(){expect(isProductPageLoading(mockedDefaultState,propsBase)).toBe(false);});it('should return true if a variant is selected, but the product data is fetching',function(){var state=createState(mockedVariantStateVariantsFetching);expect(isProductPageLoading(state,propsFull)).toBe(true);});it('should return false if a variant product is selected an all data is present',function(){var state=createState(mockedVariantStateComplete);expect(isProductPageLoading(state,propsFull)).toBe(false);});});});});
@@ -1,23 +0,0 @@
1
- import{getProductUnitPrice,getProductCurrency}from"./product";import{getRawProductOptions,getProductOptions}from"./options";import{getProductPriceAddition,getProductTotalPrice,isFullPriceAvailable}from"./price";import{basicProductState,productWithOneOption,productWithSelectedOptions,productWithVariants,productWithSelectedVariant,productWithVariantsAndOptions}from"../mock";describe('Product.Price selectors',function(){describe('Simple data selectors',function(){it('should validate simple data selectors',function(){expect(getProductUnitPrice(basicProductState,{productId:'913'})).toBe(89);expect(getProductCurrency(basicProductState,{productId:'913'})).toBe('EUR');});});describe('Additional price calculation',function(){it('should calculate no additional costs for a basic product',function(){expect(getProductPriceAddition(basicProductState,{productId:'913'})).toBe(0);expect(getProductTotalPrice(basicProductState,{productId:'913'})).toBe(89);});it('should calculate no additional cost when no options are selected',function(){expect(getProductPriceAddition(productWithOneOption,{productId:'1097'})).toBe(0);expect(getProductTotalPrice(productWithOneOption,{productId:'1097'})).toBe(10);});it('should calculate additional cost when one option is selected',function(){var props={productId:'1097',options:{1:'1',// select option
2
- 10:'Foo bar'// text option
3
- }};expect(getProductPriceAddition(productWithSelectedOptions,props)).toBe(4);expect(getProductTotalPrice(productWithSelectedOptions,props)).toBe(14);});it('should calculate no additional cost for a product with just variants',function(){expect(getProductPriceAddition(productWithSelectedVariant,{productId:'dif01-exp'})).toBe(0);expect(getProductTotalPrice(productWithSelectedVariant,{productId:'dif01-exp'})).toBe(26);});});describe('Min price calculation',function(){it('price should be available for a basic product',function(){expect(isFullPriceAvailable(basicProductState,{productId:'913'})).toBe(true);});it('price should not be available for a product with unselected options',function(){var props={productId:'1097',options:{}};expect(isFullPriceAvailable(productWithOneOption,props)).toBe(false);});it('price should be available for a product with selected options',function(){var props={productId:'1097',options:{1:'1',10:'Foo bar'}};expect(isFullPriceAvailable(productWithSelectedOptions,props)).toBe(true);});it('price should not be available for a product with unselected variants',function(){expect(isFullPriceAvailable(productWithVariants,{productId:'dif01'})).toBe(false);});it('price should be available for a product with selected variants',function(){expect(isFullPriceAvailable(productWithSelectedVariant,{productId:'dif01-exp'})).toBe(true);});});/**
4
- * Checks:
5
- * - Product Options are remembered across variants.
6
- * - From price should be used when the selection is not complete.
7
- * - Additional price should be available after selecting an option.
8
- * - Total price should be always the additional price + base price.
9
- * - Additional costs per item are correct.
10
- */describe('Scenario #1: Product with variants and options',function(){var state=productWithVariantsAndOptions;it('Step 1: Opening the product',function(){var props={productId:'SG74',productVariantId:null,currentOptions:{}};// No additional price can be calculated at the moment.
11
- expect(getProductPriceAddition(state,props)).toBe(0);expect(getProductTotalPrice(state,props)).toBe(10.51);expect(isFullPriceAvailable(state,props)).toBe(false);// No product options can be found since they are on the variant only.
12
- expect(getRawProductOptions(state,props)).toBeFalsy();});it('Step 2: Select a children/variant',function(){var props={productId:'SG74',variantId:'SG76',currentOptions:{}};// Additional price can still not be calculated because options are not available.
13
- expect(getProductPriceAddition(state,props)).toBe(0);expect(getProductTotalPrice(state,props)).toBe(10.52);expect(isFullPriceAvailable(state,props)).toBe(false);// Product options are now available.
14
- expect(getRawProductOptions(state,props).length).toBe(1);// Peak into the calculated relative additional price differences.
15
- // Price modifiers stay constant, because they're absolute.
16
- // Price modifier and difference is equal when nothing is selected, yet
17
- var availableOptions=getProductOptions(state,props);expect(availableOptions[0].items[0].price).toBe(5);expect(availableOptions[0].items[0].priceDifference).toBe(5);expect(availableOptions[0].items[1].price).toBe(4);expect(availableOptions[0].items[1].priceDifference).toBe(4);});it('Step 3: Select the option',function(){var props={productId:'SG74',variantId:'SG76',options:{1:'5'},currentOptions:{1:'5'}};// Additional price can now be calculated.
18
- expect(getProductPriceAddition(state,props)).toBe(5);expect(getProductTotalPrice(state,props)).toBe(15.52);// Peak into the calculated relative additional price differences.
19
- // Price modifiers stay constant, because they're absolute.
20
- // Price modifiers stay constant, because they're absolute.
21
- var availableOptions=getProductOptions(state,props);expect(availableOptions[0].items[0].price).toBe(5);expect(availableOptions[0].items[0].priceDifference).toBe(0);expect(availableOptions[0].items[1].price).toBe(4);expect(availableOptions[0].items[1].priceDifference).toBe(-1);expect(isFullPriceAvailable(state,props)).toBe(true);});it('Step 4: Change to a different variant',function(){var props={productId:'SG74',variantId:'SG78',options:{1:'5'},currentOptions:{1:'5'}};// Additional price should still be calculated
22
- expect(getProductPriceAddition(state,props)).toBe(5);expect(getProductTotalPrice(state,props)).toBe(15.54);expect(isFullPriceAvailable(state,props)).toBe(true);// Product options are still available.
23
- expect(getRawProductOptions(state,props).length).toBe(1);});});});
@@ -1,2 +0,0 @@
1
- function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}/* eslint-disable extra-rules/no-single-line-objects */import upperFirst from'lodash/upperFirst';import{logger}from'@shopgate/pwa-core/helpers';import{PROPERTIES_FILTER_BLACKLIST,PROPERTIES_FILTER_WHITELIST}from"../constants";import{mockedState as mockedProductState,mockedProductMetadata,mockedProductsById,mockedShippingByProductId,mockedDescriptionsByProductId,mockedPropertiesByProductId,mockedProperty1,mockedProperty2,mockedImagesByProductId,mockedProductImagesBase,mockedProductImagesVariant,mockedVariantsByProductId}from"./product.mock";import{getProductState,getProducts,getProductShippingState,getProductDescriptionState,getProductPropertiesState,getProductImagesState,getProductVariantsState,getProductById,getProductId,getVariantProductId,isVariantSelected,getProduct,getProductName,getProductLongName,getProductRating,getProductManufacturer,getProductStock,getProductAvailability,getProductFlags,getProductMetadata,getBaseProductMetadata,getProductPriceData,getProductCurrency,getProductUnitPrice,getProductShipping,getProductDescription,getProductProperties,getProductImages,getProductVariants,isProductOrderable,hasProductVariants,getSelectedVariant,isBaseProduct,getBaseProductId,getBaseProduct,hasBaseProductVariants,getVariantId,getVariantAvailabilityByCharacteristics,hasProductVariety}from"./product";jest.mock('@shopgate/pwa-core/helpers',function(){var original=require.requireActual('@shopgate/pwa-core/helpers');return _extends({},original,{logger:{warn:jest.fn(),error:jest.fn()}});});var mockedConfig;jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get productPropertiesFilter(){return mockedConfig;}};});describe('Product selectors',function(){var mockedState;beforeEach(function(){// Create a deep copy of the state to avoid unintended selector caching.
2
- mockedState=JSON.parse(JSON.stringify(mockedProductState));mockedConfig=null;jest.clearAllMocks();});describe('getProductState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductState({})).toEqual({});});it('should work as expected',function(){var _mockedState=mockedState,product=_mockedState.product;expect(getProductState(mockedState)).toEqual(product);});});describe('getProducts()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProducts({})).toEqual({});});it('should work as expected',function(){expect(getProducts(mockedState)).toEqual(mockedProductsById);});});describe('getProductShippingState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductShippingState({})).toEqual({});});it('should work as expected',function(){expect(getProductShippingState(mockedState)).toEqual(mockedShippingByProductId);});});describe('getProductDescriptionState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductDescriptionState({})).toEqual({});});it('should work as expected',function(){expect(getProductDescriptionState(mockedState)).toEqual(mockedDescriptionsByProductId);});});describe('getProductPropertiesState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductPropertiesState({})).toEqual({});});it('should work as expected',function(){expect(getProductPropertiesState(mockedState)).toEqual(mockedPropertiesByProductId);});});describe('getProductImagesState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductImagesState({})).toEqual({});});it('should work as expected',function(){expect(getProductImagesState(mockedState)).toEqual(mockedImagesByProductId);});});describe('getProductVariantsState()',function(){it('should return an empty object if the state is not ready yet',function(){expect(getProductVariantsState({})).toEqual({});});it('should work as expected',function(){expect(getProductVariantsState(mockedState)).toEqual(mockedVariantsByProductId);});});describe('getProductById()',function(){var productId='product_5';var product=mockedProductsById[productId];it('should return null when empty props are passed',function(){expect(getProductById({},{})).toBeNull();});it('should return null when no products are selectable yet',function(){expect(getProductById({},{productId:productId})).toBeNull();});it('should return null when the expected product is not available',function(){expect(getProductById({},{productId:'unavailable'})).toBeNull();});it('should return a product',function(){expect(getProductById(mockedState,{productId:productId})).toEqual(product);});it('should return a product when a product id was passed in the deprecated way',function(){expect(getProductById(mockedState,productId)).toEqual(product);expect(logger.warn).toHaveBeenCalledTimes(1);});it('should null when no props objects was passed',function(){expect(getProductById(mockedState)).toBeNull();expect(logger.warn).toHaveBeenCalledTimes(1);});});describe('getProductId()',function(){it('should return null when no props are passed',function(){expect(getProductId()).toBeNull();});it('should return null when no productId was passed within the props',function(){expect(getProductId({},{})).toBeNull();});it('should return a productId',function(){var productId='product_id';expect(getProductId({},{productId:productId})).toBe(productId);});it('should return a variantId',function(){var productId='product_id';var variantId='variant_id';expect(getProductId({},{productId:productId,variantId:variantId})).toBe(variantId);});it('should return a productId when a passed variantId is undefined',function(){var productId='product_id';var variantId;expect(getProductId({},{productId:productId,variantId:variantId})).toBe(productId);});it('should return a productId when a passed variantId is null',function(){var productId='product_id';var variantId=null;expect(getProductId({},{productId:productId,variantId:variantId})).toBe(productId);});});describe('getVariantProductId()',function(){it('should return null and log a message when no props are passed',function(){expect(getVariantProductId(mockedState)).toBeNull();expect(logger.error).toHaveBeenCalledTimes(1);});it('should return null when the props dont contain a variantId',function(){expect(getVariantProductId(mockedState,{productId:'product_1'})).toBeNull();});it('should return the expected variant id',function(){var variantId='product_2';expect(getVariantProductId(mockedState,{variantId:variantId})).toBe(variantId);});});describe('isVariantSelected()',function(){it('should return false when no variantId was passed',function(){expect(isVariantSelected({},{productId:'product_1'})).toBe(false);});it('should return true when a variantId was passed',function(){var productId='product_1';var variantId='product_2';expect(isVariantSelected(mockedState,{productId:productId,variantId:variantId})).toBe(true);});});describe('getProduct()',function(){it('should return null and log an error when no props are passed',function(){expect(getProduct(mockedState)).toBeNull();});it('should return null when the product is not selectable yet',function(){var productId='product_5';expect(getProduct({},{productId:productId})).toBeNull();});it('should return null when the product data is not available yet',function(){var productId='product_4';expect(getProduct(mockedState,{productId:productId})).toBeNull();});it('should return product data of a simple product',function(){var productId='product_5';var productData=mockedProductsById[productId].productData;expect(getProduct(mockedState,{productId:productId})).toEqual(productData);});it('should return product data of a variant product',function(){var productId='product_1';var variantId='product_2';var productData=mockedProductsById[variantId].productData;expect(getProduct(mockedState,{productId:productId,variantId:variantId})).toEqual(productData);});});describe('Product property selectors',function(){var productId='product_5';var productData=mockedProductsById[productId].productData;var tests=[[getProductName,'name'],[getProductRating,'rating'],[getProductManufacturer,'manufacturer'],[getProductStock,'stock'],[getProductAvailability,'availability'],[getProductFlags,'flags'],[getProductPriceData,'price'],[getProductMetadata,'metadata']];tests.forEach(function(test){var _test=_slicedToArray(test,2),selector=_test[0],property=_test[1];describe("getProduct".concat(upperFirst(property),"()"),function(){it('should return null when the product is not available',function(){expect(selector({},{productId:productId})).toBeNull();});it('should return the property as expected',function(){expect(selector(mockedState,{productId:productId})).toEqual(productData[property]);});});});describe('getProductLongName()',function(){it('should return the property as expected',function(){var id='product_5';var mockProductData=mockedProductsById[id].productData;expect(getProductLongName(mockedState,{productId:id})).toEqual(mockProductData.longName);});it('should return the short name if long is not available',function(){var id='product_7';var mockProductData=mockedProductsById[id].productData;expect(getProductLongName(mockedState,{productId:id})).toEqual(mockProductData.name);});it('should return null if no data is available',function(){expect(getProductLongName(mockedState,{productId:'product_4'})).toEqual(null);});});describe('getBaseProductMetadata()',function(){it('should return null when the product is not available',function(){expect(getBaseProductMetadata({},{productId:productId})).toBeNull();});it('should return the property as expected',function(){expect(getBaseProductMetadata(mockedState,{productId:'product_2'})).toEqual(mockedProductMetadata);});});describe('getProductCurrency()',function(){it('should return null when the product is not available',function(){expect(getProductCurrency({},{productId:productId})).toBeNull();});it('should return the property as expected',function(){expect(getProductCurrency(mockedState,{productId:productId})).toBe(productData.price.currency);});});describe('getProductUnitPrice()',function(){it('should return null when the product is not available',function(){expect(getProductUnitPrice({},{productId:productId})).toBeNull();});it('should return the property as expected',function(){expect(getProductUnitPrice(mockedState,{productId:productId})).toBe(productData.price.unitPrice);});});});describe('getProductShipping()',function(){it('should return null when no data can be selected for the passed productId',function(){var productId='unavailable';expect(getProductShipping({},{productId:productId})).toBeNull();});it('should return null when a product is present but no data is available yet',function(){var productId='product_4';expect(getProductShipping(mockedState,{productId:productId})).toBeNull();});it('should return null when data is currently fetching',function(){var productId='product_5';expect(getProductShipping(mockedState,{productId:productId})).toBeNull();});it('should return data when available',function(){var productId='product_1';var shipping=mockedShippingByProductId[productId].shipping;expect(getProductShipping(mockedState,{productId:productId})).toEqual(shipping);});});describe('getProductProperties()',function(){it('should return null when no data can be selected for the passed productId',function(){var productId='unavailable';expect(getProductProperties({},{productId:productId})).toBeNull();});it('should return null when a product is present but no data is available yet',function(){var productId='product_4';expect(getProductProperties(mockedState,{productId:productId})).toBeNull();});it('should return null when data is currently fetching',function(){var productId='product_5';expect(getProductProperties(mockedState,{productId:productId})).toBeNull();});it('should return data when available',function(){var productId='product_1';var properties=mockedPropertiesByProductId[productId].properties;expect(getProductProperties(mockedState,{productId:productId})).toEqual(properties);});describe('Black and whitelisting of properties',function(){var selectorProps={productId:'product_1'};it('should get whitelisted properties',function(){mockedConfig={type:PROPERTIES_FILTER_WHITELIST,properties:[mockedProperty1.label]};var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(1);expect(properties[0].label).toEqual(mockedProperty1.label);expect(properties[0].label).not.toEqual(mockedProperty2.label);});it('should not get blacklisted properties',function(){mockedConfig={type:PROPERTIES_FILTER_BLACKLIST,properties:[mockedProperty1.label]};var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(1);expect(properties[0].label).not.toEqual(mockedProperty1.label);expect(properties[0].label).toEqual(mockedProperty2.label);});it('should not filter with invalid type',function(){mockedConfig={type:'foo',properties:[mockedProperty1.label]};var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(2);expect(properties).toEqual([mockedProperty1,mockedProperty2]);});it('should not filter when no config is set',function(){mockedConfig=null;var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(2);expect(properties).toEqual([mockedProperty1,mockedProperty2]);});it('should filter all when whitelist is empty array',function(){mockedConfig={type:PROPERTIES_FILTER_WHITELIST,properties:[]};var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(0);});it('should pass all when blacklist is empty array',function(){mockedConfig={type:PROPERTIES_FILTER_BLACKLIST,properties:[]};var properties=getProductProperties(mockedState,selectorProps);expect(properties.length).toEqual(2);});});});describe('getProductDescription()',function(){it('should return null when no data can be selected for the passed productId',function(){var productId='unavailable';expect(getProductDescription({},{productId:productId})).toBeNull();});it('should return null when a product is present but no data is available yet',function(){var productId='product_4';expect(getProductDescription(mockedState,{productId:productId})).toBeNull();});it('should return null when data is currently fetching',function(){var productId='product_5';expect(getProductDescription(mockedState,{productId:productId})).toBeNull();});it('should return data when available',function(){var productId='product_1';var description=mockedDescriptionsByProductId[productId].description;expect(getProductDescription(mockedState,{productId:productId})).toEqual(description);});});describe('getProductImages()',function(){it('should return null when no data can be selected for the passed productId',function(){var productId='unavailable';expect(getProductImages({},{productId:productId})).toBeNull();});it('should return null when a product is present but no data is available yet',function(){var productId='product_4';expect(getProductImages(mockedState,{productId:productId})).toBeNull();});it('should return null when data is currently fetching',function(){var productId='product_5';expect(getProductImages(mockedState,{productId:productId})).toBeNull();});it('should return null when a product does not have images',function(){var productId='product_1';mockedState.product.imagesByProductId[productId].images=[];expect(getProductImages(mockedState,{productId:productId})).toEqual(null);});it('should return null when no props are passed',function(){expect(getProductImages({})).toBeNull();});it('should return images when available',function(){var productId='product_1';expect(getProductImages(mockedState,{productId:productId})).toEqual(mockedProductImagesBase);});it('should return images for a variant when productId and variantId are passed',function(){var productId='product_1';var variantId='product_2';expect(getProductImages(mockedState,{productId:productId,variantId:variantId})).toEqual(mockedProductImagesVariant);});it('should return images for a variant when only the variantId is passed',function(){var variantId='product_2';expect(getProductImages(mockedState,{variantId:variantId})).toEqual(mockedProductImagesVariant);});it('should return images for a variant when the id of a variant is passed as a productId',function(){var productId='product_2';expect(getProductImages(mockedState,{productId:productId})).toEqual(mockedProductImagesVariant);});it('should return images of the base product when a variant has no images',function(){var productId='product_1';var variantId='product_3';mockedState.product.imagesByProductId[variantId].images=[];expect(getProductImages(mockedState,{productId:productId,variantId:variantId})).toEqual(mockedProductImagesBase);});it('should return images of the base product when a variant has no images and only the variantId is passed',function(){var variantId='product_3';mockedState.product.imagesByProductId[variantId].images=[];expect(getProductImages(mockedState,{variantId:variantId})).toEqual(mockedProductImagesBase);});it('should return images of the base product when the id of a variant is passed as a productId',function(){var productId='product_3';expect(getProductImages(mockedState,{productId:productId})).toEqual(mockedProductImagesBase);});});describe('getProductVariants()',function(){it('should return null when no data can be selected for the passed productId',function(){var productId='unavailable';expect(getProductVariants(mockedState,{productId:productId})).toBeNull();});it('should return null when a product is present but no data is available yet',function(){var productId='product_1';delete mockedState.product.variantsByProductId[productId];expect(getProductVariants(mockedState,{productId:productId})).toBeNull();});it('should return null when data is currently fetching',function(){var productId='product_1';var state=mockedState.product.variantsByProductId[productId];state.isFetching=true;state.variants=undefined;expect(getProductVariants(mockedState,{productId:productId})).toBeNull();});it('should return data when the productId of a base product is passed',function(){var productId='product_1';var variants=mockedVariantsByProductId[productId].variants;expect(getProductVariants(mockedState,{productId:productId})).toEqual(variants);});it('should return data when the productId of a base product and a variantId is passed',function(){var productId='product_1';var variantId='product_2';var variants=mockedVariantsByProductId[productId].variants;expect(getProductVariants(mockedState,{productId:productId,variantId:variantId})).toEqual(variants);});it('should return data when only the id of a variant is passed',function(){var productId='product_2';var variants=mockedVariantsByProductId.product_1.variants;expect(getProductVariants(mockedState,{productId:productId})).toEqual(variants);});});describe('isProductOrderable()',function(){it('should return false when the product is not available',function(){var productId='unavailable';expect(isProductOrderable(mockedState,{productId:productId})).toBe(false);});it('should return false when the product does not have stock info',function(){var productId='product_4';expect(isProductOrderable(mockedState,{productId:productId})).toBe(false);});it('should return false when the product is not orderable',function(){var productId='product_3';expect(isProductOrderable(mockedState,{productId:productId})).toBe(false);});it('should return true when the product is orderable',function(){var productId='product_5';expect(isProductOrderable(mockedState,{productId:productId})).toBe(true);});});describe('hasProductVariants()',function(){it('should return false when the product is not available',function(){var productId='unavailable';expect(hasProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return false when the product does not have variants',function(){var productId='product_5';expect(hasProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return true when the product has variants',function(){var productId='product_1';expect(hasProductVariants(mockedState,{productId:productId})).toBe(true);});});describe('getSelectedVariant()',function(){it('should return null when no variant is selected',function(){var productId='product_1';expect(getSelectedVariant(mockedState,{productId:productId})).toBeNull();});it('should return null when no variant is selected',function(){var productId='product_1';var variantId='unknown';expect(getSelectedVariant(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return null for a fetching product',function(){var productId='product_1';var variantId='product_4';expect(getSelectedVariant(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return a product',function(){var productId='product_1';var variantId='product_2';var productData=mockedProductsById[variantId].productData;expect(getSelectedVariant(mockedState,{productId:productId,variantId:variantId})).toEqual(productData);});});describe('isBaseProduct()',function(){it('should indicate base products',function(){expect(isBaseProduct(mockedState,{productId:'product_1'})).toBe(true);expect(isBaseProduct(mockedState,{productId:'product_2'})).toBe(false);expect(isBaseProduct(mockedState,{productId:'product_4'})).toBe(false);expect(isBaseProduct(mockedState,{productId:'product_5'})).toBe(true);});});describe('getBaseProductId()',function(){it('should return null when props are not given',function(){expect(getBaseProductId(mockedState)).toBeNull();});it('should return null when product is not found in store',function(){var productId='unknown';expect(getBaseProductId(mockedState,{productId:productId})).toBeNull();});it('should return the id of a base product when baseProductId is null',function(){var productId='product_5';expect(getBaseProductId(mockedState,{productId:productId})).toBe(productId);});it('should return the id of a simple product',function(){var productId='product_5';expect(getBaseProductId(mockedState,{productId:productId})).toBe(productId);});it('should return the id of a base product when no variantId is in props',function(){var productId='product_1';expect(getBaseProductId(mockedState,{productId:productId})).toBe(productId);});it('should return the id of a base product when a variantId is in props',function(){var productId='product_1';var variantId='product_2';expect(getBaseProductId(mockedState,{productId:productId,variantId:variantId})).toBe(productId);});it('should return the id of a base product when a variantId is in props even if there is no variant product in the store',function(){var productId='product_1';var variantId='product_2';delete mockedState.product.variantsByProductId[variantId];expect(getBaseProductId(mockedState,{productId:productId,variantId:variantId})).toBe(productId);});});describe('getBaseProduct()',function(){it('should return null and log an error when no props are passed',function(){expect(getBaseProduct(mockedState)).toBeNull();});it('should return null when the product is not available',function(){var productId='unavailable';expect(getBaseProduct(mockedState,{productId:productId})).toBeNull();});it('should return null when the base product is not available',function(){var productId='product_2';delete mockedState.product.productsById.product_1;expect(getBaseProduct(mockedState,{productId:productId})).toBeNull();});it('should return the the base product when no variant is selected yet',function(){var productId='product_1';var productData=mockedProductsById[productId].productData;expect(getBaseProduct(mockedState,{productId:productId})).toEqual(productData);});it('should return the the base product when a variant is selected',function(){var productId='product_1';var variantId='product_2';var productData=mockedProductsById[productId].productData;expect(getBaseProduct(mockedState,{productId:productId,variantId:variantId})).toEqual(productData);});it('should return the the base product when only a variant is selected',function(){var productId='product_1';var variantId='product_2';var productData=mockedProductsById[productId].productData;expect(getBaseProduct(mockedState,{variantId:variantId})).toEqual(productData);});});describe('hasBaseProductVariants()',function(){it('should return false when the product is not available',function(){var productId='unavailable';expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return false when the base product is not available',function(){var productId='product_2';delete mockedState.product.productsById.product_1;expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return false when the flags are missing',function(){var productId='product_1';delete mockedState.product.productsById[productId].productData.flags;expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return false when no product data is available yet',function(){var productId='product_4';expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return false when the product does not have variants',function(){var productId='product_5';expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(false);});it('should return true when the product has variants',function(){var productId='product_1';expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(true);});it('should return true when the products base product has variants',function(){var productId='product_2';expect(hasBaseProductVariants(mockedState,{productId:productId})).toBe(true);});});describe('getVariantId()',function(){it('should return null when the product is not available',function(){var productId='unavailable';expect(getVariantId(mockedState,{productId:productId})).toBeNull();});it('should return null when the product is a simple product',function(){var productId='product_5';expect(getVariantId(mockedState,{productId:productId})).toBeNull();});it('should return null when the product is a base product',function(){var productId='product_1';expect(getVariantId(mockedState,{productId:productId})).toBeNull();});it('should return a productId when the product is a variant product',function(){var productId='product_2';expect(getVariantId(mockedState,{productId:productId})).toBe(productId);});it('should return the productId of the variant if base product and variant are selected',function(){var productId='product_1';var variantId='product_2';expect(getVariantId(mockedState,{productId:productId,variantId:variantId})).toBe(variantId);});});describe('getVariantAvailabilityByCharacteristics()',function(){it('should return null and log an error message when no props where passed',function(){expect(getVariantAvailabilityByCharacteristics(mockedState)).toBeNull();});it('should return null when no variants are available yet',function(){var productId='unavailable';var characteristics={};var props={productId:productId,characteristics:characteristics};expect(getVariantAvailabilityByCharacteristics(mockedState,props)).toBeNull();});it('should return null when no matching product was found',function(){var productId='product_1';var characteristics={1:'5'};var props={productId:productId,characteristics:characteristics};expect(getVariantAvailabilityByCharacteristics(mockedState,props)).toBeNull();});it('should return data when a matching product was found',function(){var productId='product_1';var _mockedVariantsByProd=mockedVariantsByProductId[productId].variants.products[1],characteristics=_mockedVariantsByProd.characteristics,availability=_mockedVariantsByProd.availability;var props={productId:productId,characteristics:characteristics};expect(getVariantAvailabilityByCharacteristics(mockedState,props)).toEqual(availability);});});describe('hasProductVariety()',function(){it('should return null for missing product data',function(){expect(hasProductVariety(mockedState)).toBeNull();expect(hasProductVariety(mockedState,{productId:'unknown'})).toBeNull();});it('should return false for simple product',function(){expect(hasProductVariety(mockedState,{productId:'product_5'})).toBeFalsy();});it('should return true for variants',function(){expect(hasProductVariety(mockedState,{productId:'product_1'})).toBeTruthy();});it('should return true for options',function(){mockedState.product.productsById.product_5.productData.flags.hasOptions=true;expect(hasProductVariety(mockedState,{productId:'product_1'})).toBeTruthy();});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1,4 +0,0 @@
1
- function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import{getRelatedProducts}from"./relations";describe('Relations selectors',function(){describe('getRelatedProducts',function(){it('should memoize selector properly',function(){var hash='{"limit":20,"pipeline":"shopgate.catalog.getProductRelations","productId":"a","type":"upselling"}';var state={product:{productsById:{a:{productData:{id:'a'}},b:{productData:{id:'b'}}},productRelationsByHash:_defineProperty({},hash,{productIds:['b']})}};var expectedResult=[{id:'b'}];// First selector run.
2
- var selector=getRelatedProducts({productId:'a',type:'upselling',limit:20});var result1=selector(state);expect(result1).toEqual(expectedResult);expect(selector.recomputations()).toBe(1);// Second selector run. It should not recompute, state did not change.
3
- var result2=selector(state);expect(result2).toEqual(expectedResult);expect(selector.recomputations()).toBe(1);state={product:_extends({},state.product,{productRelationsByHash:_extends({},state.product.productRelationsByHash,_defineProperty({},hash,{productIds:['b','c']}))})};// State did change. It should recompute.
4
- var result3=selector(state);expect(result3).toEqual(expectedResult);expect(selector.recomputations()).toBe(2);});});});
@@ -1,2 +0,0 @@
1
- function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}/* eslint-disable extra-rules/no-single-line-objects */import{mockedState as mockedProductState,mockedVariantProductMetadata,mockedVariantMetadata}from"./product.mock";import{getSelectedVariantMetadata,getKnownRelatives}from"./variants";jest.mock('@shopgate/pwa-core/helpers',function(){var original=require.requireActual('@shopgate/pwa-core/helpers');return _extends({},original,{logger:{error:jest.fn()}});});describe('Variants selectors',function(){var mockedState;beforeEach(function(){// Create a deep copy of the state to avoid unintended selector caching.
2
- mockedState=JSON.parse(JSON.stringify(_extends({},mockedProductState)));jest.clearAllMocks();});describe('getSelectedVariantMetadata()',function(){it('should return undefined when no variant data is available at all but the variant product is there',function(){var productId='product_1';var variantId='product_3';delete mockedState.product.variantsByProductId;expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeUndefined();});it('should return null when no variant data is available at all an no variant product can be determined',function(){var productId='product_1';var variantId='product_10';delete mockedState.product.variantsByProductId;expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return null when no variant data is available for the parameters inside of the props',function(){var productId='product_1';var variantId='product_6';expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return null when no variant data is available for the referenced product ids',function(){var productId='product_8';var variantId='product_9';expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return undefined when neither the variant data, nor the variant product contains metadata',function(){var productId='product_1';var variantId='product_2';delete mockedState.product.productsById[variantId].productData.metadata;expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeUndefined();});it('should return null when neither the variant product is not available yet',function(){var productId='product_1';var variantId='product_2';delete mockedState.product.productsById[variantId];expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toBeNull();});it('should return metadata from the variant data',function(){var productId='product_1';var variantId='product_3';expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toEqual(mockedVariantMetadata);});it('should return metadata from the variant product',function(){var productId='product_1';var variantId='product_2';expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toEqual(mockedVariantProductMetadata);});it('should return metadata from the variant product when variant data is not available',function(){var productId='product_1';var variantId='product_2';mockedState.product.variantsByProductId[productId].variants.products.splice(0,1);expect(getSelectedVariantMetadata(mockedState,{productId:productId,variantId:variantId})).toEqual(mockedVariantProductMetadata);});});describe('getKnownRelatives()',function(){it('should return parent and children for given parentId',function(){expect(getKnownRelatives(mockedState,{productId:'parent'})).toEqual(['parent','child','child2']);});it('should return parent and children for given child id',function(){expect(getKnownRelatives(mockedState,{productId:'child'})).toEqual(['parent','child','child2']);});it('should return notAChild and it\'s parent only',function(){expect(getKnownRelatives(mockedState,{productId:'notAChild'})).toEqual(['notAChild','foo']);});it('should return empty array on empty product data',function(){expect(getKnownRelatives(mockedState,{productId:'not_exist'})).toEqual([]);});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1,8 +0,0 @@
1
- /* eslint-disable extra-rules/no-single-line-objects */import{combineReducers}from'redux';import{createMockStore}from'@shopgate/pwa-common/store';import{ENOTFOUND}from'@shopgate/pwa-core';import{mainSubject}from'@shopgate/pwa-common/store/middelwares/streams';import{bin2hex as mockBin2Hex}from'@shopgate/pwa-common/helpers/data';import{routeDidUpdate}from'@shopgate/pwa-common/action-creators/router';import{ROUTE_WILL_ENTER}from'@shopgate/pwa-common/constants/ActionTypes';import{ACTION_UPDATE}from'@virtuous/conductor';import router from'@shopgate/pwa-common/reducers/router';import product from'@shopgate/pwa-common-commerce/product/reducers';import receiveProduct from'@shopgate/pwa-common-commerce/product/action-creators/receiveProduct';import errorProduct from"../action-creators/errorProduct";import{ITEM_PATTERN}from"../constants";import{productReceived$,variantWillUpdate$,variantDidChange$,visibleProductNotFound$}from"./index";jest.mock("../selectors/product",function(){return{getBaseProduct:function getBaseProduct(){return{id:'variantId'};}};});/**
2
- * Wrapper for the routeWillEnter action. It also sets up the mocked current route.
3
- * @param {string} pattern A route pattern.
4
- * @param {string} historyAction A history action.
5
- * @param {string} productId A product id.
6
- * @param {string} variantId A variant id.
7
- * @return {Object}
8
- */var wrappedRouteDidUpdate=function wrappedRouteDidUpdate(pattern,historyAction){var productId=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'';var variantId=arguments.length>3&&arguments[3]!==undefined?arguments[3]:'';return routeDidUpdate({pattern:pattern,params:{productId:mockBin2Hex(productId)},state:{productId:variantId}},historyAction);};describe('Product streams',function(){var store;var dispatch;beforeEach(function(){store=createMockStore(combineReducers({product:product,router:router}));var _store=store;dispatch=_store.dispatch;});describe('productReceived$',function(){var productReceivedSubscriber;beforeEach(function(){productReceivedSubscriber=jest.fn();productReceived$.subscribe(productReceivedSubscriber);});it('should emit when a product was received',function(){dispatch(receiveProduct());expect(productReceivedSubscriber).toHaveBeenCalledTimes(1);});it('should not emit for other actions',function(){dispatch({type:'someaction'});expect(productReceivedSubscriber).not.toHaveBeenCalled();});});describe('variantWillUpdate$',function(){var variantWillUpdateSubscriber;beforeEach(function(){variantWillUpdateSubscriber=jest.fn();variantWillUpdate$.subscribe(variantWillUpdateSubscriber);});it('should emit when an item page was updated',function(){dispatch(wrappedRouteDidUpdate(ITEM_PATTERN,ACTION_UPDATE));expect(variantWillUpdateSubscriber).toHaveBeenCalledTimes(1);});});describe('variantDidChange$',function(){var variantDidChangeSubscriber;var baseProductId='baseProductId';var productId='productId';var variantId='variantId';beforeEach(function(){variantDidChangeSubscriber=jest.fn();variantDidChange$.subscribe(variantDidChangeSubscriber);});it('should emit when a variant was selected and base product data is available',function(){dispatch(wrappedRouteDidUpdate(ITEM_PATTERN,ACTION_UPDATE,productId,variantId));dispatch(receiveProduct(variantId,{id:variantId,baseProductId:baseProductId}));expect(variantDidChangeSubscriber).toHaveBeenCalledTimes(1);});});describe('visibleProductNotFound$',function(){var hex='5347313030';var bin='SG100';var subscriber;beforeEach(function(){subscriber=jest.fn();});it('should emit error action',function(){visibleProductNotFound$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:ITEM_PATTERN,params:{productId:hex}}}});var notFound=errorProduct(bin,ENOTFOUND);mainSubject.next({action:notFound});expect(subscriber).toHaveBeenCalledTimes(1);expect(subscriber).toHaveBeenCalledWith({action:notFound});});it('should not emit for not visible product',function(){visibleProductNotFound$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_WILL_ENTER,route:{pattern:ITEM_PATTERN,params:{productId:'OTHER_PRODUCT'}}}});var notFound=errorProduct(bin,ENOTFOUND);mainSubject.next({action:notFound});expect(subscriber).toHaveBeenCalledTimes(0);});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}/* eslint-disable extra-rules/no-single-line-objects */import{ENOTFOUND}from'@shopgate/pwa-core';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{historyPop}from'@shopgate/engage/core';import expireProductById from"../action-creators/expireProductById";import subscription from"./index";import errorProduct from"../action-creators/errorProduct";import fetchProductImages from"../actions/fetchProductImages";import{galleryWillEnter$,productRelationsReceived$}from"../streams";var mockedGetProductsById=jest.fn();jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn();});jest.mock('@shopgate/engage/core',function(){return{historyPop:jest.fn()};});jest.mock("../actions/fetchProductsById",function(){return function(){return mockedGetProductsById.apply(void 0,arguments);};});jest.mock("../action-creators/expireProductById",function(){return jest.fn();});jest.mock("../actions/fetchProductImages",function(){return jest.fn();});describe('Product subscription',function(){var subscribe=jest.fn();var getState=jest.fn();var dispatch=jest.fn().mockResolvedValue();beforeAll(function(){subscription(subscribe);});it('should subscribe',function(){expect(subscribe).toHaveBeenCalledTimes(10);});describe('galleryWillEnter$',function(){var galleryWillEnter$Subscription;beforeAll(function(){var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,2);galleryWillEnter$Subscription=_subscribe$mock$calls[1];});it('should dispatch fetchProductImages when called',function(){var _galleryWillEnter$Sub=galleryWillEnter$Subscription,_galleryWillEnter$Sub2=_slicedToArray(_galleryWillEnter$Sub,2),stream=_galleryWillEnter$Sub2[0],callback=_galleryWillEnter$Sub2[1];expect(stream===galleryWillEnter$).toBe(true);var action={route:{params:{productId:'31333337'}}};callback({dispatch:dispatch,action:action});expect(fetchProductImages).toHaveBeenCalledWith('1337');});});describe('productRelationsReceived$',function(){var productRelationsReceived$Subscription;beforeAll(function(){var _subscribe$mock$calls2=_slicedToArray(subscribe.mock.calls,6);productRelationsReceived$Subscription=_subscribe$mock$calls2[5];});it('should dispatch fetchProductsById when called',function(){var _productRelationsRece=productRelationsReceived$Subscription,_productRelationsRece2=_slicedToArray(_productRelationsRece,2),stream=_productRelationsRece2[0],callback=_productRelationsRece2[1];expect(stream===productRelationsReceived$).toBe(true);var result=['productId'];var hash='hash';var action={hash:hash};getState.mockReturnValueOnce({product:{productRelationsByHash:_defineProperty({},hash,{productIds:result})}});callback({dispatch:dispatch,getState:getState,action:action});expect(mockedGetProductsById).toHaveBeenCalledWith(result);});});describe('visibleProductNotFound$ subscription',function(){var visibleProductNotFound$Subscription;var subscriptionThunk;beforeAll(function(){var _subscribe$mock$calls3=_slicedToArray(subscribe.mock.calls,5);visibleProductNotFound$Subscription=_subscribe$mock$calls3[4];var _visibleProductNotFou=visibleProductNotFound$Subscription;var _visibleProductNotFou2=_slicedToArray(_visibleProductNotFou,2);subscriptionThunk=_visibleProductNotFou2[1];});it('should show modal with product name',function(){subscriptionThunk([{dispatch:dispatch,action:errorProduct('SG100',ENOTFOUND)},{dispatch:dispatch,action:{productData:{id:'SG100',name:'SG100 name'}}}]);expect(showModal).toHaveBeenCalledWith({confirm:null,dismiss:'modal.ok',title:'modal.title_error',message:'product.no_more_found',params:{name:'SG100 name'}});expect(historyPop).toBeCalledTimes(1);expect(expireProductById).toHaveBeenCalledWith('SG100');});it('should show modal with product id',function(){subscriptionThunk([{dispatch:dispatch,action:errorProduct('SG100',ENOTFOUND)},{dispatch:dispatch,action:{productData:{id:'SG200',name:'SG200 name'}}}]);expect(showModal).toHaveBeenCalledWith({confirm:null,dismiss:'modal.ok',title:'modal.title_error',message:'product.no_more_found',params:{name:'SG100'}});});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}/* eslint-disable extra-rules/no-single-line-objects */import{SCANNER_SCOPE_DEFAULT}from'@shopgate/pwa-core/constants/Scanner';import successHandleScanner from"../action-creators/successHandleScanner";import handleBarCode from"./handleBarCode";import handleSearch from"./handleSearch";import handleNoResults from"./handleNoResults";jest.mock("./handleSearch");jest.mock("./handleNoResults");var scope=SCANNER_SCOPE_DEFAULT;var format='EAN_13';var payload='123456';describe('handleBarCode',function(){var dispatch=jest.fn(function(action){return action;});afterEach(function(){jest.clearAllMocks();});it('should use the product search',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var event;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:event={scope:scope,format:format,payload:payload};_context.next=3;return handleBarCode(event)(dispatch);case 3:expect(handleSearch).toHaveBeenCalledWith(payload);case 4:case"end":return _context.stop();}}},_callee);})));it("should trigger handling of no results when the search didn't find anything",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var event;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:event={scope:scope,format:format,payload:payload};handleSearch.mockResolvedValue(false);_context2.next=4;return handleBarCode(event)(dispatch);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.barCode'));case 5:case"end":return _context2.stop();}}},_callee2);})));it('should inform with a success event if the search handler did its job',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var event;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:event={scope:scope,format:format,payload:payload};handleSearch.mockResolvedValue(true);_context3.next=4;return handleBarCode(event)(dispatch);case 4:expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));case 5:case"end":return _context3.stop();}}},_callee3);})));});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}/* eslint-disable extra-rules/no-single-line-objects */import Scanner from'@shopgate/pwa-core/classes/Scanner';import{SCANNER_SCOPE_DEFAULT}from'@shopgate/pwa-core/constants/Scanner';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import errorHandleScanner from"../action-creators/errorHandleScanner";import handleNoResults from"./handleNoResults";jest.mock('@shopgate/pwa-core/classes/AppCommand');jest.mock('@shopgate/pwa-common/actions/router',function(){return{historyReplace:jest.fn()};});jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn().mockResolvedValue(true);});var scope=SCANNER_SCOPE_DEFAULT;var format='EAN_13';var payload='123456';describe('handleNoResults',function(){var dispatch=jest.fn(function(action){return action;});var scannerStart=jest.spyOn(Scanner,'start').mockImplementation(function(){});var modalContent={dismiss:null,confirm:'modal.ok',title:'modal.title_error',message:'test_message'};afterEach(function(){jest.clearAllMocks();});it('should show a modal with a predefined display message',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return handleNoResults({scope:scope,format:format,payload:payload},modalContent.message)(dispatch);case 2:expect(showModal).toHaveBeenCalledWith(modalContent);expect(scannerStart).toHaveBeenCalledTimes(1);case 4:case"end":return _context.stop();}}},_callee);})));it('should inform listeners that an error occurred',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return handleNoResults({scope:scope,format:format,payload:payload},modalContent.message)(dispatch);case 2:expect(dispatch).toHaveBeenCalledWith(errorHandleScanner(scope,format,payload));case 3:case"end":return _context2.stop();}}},_callee2);})));it('should start the Scanner again',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return handleNoResults({scope:scope,format:format,payload:payload},modalContent.message)(dispatch);case 2:expect(scannerStart).toHaveBeenCalledTimes(1);case 3:case"end":return _context3.stop();}}},_callee3);})));});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}/* eslint-disable extra-rules/no-single-line-objects */import{SCANNER_SCOPE_DEFAULT}from'@shopgate/pwa-core/constants/Scanner';import{historyReplace,historyPop}from'@shopgate/pwa-common/actions/router';import{fetchPageConfig}from'@shopgate/pwa-common/actions/page';import{getPageConfigById}from'@shopgate/pwa-common/selectors/page';import{fetchProductsById,getProductById}from'@shopgate/pwa-common-commerce/product';import{fetchCategory,getCategory}from'@shopgate/pwa-common-commerce/category';import{QR_CODE_TYPE_HOMEPAGE,QR_CODE_TYPE_PRODUCT,QR_CODE_TYPE_COUPON,QR_CODE_TYPE_CATEGORY,QR_CODE_TYPE_SEARCH,QR_CODE_TYPE_PAGE}from"../constants";import successHandleScanner from"../action-creators/successHandleScanner";import{parse2dsQrCode}from"../helpers";import handleQrCode from"./handleQrCode";import handleSearch from"./handleSearch";import handleNoResults from"./handleNoResults";jest.mock('@shopgate/pwa-common/actions/router',function(){return{historyReplace:jest.fn(),historyPop:jest.fn()};});jest.mock('@shopgate/pwa-common/actions/page',function(){return{fetchPageConfig:jest.fn().mockResolvedValue(null)};});jest.mock('@shopgate/pwa-common/selectors/page',function(){return{getPageConfigById:jest.fn()};});jest.mock('@shopgate/pwa-common-commerce/product',function(){return{fetchProductsById:jest.fn().mockResolvedValue(null),getProductById:jest.fn()};});jest.mock('@shopgate/pwa-common-commerce/category',function(){return{fetchCategory:jest.fn().mockResolvedValue(null),getCategory:jest.fn()};});jest.mock("../helpers",function(){return{parse2dsQrCode:jest.fn()};});jest.mock("./handleSearch");jest.mock("./handleNoResults");var scope=SCANNER_SCOPE_DEFAULT;var format='QR_CODE';var payload='qr.code.from.scanner';describe('handleQrCode',function(){var dispatch=jest.fn(function(action){return action;});var getState=jest.fn();afterEach(function(){jest.clearAllMocks();});it('parse2dsQrCode is called with given qr code',function(){handleQrCode({scope:scope,format:format,payload:payload})(dispatch);expect(parse2dsQrCode).toHaveBeenCalledWith(payload);});describe('unknown link handling',function(){it('should trigger "no result" handling when type is undefined',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var event;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:parse2dsQrCode.mockReturnValue(null);event={scope:scope,format:format,payload:payload};_context.next=4;return handleQrCode(event)(dispatch);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 5:case"end":return _context.stop();}}},_callee);})));it('should trigger "no result" handling when type is unknown',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var event;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:parse2dsQrCode.mockReturnValue({type:'unknown'});event={scope:scope,format:format,payload:payload};_context2.next=4;return handleQrCode(event)(dispatch);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 5:case"end":return _context2.stop();}}},_callee2);})));});describe('simple link handling',function(){it('should navigate to homepage',function(){parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_HOMEPAGE,link:'/'});handleQrCode({scope:scope,format:format,payload:payload})(dispatch);expect(historyReplace).toHaveBeenCalledWith({pathname:'/'});expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));});it('should pass the correct phrase to the search',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var data,event;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:data={searchPhrase:'Food'};parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_SEARCH,link:'/search?Food',data:data});event={scope:scope,format:format,payload:payload};_context3.next=5;return handleQrCode(event)(dispatch,getState);case 5:expect(dispatch).toHaveBeenCalledWith(handleSearch(data.searchPhrase));case 6:case"end":return _context3.stop();}}},_callee3);})));it('should perform a search and handle it accordingly when something was found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var data,event;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:data={searchPhrase:'Food'};parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_SEARCH,link:'/search?Food',data:data});handleSearch.mockResolvedValue(true);event={scope:scope,format:format,payload:payload};_context4.next=6;return handleQrCode(event)(dispatch,getState);case 6:expect(dispatch).toHaveBeenCalledWith(handleSearch(data.searchPhrase));expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));case 8:case"end":return _context4.stop();}}},_callee4);})));it('should trigger "no result" handling if the search would not find any products',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var data,event;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:data={searchPhrase:'FoodWithExtra'};parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_SEARCH,link:'/search?FoodWithExtra',data:data});handleSearch.mockResolvedValue(false);event={scope:scope,format:format,payload:payload};_context5.next=6;return handleQrCode(event)(dispatch,getState);case 6:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 7:case"end":return _context5.stop();}}},_callee5);})));it('should navigate to add coupon page',function(){parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_COUPON,link:'/add_coupon/code'});handleQrCode({scope:scope,format:format,payload:payload})(dispatch);expect(historyReplace).toHaveBeenCalledWith({pathname:'/add_coupon/code'});expect(historyPop).toHaveBeenCalledWith();expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));});});describe('PDP handling',function(){beforeEach(function(){parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_PRODUCT,link:'/item/SG1',data:{productId:'SG1'}});});it('fetch product and getState is called with productId',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 2:expect(fetchProductsById).toHaveBeenCalledWith(['SG1']);expect(getState).toHaveBeenCalledTimes(1);case 4:case"end":return _context6.stop();}}},_callee6);})));it('should trigger "no result" handling when the product is not found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var event;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:getProductById.mockReturnValue(null);event={scope:scope,format:format,payload:payload};_context7.next=4;return handleQrCode(event)(dispatch,getState);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 5:case"end":return _context7.stop();}}},_callee7);})));it('should navigate to PDP when product exists',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:getProductById.mockReturnValue(true);_context8.next=3;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 3:expect(historyReplace).toHaveBeenCalledWith({pathname:'/item/SG1'});expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));case 5:case"end":return _context8.stop();}}},_callee8);})));});describe('PLP handling',function(){beforeEach(function(){parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_CATEGORY,link:'/category/SG2',data:{categoryId:'SG2'}});});it('fetch category and getState is called with categoryId',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:_context9.next=2;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 2:expect(fetchCategory).toHaveBeenCalledWith('SG2');expect(getState).toHaveBeenCalledTimes(1);case 4:case"end":return _context9.stop();}}},_callee9);})));it('should trigger "no result" handling when the category is not found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var event;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:getCategory.mockReturnValue(null);event={scope:scope,format:format,payload:payload};_context10.next=4;return handleQrCode(event)(dispatch,getState);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 5:case"end":return _context10.stop();}}},_callee10);})));it('should navigate to PLP when category exists',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:getCategory.mockReturnValue(true);_context11.next=3;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 3:expect(historyReplace).toHaveBeenCalledWith({pathname:'/category/SG2'});expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));case 5:case"end":return _context11.stop();}}},_callee11);})));});describe('CMS handling',function(){beforeEach(function(){parse2dsQrCode.mockReturnValue({type:QR_CODE_TYPE_PAGE,link:'/page/SG3',data:{pageId:'SG3'}});});it('fetch page and getState is called with pageId',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(){return _regeneratorRuntime.wrap(function _callee12$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:_context12.next=2;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 2:expect(fetchPageConfig).toHaveBeenCalledWith('SG3');expect(getState).toHaveBeenCalledTimes(1);case 4:case"end":return _context12.stop();}}},_callee12);})));it('should trigger "no result" handling when no page not found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(){var event;return _regeneratorRuntime.wrap(function _callee13$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:getPageConfigById.mockReturnValue(null);event={scope:scope,format:format,payload:payload};_context13.next=4;return handleQrCode(event)(dispatch,getState);case 4:expect(dispatch).toHaveBeenCalledWith(handleNoResults(event,'scanner.noResult.qrCode'));case 5:case"end":return _context13.stop();}}},_callee13);})));it('should navigate to CMS when page exists',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(){return _regeneratorRuntime.wrap(function _callee14$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:getPageConfigById.mockReturnValue(true);_context14.next=3;return handleQrCode({scope:scope,format:format,payload:payload})(dispatch,getState);case 3:expect(historyReplace).toHaveBeenCalledWith({pathname:'/page/SG3'});expect(dispatch).toHaveBeenCalledWith(successHandleScanner(scope,format,payload));case 5:case"end":return _context14.stop();}}},_callee14);})));});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{historyReplace}from'@shopgate/pwa-common/actions/router';import fetchProductsByQuery from'@shopgate/pwa-common-commerce/product/actions/fetchProductsByQuery';import{getProductRoute}from'@shopgate/pwa-common-commerce/product/helpers';import{getSearchRoute}from'@shopgate/pwa-common-commerce/search/helpers';import handleSearch from"./handleSearch";jest.mock('@shopgate/pwa-common/actions/router',function(){return{historyReplace:jest.fn()};});jest.mock('@shopgate/pwa-common-commerce/product/actions/fetchProductsByQuery');var searchPhrase='Food';describe('handleSearch',function(){var dispatch=jest.fn(function(action){return action;});afterEach(function(){jest.clearAllMocks();});it('should just return false when nothing was found, without performing any actions',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:fetchProductsByQuery.mockResolvedValue({products:[]});_context.t0=expect;_context.next=4;return handleSearch(searchPhrase)(dispatch);case 4:_context.t1=_context.sent;(0,_context.t0)(_context.t1).toBeFalsy();case 6:case"end":return _context.stop();}}},_callee);})));it('should return true when the search handler performed any actions',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:fetchProductsByQuery.mockResolvedValue({products:['1']});_context2.t0=expect;_context2.next=4;return handleSearch(searchPhrase)(dispatch);case 4:_context2.t1=_context2.sent;(0,_context2.t0)(_context2.t1).toBeTruthy();case 6:case"end":return _context2.stop();}}},_callee2);})));it('should navigate to PDP when exactly one product was found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:fetchProductsByQuery.mockResolvedValue({products:[{id:searchPhrase}]});_context3.next=3;return handleSearch(searchPhrase)(dispatch);case 3:expect(fetchProductsByQuery).toHaveBeenCalledWith(2,searchPhrase);expect(historyReplace).toHaveBeenCalledWith({pathname:getProductRoute(searchPhrase)});case 5:case"end":return _context3.stop();}}},_callee3);})));it('should navigate to PDP when exactly one hashed product is found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:fetchProductsByQuery.mockResolvedValue({products:[searchPhrase]});_context4.next=3;return handleSearch(searchPhrase)(dispatch);case 3:expect(fetchProductsByQuery).toHaveBeenCalledWith(2,searchPhrase);expect(historyReplace).toHaveBeenCalledWith({pathname:getProductRoute(searchPhrase)});case 5:case"end":return _context4.stop();}}},_callee4);})));it('should navigate to the search page when multiple products have been found',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:fetchProductsByQuery.mockReturnValue(Promise.resolve({products:['111','222']}));_context5.next=3;return handleSearch(searchPhrase)(dispatch);case 3:expect(fetchProductsByQuery).toHaveBeenCalledWith(2,searchPhrase);expect(historyReplace).toHaveBeenCalledWith({pathname:getSearchRoute(searchPhrase)});case 5:case"end":return _context5.stop();}}},_callee5);})));});
@@ -1 +0,0 @@
1
- /* eslint-disable extra-rules/no-single-line-objects */import{SCANNER_SCOPE_DEFAULT,SCANNER_TYPE_BARCODE,SCANNER_TYPE_IMAGE}from'@shopgate/pwa-core/constants/Scanner';import{getSearchRoute}from'@shopgate/pwa-common-commerce/search';import{getCategoryRoute}from'@shopgate/pwa-common-commerce/category';import{getProductRoute}from'@shopgate/pwa-common-commerce/product';import{QR_CODE_TYPE_HOMEPAGE,QR_CODE_TYPE_PRODUCT,QR_CODE_TYPE_PRODUCT_WITH_COUPON,QR_CODE_TYPE_COUPON,QR_CODE_TYPE_CATEGORY,QR_CODE_TYPE_SEARCH,QR_CODE_TYPE_PAGE,QR_CODE_HOST_2DS,SCANNER_PATH}from"../constants";import{is2dsQrCode,parse2dsQrCode,getScannerRoute}from"./index";describe('scanner helpers',function(){describe('is2dsQrCode',function(){it('should return true when link is 2ds',function(){expect(is2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/uri"))).toBe(true);});it('should return false when link is not 2ds',function(){expect(is2dsQrCode('http://site.com/uri')).toBe(false);});});describe('parse2dsQrCode',function(){describe('invalid 2ds link',function(){it('should return NULL when an invalid link was passed',function(){expect(parse2dsQrCode('some string')).toBeNull();});it('should return NULL when url is not 2ds',function(){expect(parse2dsQrCode('http://site.com/uri')).toBeNull();});});describe('valid 2ds link',function(){it('should parse a homepage link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/5/30186?s=30"));expect(result).toEqual({link:'/',type:QR_CODE_TYPE_HOMEPAGE,data:{}});});it('should parse a PDP link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/7/30186/345%252F34%2523?s=25"));expect(result).toEqual({link:getProductRoute('345/34#'),type:QR_CODE_TYPE_PRODUCT,data:{productId:'345/34#'}});});it('should parse add product with coupon link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/9/30186/345%252F34%2523/TEST%252FCODE%2523?s=26"));expect(result).toEqual({link:'/cart_add_product/345%2F34%23/TEST%2FCODE%23',type:QR_CODE_TYPE_PRODUCT_WITH_COUPON,data:{productId:'345/34#',couponCode:'TEST/CODE#'}});});it('should parse a coupon link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/2/TEST-CODE/23729?s=27"));expect(result).toEqual({link:'/cart_add_coupon/TEST-CODE',type:QR_CODE_TYPE_COUPON,data:{couponCode:'TEST-CODE'}});});it('should parse a PLP link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/e/30186/1337?s=28"));expect(result).toEqual({link:getCategoryRoute('1337'),type:QR_CODE_TYPE_CATEGORY,data:{categoryId:'1337'}});});it('should parse a search link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/b/30186/N%25C3%25A4hk%25C3%25A4stchen%2520Schl%25C3%25BCssel?s=29"));expect(result).toEqual({link:getSearchRoute('Nähkästchen Schlüssel'),type:QR_CODE_TYPE_SEARCH,data:{searchPhrase:'Nähkästchen Schlüssel'}});});it('should parse a CMS page link',function(){var result=parse2dsQrCode("http://".concat(QR_CODE_HOST_2DS,"/1/30186/cms-page?s=31"));expect(result).toEqual({link:'/page/cms-page',type:QR_CODE_TYPE_PAGE,data:{pageId:'cms-page'}});});});});describe('getScannerRoute',function(){it('should create a route without passing parameters',function(){var route=getScannerRoute();var expected="".concat(SCANNER_PATH,"?scope=").concat(SCANNER_SCOPE_DEFAULT,"&type=").concat(SCANNER_TYPE_BARCODE);expect(route).toBe(expected);});it('should create a route when a value is passed for the scope parameter',function(){var route=getScannerRoute('custom');var expected="".concat(SCANNER_PATH,"?scope=custom&type=").concat(SCANNER_TYPE_BARCODE);expect(route).toBe(expected);});it('should create a route when a values are passed for both parameters',function(){var route=getScannerRoute('custom',SCANNER_TYPE_IMAGE);var expected="".concat(SCANNER_PATH,"?scope=custom&type=").concat(SCANNER_TYPE_IMAGE);expect(route).toBe(expected);});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- /* eslint-disable extra-rules/no-single-line-objects */import{mainSubject}from'@shopgate/pwa-common/store/middelwares/streams';import{ROUTE_DID_ENTER}from'@shopgate/pwa-common/constants/ActionTypes';import{scannerDidEnter$,startScanner$,scannerStarted$,scannerCancelled$,scannerFinished$,scannerFinishedBarCode$,scannerFinishedQrCode$}from"./index";import{START_SCANNER,SCANNER_CANCELLED,SCANNER_FINISHED,SCANNER_STARTED,SCANNER_PATH,SCANNER_FORMATS_BARCODE,SCANNER_FORMATS_QR_CODE}from"../constants";describe('scanner streams',function(){var subscriber;beforeEach(function(){subscriber=jest.fn();});it('should call subscriber when the scanner page was opened',function(){scannerDidEnter$.subscribe(subscriber);mainSubject.next({action:{type:ROUTE_DID_ENTER,route:{pathname:SCANNER_PATH}}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscriber on start scanner event',function(){startScanner$.subscribe(subscriber);mainSubject.next({action:{type:START_SCANNER}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscriber on scanner start event',function(){scannerStarted$.subscribe(subscriber);mainSubject.next({action:{type:SCANNER_STARTED}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscriber on scanner cancelled event',function(){scannerCancelled$.subscribe(subscriber);mainSubject.next({action:{type:SCANNER_CANCELLED}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscriber on scanner finished event',function(){scannerFinished$.subscribe(subscriber);mainSubject.next({action:{type:SCANNER_FINISHED}});expect(subscriber).toHaveBeenCalledTimes(1);});it('should call subscriber on bar code finished event',function(){scannerFinished$.subscribe(subscriber);scannerFinishedBarCode$.subscribe(subscriber);mainSubject.next({action:{type:SCANNER_FINISHED,format:SCANNER_FORMATS_BARCODE[0]}});expect(subscriber).toHaveBeenCalledTimes(2);});it('should call subscriber on qr code finished event',function(){scannerFinished$.subscribe(subscriber);scannerFinishedQrCode$.subscribe(subscriber);mainSubject.next({action:{type:SCANNER_FINISHED,format:SCANNER_FORMATS_QR_CODE[0]}});expect(subscriber).toHaveBeenCalledTimes(2);});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1,7 +0,0 @@
1
- import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _slicedToArray(arr,i){return _arrayWithHoles(arr)||_iterableToArrayLimit(arr,i)||_unsupportedIterableToArray(arr,i)||_nonIterableRest();}function _nonIterableRest(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.");}function _unsupportedIterableToArray(o,minLen){if(!o)return;if(typeof o==="string")return _arrayLikeToArray(o,minLen);var n=Object.prototype.toString.call(o).slice(8,-1);if(n==="Object"&&o.constructor)n=o.constructor.name;if(n==="Map"||n==="Set")return Array.from(o);if(n==="Arguments"||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n))return _arrayLikeToArray(o,minLen);}function _arrayLikeToArray(arr,len){if(len==null||len>arr.length)len=arr.length;for(var i=0,arr2=new Array(len);i<len;i++){arr2[i]=arr[i];}return arr2;}function _iterableToArrayLimit(arr,i){var _i=arr==null?null:typeof Symbol!=="undefined"&&arr[Symbol.iterator]||arr["@@iterator"];if(_i==null)return;var _arr=[];var _n=true;var _d=false;var _s,_e;try{for(_i=_i.call(arr);!(_n=(_s=_i.next()).done);_n=true){_arr.push(_s.value);if(i&&_arr.length===i)break;}}catch(err){_d=true;_e=err;}finally{try{if(!_n&&_i["return"]!=null)_i["return"]();}finally{if(_d)throw _e;}}return _arr;}function _arrayWithHoles(arr){if(Array.isArray(arr))return arr;}/* eslint-disable extra-rules/no-single-line-objects */import Scanner from'@shopgate/pwa-core/classes/Scanner';import ScannerEvent from'@shopgate/pwa-core/classes/ScannerEvent';import{SCANNER_SCOPE_DEFAULT,SCANNER_TYPE_BARCODE}from'@shopgate/pwa-core/constants/Scanner';import{appDidStart$}from'@shopgate/pwa-common/streams';import scannerFinished from"../action-creators/scannerFinished";import handleBarCode from"../actions/handleBarCode";import handleQrCode from"../actions/handleQrCode";import{startScanner$}from"../streams";import subscriptions,{handledFormats}from"./index";jest.mock('@shopgate/pwa-core/classes/Scanner',function(){return{addListener:jest.fn(),start:jest.fn()};});jest.mock('@shopgate/pwa-common/streams/app',function(){return{appDidStart$:jest.fn()};});jest.mock("../action-creators/scannerFinished",function(){return jest.fn();});jest.mock("../actions/handleBarCode");jest.mock("../actions/handleQrCode");describe('scanner subscriptions',function(){var subscribe=jest.fn();var dispatch=jest.fn();/**
2
- * @param {string} [format='EAN_13'] The event format.
3
- * @returns {ScannerEvent}
4
- */var createMockedEvent=function createMockedEvent(){var format=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'EAN_13';return new ScannerEvent(SCANNER_SCOPE_DEFAULT,SCANNER_TYPE_BARCODE,{format:format,code:'0000000000000'});};var appDidStartStream$;var appDidStartCallback;var startScannerStream$;var startScannerCallback;// eslint-disable-next-line no-unused-vars
5
- var scanFinishedBarCodeStream$;var scanFinishedBarCodeCallback;// eslint-disable-next-line no-unused-vars
6
- var scanFinishedQrCodeStream$;var scanFinishedQrCodeCallback;afterEach(function(){jest.clearAllMocks();});beforeEach(function(){subscriptions(subscribe);var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,4);var _subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);appDidStartStream$=_subscribe$mock$calls2[0];appDidStartCallback=_subscribe$mock$calls2[1];var _subscribe$mock$calls3=_slicedToArray(_subscribe$mock$calls[1],2);startScannerStream$=_subscribe$mock$calls3[0];startScannerCallback=_subscribe$mock$calls3[1];var _subscribe$mock$calls4=_slicedToArray(_subscribe$mock$calls[2],2);scanFinishedBarCodeStream$=_subscribe$mock$calls4[0];scanFinishedBarCodeCallback=_subscribe$mock$calls4[1];var _subscribe$mock$calls5=_slicedToArray(_subscribe$mock$calls[3],2);scanFinishedQrCodeStream$=_subscribe$mock$calls5[0];scanFinishedQrCodeCallback=_subscribe$mock$calls5[1];});it('should init 4 subscriptions',function(){expect(subscribe).toHaveBeenCalledTimes(4);});describe('appDidStart subscription',function(){it('should init appDidStart subscription',function(){expect(appDidStartStream$).toEqual(appDidStart$);expect(appDidStartCallback).toBeInstanceOf(Function);});it('should dispatch mapped ScannerEvent action',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var _Scanner$addListener$,_Scanner$addListener$2,listenerActual;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:appDidStartCallback({dispatch:dispatch});expect(Scanner.addListener).toHaveBeenCalledTimes(1);_Scanner$addListener$=_slicedToArray(Scanner.addListener.mock.calls,1),_Scanner$addListener$2=_slicedToArray(_Scanner$addListener$[0],1),listenerActual=_Scanner$addListener$2[0];expect(listenerActual.handler).toBeInstanceOf(Function);_context.next=6;return listenerActual.notify(createMockedEvent());case 6:// Expect event to be mapped to stream
7
- expect(scannerFinished).toBeCalledWith(SCANNER_SCOPE_DEFAULT,'EAN_13','0000000000000');case 7:case"end":return _context.stop();}}},_callee);})));it('should dispatch mapped ScannerEvent action for every supported format',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var _Scanner$addListener$3,_Scanner$addListener$4,listenerActual,events;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:appDidStartCallback({dispatch:dispatch});_Scanner$addListener$3=_slicedToArray(Scanner.addListener.mock.calls,1),_Scanner$addListener$4=_slicedToArray(_Scanner$addListener$3[0],1),listenerActual=_Scanner$addListener$4[0];events=handledFormats.map(function(format){return listenerActual.handler(createMockedEvent(format));});_context2.next=5;return Promise.all(events);case 5:expect(scannerFinished).toHaveBeenCalledTimes(handledFormats.length);case 6:case"end":return _context2.stop();}}},_callee2);})));it('should not dispatch mapped ScannerEvent action for an unsupported format',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var _Scanner$addListener$5,_Scanner$addListener$6,listenerActual;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:appDidStartCallback({dispatch:dispatch});_Scanner$addListener$5=_slicedToArray(Scanner.addListener.mock.calls,1),_Scanner$addListener$6=_slicedToArray(_Scanner$addListener$5[0],1),listenerActual=_Scanner$addListener$6[0];_context3.next=4;return listenerActual.notify(createMockedEvent('unknown'));case 4:expect(scannerFinished).not.toHaveBeenCalled();case 5:case"end":return _context3.stop();}}},_callee3);})));});describe('scannerStart subscription',function(){it('should init scannerStart subscription',function(){expect(startScannerStream$).toEqual(startScanner$);expect(startScannerCallback).toBeInstanceOf(Function);});it('should call the start method of the scanner instance',function(){startScannerCallback();expect(Scanner.start).toHaveBeenCalledTimes(1);});});describe('scanFinishedBarCode subscription',function(){it('should init scanFinishedBarCode subscription',function(){expect(scanFinishedBarCodeCallback).toBeInstanceOf(Function);});it('should call bar code handler with bar code payload',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var scope,format,payload;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:scope=SCANNER_SCOPE_DEFAULT;format='EAN_13';payload='123456';scanFinishedBarCodeCallback({dispatch:dispatch,action:{scope:scope,format:format,payload:payload}});expect(handleBarCode).toHaveBeenCalledTimes(1);expect(handleBarCode).toHaveBeenCalledWith({scope:scope,format:format,payload:payload});case 6:case"end":return _context4.stop();}}},_callee4);})));});describe('scanFinishedQrCode subscription',function(){it('should init scanFinishedQrCode subscription',function(){expect(scanFinishedQrCodeCallback).toBeInstanceOf(Function);});it('should call qr code handler with qr code payload',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var scope,format,payload;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:scope=SCANNER_SCOPE_DEFAULT;format='QR_CODE';payload='https://2d.is/7/30289';scanFinishedQrCodeCallback({dispatch:dispatch,action:{scope:scope,format:format,payload:payload}});expect(handleQrCode).toHaveBeenCalledTimes(1);expect(handleQrCode).toHaveBeenCalledWith({scope:scope,format:format,payload:payload});case 6:case"end":return _context5.stop();}}},_callee5);})));});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1 +0,0 @@
1
- import{getSuggestionsState,getSuggestions,getSuggestionsFetchingState}from"./index";var mockedState={search:{suggestions:{notfetching:{isFetching:false,suggestions:['Entry One','Entry Two']},fetching:{isFetching:true,suggestions:[]}}}};describe('Search selectors',function(){var suggestions=mockedState.search.suggestions;describe('getSuggestionsState()',function(){it('should return the state',function(){expect(getSuggestionsState(mockedState)).toEqual(suggestions);});});describe('getSuggestions()',function(){it('should return suggestions',function(){var searchPhrase='notfetching';var result=getSuggestions(mockedState,{searchPhrase:searchPhrase});expect(result).toEqual(suggestions[searchPhrase].suggestions);});it('should return null if an empty search phrase was passed',function(){var searchPhrase='';var result=getSuggestions(mockedState,{searchPhrase:searchPhrase});expect(result).toBeNull();});it('should return null if the store does not contain an entry for the passed search phrase',function(){var searchPhrase='somephrase';var result=getSuggestions(mockedState,{searchPhrase:searchPhrase});expect(result).toBeNull();});it('should return an empty array if the suggestions for the passed search phrase are empty ',function(){var searchPhrase='fetching';var result=getSuggestions(mockedState,{searchPhrase:searchPhrase});expect(result).toEqual([]);});});describe('getSuggestionsFetchingState()',function(){it('should return true for fetching suggestions',function(){var searchPhrase='fetching';var result=getSuggestionsFetchingState(mockedState,{searchPhrase:searchPhrase});expect(result).toBeTruthy();});it('should return false when the related store entry is not fetching',function(){var searchPhrase='notfetching';var result=getSuggestionsFetchingState(mockedState,{searchPhrase:searchPhrase});expect(result).toBeFalsy();});it('should return false if an empty search phrase was passed',function(){var searchPhrase='';var result=getSuggestionsFetchingState(mockedState,{searchPhrase:searchPhrase});expect(result).toBeFalsy();});it('should return false if the store does not contain an entry for the passed search phrase',function(){var searchPhrase='somephrase';var result=getSuggestionsFetchingState(mockedState,{searchPhrase:searchPhrase});expect(result).toBeFalsy();});});});