@shopgate/engage 6.21.0 → 6.22.0-beta.10

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 (184) hide show
  1. package/app-rating/action-creators/appStart.js +3 -3
  2. package/app-rating/action-creators/ordersPlaced.js +3 -3
  3. package/app-rating/action-creators/popup.js +4 -4
  4. package/app-rating/action-creators/timer.js +3 -3
  5. package/app-rating/actions/showModal.js +2 -2
  6. package/app-rating/constants/index.js +2 -2
  7. package/app-rating/reducers/index.js +2 -2
  8. package/app-rating/subscriptions/index.js +2 -2
  9. package/back-in-stock/actions/index.js +14 -0
  10. package/back-in-stock/components/BackInStockButton/connector.js +1 -0
  11. package/back-in-stock/components/BackInStockButton/index.js +13 -0
  12. package/back-in-stock/components/BackInStockButton/style.js +1 -0
  13. package/back-in-stock/components/CharacteristicsButton/connector.js +3 -0
  14. package/back-in-stock/components/CharacteristicsButton/index.js +8 -0
  15. package/back-in-stock/components/ProductInfoBackInStockButton/connector.js +3 -0
  16. package/back-in-stock/components/ProductInfoBackInStockButton/index.js +10 -0
  17. package/back-in-stock/components/Subscriptions/components/List/index.js +4 -0
  18. package/back-in-stock/components/Subscriptions/components/Subscription/index.js +7 -0
  19. package/back-in-stock/components/Subscriptions/index.js +4 -0
  20. package/back-in-stock/components/index.js +1 -0
  21. package/back-in-stock/constants/Actions.js +1 -0
  22. package/back-in-stock/constants/Common.js +1 -0
  23. package/back-in-stock/constants/Pipelines.js +1 -0
  24. package/back-in-stock/constants/Portals.js +9 -0
  25. package/back-in-stock/constants/index.js +1 -0
  26. package/back-in-stock/hooks/index.js +4 -0
  27. package/back-in-stock/providers/BackInStockSubscriptionsProvider.connector.js +7 -0
  28. package/back-in-stock/providers/BackInStockSubscriptionsProvider.context.js +1 -0
  29. package/back-in-stock/providers/BackInStockSubscriptionsProvider.js +5 -0
  30. package/back-in-stock/providers/index.js +1 -0
  31. package/back-in-stock/reducers/index.js +5 -0
  32. package/back-in-stock/selectors/index.js +42 -0
  33. package/back-in-stock/streams/index.js +1 -0
  34. package/back-in-stock/subscriptions/index.js +11 -0
  35. package/components/index.js +1 -1
  36. package/core/action-creators/appPermissions.js +9 -0
  37. package/core/action-creators/index.js +1 -0
  38. package/core/actions/getGeolocation.js +1 -1
  39. package/core/actions/grantCameraPermissions.js +1 -1
  40. package/core/actions/grantGeolocationPermissions.js +1 -1
  41. package/core/actions/grantPermissions.js +11 -4
  42. package/core/actions/grantPushPermissions.js +22 -0
  43. package/core/actions/index.js +1 -0
  44. package/core/actions/requestAppPermission.js +7 -0
  45. package/core/actions/requestAppPermissionStatus.js +7 -0
  46. package/core/collections/AppInitialization.js +49 -0
  47. package/core/collections/index.js +1 -0
  48. package/core/constants/actionTypes.js +1 -0
  49. package/core/constants/appFeatures.js +1 -0
  50. package/core/constants/index.js +6 -0
  51. package/core/helpers/appFeatures.js +7 -0
  52. package/core/helpers/index.js +1 -0
  53. package/core/index.js +8 -12
  54. package/core/initialization/index.js +7 -0
  55. package/core/streams/appPermissions.js +19 -0
  56. package/core/streams/index.js +1 -0
  57. package/package.json +7 -7
  58. package/product/components/Characteristics/Characteristic/components/Sheet/index.js +2 -2
  59. package/product/components/Characteristics/Characteristic/components/SheetItem/index.js +3 -3
  60. package/product/components/Characteristics/Characteristic/components/SheetItem/style.js +1 -1
  61. package/product/index.js +1 -1
  62. package/product/selectors/product.js +5 -1
  63. package/product/selectors/variants.js +2 -2
  64. package/push-opt-in/action-creators/index.js +1 -0
  65. package/push-opt-in/action-creators/optInTrigger.js +23 -0
  66. package/push-opt-in/action-creators/pushOptIn.js +7 -0
  67. package/push-opt-in/actions/index.js +1 -0
  68. package/push-opt-in/actions/pushOptInModal.js +8 -0
  69. package/push-opt-in/components/PushOptInModal/connector.js +9 -0
  70. package/push-opt-in/components/PushOptInModal/index.js +10 -0
  71. package/push-opt-in/components/PushOptInModal/push-opt-in.svg +62 -0
  72. package/push-opt-in/components/PushOptInModal/style.js +1 -0
  73. package/push-opt-in/components/index.js +1 -0
  74. package/push-opt-in/constants/index.js +1 -0
  75. package/push-opt-in/constants/optInModal.js +1 -0
  76. package/push-opt-in/constants/optInTrigger.js +1 -0
  77. package/push-opt-in/reducers/index.js +1 -0
  78. package/push-opt-in/reducers/optInModal.js +6 -0
  79. package/push-opt-in/reducers/optInTrigger.js +6 -0
  80. package/push-opt-in/selectors/index.js +1 -0
  81. package/push-opt-in/selectors/optInModal.js +8 -0
  82. package/push-opt-in/selectors/optInTrigger.js +5 -0
  83. package/push-opt-in/subscriptions/index.js +1 -0
  84. package/push-opt-in/subscriptions/optInTrigger.js +12 -0
  85. package/a11y/components/LiveMessage/__tests__/index.spec.js +0 -1
  86. package/a11y/components/LiveMessenger/__tests__/helpers.spec.js +0 -1
  87. package/a11y/components/LiveMessenger/__tests__/index.spec.js +0 -1
  88. package/a11y/components/Navigation/__tests__/index.spec.js +0 -1
  89. package/a11y/components/Section/__tests__/index.spec.js +0 -1
  90. package/a11y/index.spec.js +0 -1
  91. package/cart/index.spec.js +0 -1
  92. package/category/index.spec.js +0 -1
  93. package/checkout/index.spec.js +0 -1
  94. package/components/Footer/__tests__/Footer.spec.js +0 -8
  95. package/components/Form/Builder/Builder.spec.js +0 -19
  96. package/components/Form/Builder/classes/ActionListener.spec.js +0 -21
  97. package/components/Form/Builder/helpers/buildCountryList.spec.js +0 -1
  98. package/components/Form/Builder/helpers/buildFormDefaults.spec.js +0 -1
  99. package/components/Form/Builder/helpers/buildFormElements.spec.js +0 -3
  100. package/components/Form/Builder/helpers/buildProvinceList.spec.js +0 -1
  101. package/components/IntersectionVisibility/__tests__/index.js +0 -1
  102. package/components/View/__mocks__/context.js +0 -1
  103. package/components/View/__mocks__/index.js +0 -5
  104. package/components/View/__tests__/index.spec.js +0 -1
  105. package/components/View/__tests__/provider.spec.js +0 -1
  106. package/components/View/components/Above/__tests__/index.spec.js +0 -1
  107. package/components/View/components/Below/__tests__/index.spec.js +0 -1
  108. package/components/View/components/Content/__tests__/index.spec.js +0 -2
  109. package/components/__mocks__/index.js +0 -4
  110. package/components/index.spec.js +0 -1
  111. package/core/actions/__tests__/getGeolocation.spec.js +0 -2
  112. package/core/actions/__tests__/grantCameraPermissions.spec.js +0 -1
  113. package/core/actions/__tests__/grantGeolocationPermissions.spec.js +0 -1
  114. package/core/actions/__tests__/grantPermissions.spec.js +0 -9
  115. package/core/actions/__tests__/updateStatusBarBackground.spec.js +0 -1
  116. package/core/classes/__tests__/GeolocationRequest.spec.js +0 -5
  117. package/core/config/__tests__/getPageConfig.spec.js +0 -1
  118. package/core/config/__tests__/getPageSettings.spec.js +0 -2
  119. package/core/config/__tests__/getThemeAssets.spec.js +0 -1
  120. package/core/config/__tests__/getThemeColors.spec.js +0 -1
  121. package/core/config/__tests__/getThemeConfig.spec.js +0 -2
  122. package/core/config/__tests__/getThemeSettings.spec.js +0 -1
  123. package/core/config/__tests__/getThemeStyles.spec.js +0 -1
  124. package/core/config/__tests__/getWidgetConfig.spec.js +0 -1
  125. package/core/config/__tests__/getWidgetSettings.spec.js +0 -3
  126. package/core/helpers/__mocks__/i18n.js +0 -1
  127. package/core/helpers/__tests__/i18n.spec.js +0 -1
  128. package/core/helpers/__tests__/updateLegacyNavigationBar.spec.js +0 -1
  129. package/core/hocs/__mocks__/withWidgetSettings.js +0 -5
  130. package/core/hocs/__tests__/withApp.spec.js +0 -2
  131. package/core/hocs/__tests__/withCurrentProduct.spec.js +0 -2
  132. package/core/hocs/__tests__/withForwardedRef.spec.js +0 -1
  133. package/core/hocs/__tests__/withNavigation.spec.js +0 -2
  134. package/core/hocs/__tests__/withRoute.spec.js +0 -2
  135. package/core/hocs/__tests__/withTheme.spec.js +0 -2
  136. package/core/hocs/__tests__/withWidgetSettings.spec.js +0 -2
  137. package/core/hocs/__tests__/withWidgetStyles.spec.js +0 -2
  138. package/core/hooks/__tests__/useApp.spec.js +0 -1
  139. package/core/hooks/__tests__/useNavigation.spec.js +0 -1
  140. package/core/hooks/__tests__/usePageConfig.spec.js +0 -1
  141. package/core/hooks/__tests__/usePageSettings.spec.js +0 -1
  142. package/core/hooks/__tests__/useTheme.spec.js +0 -1
  143. package/core/hooks/__tests__/useWidgetConfig.spec.js +0 -1
  144. package/core/hooks/__tests__/useWidgetSettings.spec.js +0 -1
  145. package/core/hooks/__tests__/useWidgetStyles.spec.js +0 -1
  146. package/core/index.spec.js +0 -1
  147. package/core/providers/__tests__/AppProvider.spec.js +0 -2
  148. package/core/router/__tests__/helpers.spec.js +0 -1
  149. package/favorites/index.spec.js +0 -1
  150. package/filter/helpers/__tests__/buildUpdatedFilters.spec.js +0 -1
  151. package/filter/index.spec.js +0 -1
  152. package/index.spec.js +0 -1
  153. package/market/index.spec.js +0 -1
  154. package/orders/index.spec.js +0 -1
  155. package/page/index.spec.js +0 -1
  156. package/product/components/Description/__tests__/Description.spec.js +0 -1
  157. package/product/components/Media/helpers.spec.js +0 -3
  158. package/product/components/ProductCharacteristics/helpers/index.spec.js +0 -12
  159. package/product/components/ProductGridPrice/index.spec.js +0 -1
  160. package/product/components/ProductProperties/__tests__/Content.spec.js +0 -1
  161. package/product/components/ProductProperties/__tests__/Group.spec.js +0 -1
  162. package/product/components/ProductProperties/__tests__/GroupedProperties.spec.js +0 -1
  163. package/product/components/ProductProperties/__tests__/Lists.spec.js +0 -1
  164. package/product/components/ProductProperties/__tests__/ProductProperties.spec.js +0 -1
  165. package/product/components/ProductProperties/__tests__/Row.spec.js +0 -1
  166. package/product/components/ProductProperties/__tests__/Rows.spec.js +0 -1
  167. package/product/components/ProductProperties/__tests__/helpers/getGroupsFromProperties.spec.js +0 -1
  168. package/product/components/ProductProperties/__tests__/helpers/getSubgroupsFromProperties.spec.js +0 -1
  169. package/product/components/QuantityPicker/helpers.spec.js +0 -1
  170. package/product/components/__mocks__/context.js +0 -1
  171. package/product/hocs/withMapPricing.spec.js +0 -4
  172. package/product/hocs/withPriceCalculation.spec.js +0 -1
  173. package/product/index.spec.js +0 -1
  174. package/product/selectors/__tests__/media.spec.js +0 -1
  175. package/product/selectors/__tests__/price.spec.js +0 -1
  176. package/product/selectors/__tests__/product.spec.js +0 -2
  177. package/product/selectors/__tests__/relations.spec.js +0 -1
  178. package/product/selectors/__tests__/variants.spec.js +0 -1
  179. package/product/selectors/mocks/productProperties.mock.js +0 -1
  180. package/reviews/index.spec.js +0 -1
  181. package/scanner/index.spec.js +0 -1
  182. package/search/index.spec.js +0 -1
  183. package/user/index.spec.js +0 -1
  184. package/user/selectors/__tests__/login.spec.js +0 -1
@@ -0,0 +1 @@
1
+ export*from"./optInTrigger";export*from"./optInModal";
@@ -0,0 +1 @@
1
+ export var SHOW_PUSH_OPT_IN_MODAL='SHOW_PUSH_OPT_IN_MODAL';export var HIDE_PUSH_OPT_IN_MODAL='HIDE_PUSH_OPT_IN_MODAL';
@@ -0,0 +1 @@
1
+ export var PUSH_OPT_IN_INCREASE_APP_START_COUNT='PUSH_OPT_IN_INCREASE_APP_START_COUNT';export var PUSH_OPT_IN_RESET_APP_START_COUNT='PUSH_OPT_IN_RESET_APP_START_COUNT';export var PUSH_OPT_IN_RESET_APP_START_STATE='PUSH_OPT_IN_RESET_APP_START_STATE';export var PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT='PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT';export var PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT='PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT';export var PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE='PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE';export var PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP='PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP';export var PUSH_OPT_IN_INCREASE_REJECTION_COUNT='PUSH_OPT_IN_INCREASE_REJECTION_COUNT';export var PUSH_OPT_IN_OPT_IN_POSTPONED='PUSH_OPT_IN_OPT_IN_POSTPONED';
@@ -0,0 +1 @@
1
+ import{combineReducers}from'redux';import optInTrigger from"./optInTrigger";import optInModal from"./optInModal";export default combineReducers({optInTrigger:optInTrigger,optInModal:optInModal});
@@ -0,0 +1,6 @@
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);}import{HIDE_PUSH_OPT_IN_MODAL,SHOW_PUSH_OPT_IN_MODAL}from"../constants";var defaultState={isPushOptInModalVisible:false};/**
2
+ * Stores all the states related to the push Opt-In Modal functionality.
3
+ * @param {Object} [state] The current state.
4
+ * @param {Object} action The action object.
5
+ * @return {Object} The new state.
6
+ */var pushOptInModalReducer=function pushOptInModalReducer(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultState;var action=arguments.length>1?arguments[1]:undefined;switch(action.type){case SHOW_PUSH_OPT_IN_MODAL:{return _extends({},state,{isPushOptInModalVisible:true});}case HIDE_PUSH_OPT_IN_MODAL:{return _extends({},state,{isPushOptInModalVisible:false});}default:return state;}};export default pushOptInModalReducer;
@@ -0,0 +1,6 @@
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);}import{PUSH_OPT_IN_INCREASE_APP_START_COUNT,PUSH_OPT_IN_RESET_APP_START_STATE,PUSH_OPT_IN_RESET_APP_START_COUNT,PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT,PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT,PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE,PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP,PUSH_OPT_IN_INCREASE_REJECTION_COUNT}from"../constants";var defaultState={appStartCount:0,appStartResetCount:0,ordersPlacedCount:0,ordersPlacedResetCount:0,lastPopupAt:null,rejectionCount:0};/**
2
+ * Stores all the states related to the pushOptInTrigger functionality.
3
+ * @param {Object} [state] The current state.
4
+ * @param {Object} action The action object.
5
+ * @return {Object} The new state.
6
+ */var pushOptInReducer=function pushOptInReducer(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultState;var action=arguments.length>1?arguments[1]:undefined;switch(action.type){case PUSH_OPT_IN_INCREASE_APP_START_COUNT:{return _extends({},state,{appStartCount:state.appStartCount+1});}case PUSH_OPT_IN_RESET_APP_START_COUNT:{return _extends({},state,{appStartCount:0,appStartResetCount:state.appStartResetCount+1});}case PUSH_OPT_IN_RESET_APP_START_STATE:{return _extends({},state,{appStartCount:0,appStartResetCount:0});}case PUSH_OPT_IN_INCREASE_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:state.ordersPlacedCount+1});}case PUSH_OPT_IN_RESET_ORDERS_PLACED_COUNT:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:state.ordersPlacedResetCount+1});}case PUSH_OPT_IN_RESET_ORDERS_PLACED_STATE:{return _extends({},state,{ordersPlacedCount:0,ordersPlacedResetCount:0});}case PUSH_OPT_IN_SET_LAST_POPUP_TIMESTAMP:{return _extends({},state,{lastPopupAt:Date.now()});}case PUSH_OPT_IN_INCREASE_REJECTION_COUNT:{return _extends({},state,{rejectionCount:state.rejectionCount+1});}default:return state;}};export default pushOptInReducer;
@@ -0,0 +1 @@
1
+ export*from"./optInTrigger";export*from"./optInModal";
@@ -0,0 +1,8 @@
1
+ import{createSelector}from'reselect';/**
2
+ * Selects the push opt-in modal state.
3
+ * @param {Object} state The current state of the push opt-in modal.
4
+ * @returns {Object} whether push opt-in modal is shown.
5
+ */export var getPushOptInModalState=function getPushOptInModalState(state){var _state$pushOptIn;return(state===null||state===void 0?void 0:(_state$pushOptIn=state.pushOptIn)===null||_state$pushOptIn===void 0?void 0:_state$pushOptIn.optInModal)||{};};/**
6
+ * Selects the property of the push opt-in modal.
7
+ * @returns {boolean} whether push opt-in modal is shown.
8
+ */export var getIsPushOptInModalVisible=createSelector(getPushOptInModalState,function(modalState){return modalState.isPushOptInModalVisible||false;});
@@ -0,0 +1,5 @@
1
+ /**
2
+ * Selects the push opt in information.
3
+ * @param {Object} state The current state.
4
+ * @returns {Object} The push opt in information.
5
+ */export var getPushOptInTriggerState=function getPushOptInTriggerState(state){var _state$pushOptIn;return(state===null||state===void 0?void 0:(_state$pushOptIn=state.pushOptIn)===null||_state$pushOptIn===void 0?void 0:_state$pushOptIn.optInTrigger)||{};};
@@ -0,0 +1 @@
1
+ import optInTrigger from"./optInTrigger";export default(function(subscribe){optInTrigger(subscribe);});
@@ -0,0 +1,12 @@
1
+ import _regeneratorRuntime from"@babel/runtime/regenerator";function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}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{appConfig}from'@shopgate/engage';import{main$,event,appDidStart$,logger}from'@shopgate/engage/core';import{appSupportsPushOptIn}from'@shopgate/engage/core/helpers';import{PERMISSION_ID_PUSH,PERMISSION_STATUS_NOT_DETERMINED}from'@shopgate/engage/core/constants';import{requestAppPermissionStatus}from'@shopgate/engage/core/actions';import{increaseAppStartCount,resetAppStartCount,increaseOrdersPlacedCount,resetOrdersPlacedCount,setLastPopupTimestamp,increaseRejectionCount,showPushOptInModal}from"../action-creators";import{PUSH_OPT_IN_OPT_IN_POSTPONED}from"../constants";import{getPushOptInTriggerState}from"../selectors";var DAY_IN_MS=1000*60*60*24;var increaseRejectionCount$=main$.filter(function(_ref){var action=_ref.action;return action.type===PUSH_OPT_IN_OPT_IN_POSTPONED;});/**
2
+ * Push opt in subscriptions
3
+ * @param {Function} subscribe The subscribe function
4
+ */export default function pushOptIn(subscribe){/**
5
+ * @param {Object} subscriptionParams Params from the subscription callback
6
+ * @param {string} configKey The "pushOptIn" key to be used
7
+ * @param {Function} increaseCountAction Action to increase the count in Redux for the configKey
8
+ * @returns {void}
9
+ */var showOptInAfterChecks=/*#__PURE__*/function(){var _ref3=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(_ref2,configKey,increaseCountAction){var dispatch,getState,_appConfig$pushOptIn,appStarts,ordersPlaced,rejectionMaxCount,minDaysBetweenOptIns,pushStatus,state,configValue,resetAction,resetCountState,configCountState,mustShowModal,hasRepeats,minDaysElapsed;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:dispatch=_ref2.dispatch,getState=_ref2.getState;if(appSupportsPushOptIn()){_context.next=3;break;}return _context.abrupt("return");case 3:_appConfig$pushOptIn=appConfig.pushOptIn;_appConfig$pushOptIn=_appConfig$pushOptIn===void 0?{}:_appConfig$pushOptIn;appStarts=_appConfig$pushOptIn.appStarts,ordersPlaced=_appConfig$pushOptIn.ordersPlaced,rejectionMaxCount=_appConfig$pushOptIn.rejectionMaxCount,minDaysBetweenOptIns=_appConfig$pushOptIn.minDaysBetweenOptIns;// Deactivate feature when config is invalid
10
+ if(!(typeof minDaysBetweenOptIns!=='number'||typeof rejectionMaxCount!=='number'||_typeof(ordersPlaced)!=='object'||_typeof(appStarts)!=='object')){_context.next=9;break;}logger.error('PushOptInTrigger - Config invalid',appConfig===null||appConfig===void 0?void 0:appConfig.pushOptIn);return _context.abrupt("return");case 9:_context.next=11;return dispatch(requestAppPermissionStatus({permissionId:PERMISSION_ID_PUSH}));case 11:pushStatus=_context.sent;if(!(pushStatus!==PERMISSION_STATUS_NOT_DETERMINED)){_context.next=14;break;}return _context.abrupt("return");case 14:dispatch(increaseCountAction());state=getPushOptInTriggerState(getState());configValue=appStarts;resetAction=resetAppStartCount;resetCountState=state.appStartResetCount;configCountState=state.appStartCount;if(configKey==='ordersPlaced'){configValue=ordersPlaced;resetAction=resetOrdersPlacedCount;resetCountState=state.ordersPlacedResetCount;configCountState=state.ordersPlacedCount;}if(!(state.rejectionCount>=rejectionMaxCount)){_context.next=23;break;}return _context.abrupt("return");case 23:mustShowModal=Number(configValue.value)>0&&configCountState>=configValue.value;hasRepeats=configValue.repeats===null||resetCountState<=configValue.repeats;minDaysElapsed=Date.now()-state.lastPopupAt>=minDaysBetweenOptIns*DAY_IN_MS;if(mustShowModal&&hasRepeats&&minDaysElapsed){dispatch(setLastPopupTimestamp());dispatch(resetAction());dispatch(showPushOptInModal());}case 27:case"end":return _context.stop();}}},_callee);}));return function showOptInAfterChecks(_x,_x2,_x3){return _ref3.apply(this,arguments);};}();// event subscriber to handle app start based push opt in
11
+ subscribe(appDidStart$,/*#__PURE__*/function(){var _ref5=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(_ref4){var dispatch,getState;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:dispatch=_ref4.dispatch,getState=_ref4.getState;_context2.next=3;return showOptInAfterChecks({dispatch:dispatch,getState:getState},'appStarts',increaseAppStartCount);case 3:case"end":return _context2.stop();}}},_callee2);}));return function(_x4){return _ref5.apply(this,arguments);};}());// event subscriber to handle order based push opt in
12
+ subscribe(appDidStart$,function(_ref6){var dispatch=_ref6.dispatch,getState=_ref6.getState;event.addCallback('checkoutSuccess',/*#__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 showOptInAfterChecks({dispatch:dispatch,getState:getState},'ordersPlaced',increaseOrdersPlacedCount);case 2:case"end":return _context3.stop();}}},_callee3);})));});subscribe(increaseRejectionCount$,function(_ref8){var dispatch=_ref8.dispatch;dispatch(increaseRejectionCount());});}
@@ -1 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import LiveMessage from"../index";jest.mock("../../../../components",function(){return{I18n:{Text:function Translate(_ref){var string=_ref.string;return string;}}};});describe('<LiveMessage />',function(){var message='My Message';it('should render a polite simple message',function(){var ariaLive='polite';var wrapper=shallow(/*#__PURE__*/React.createElement(LiveMessage,{message:message}));expect(wrapper).toMatchSnapshot();expect(wrapper.find('div').prop('aria-live')).toBe(ariaLive);expect(wrapper.find('Translate').prop('string')).toBe(message);expect(wrapper.find('Translate').prop('params')).toEqual(null);});it('should render an assertive message with params ',function(){var ariaLive='assertive';var params={my:'param'};var wrapper=shallow(/*#__PURE__*/React.createElement(LiveMessage,{message:message,params:params,"aria-live":ariaLive}));expect(wrapper).toMatchSnapshot();expect(wrapper.find('div').prop('aria-live')).toBe(ariaLive);expect(wrapper.find('Translate').prop('string')).toBe(message);expect(wrapper.find('Translate').prop('params')).toEqual(params);});});
@@ -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);}import{UIEvents}from"../../../../core";import{broadcastLiveMessage}from"../helpers";import{EVENT_LIVE_MESSAGE,LIVE_MESSAGE_TYPE_POLITE,LIVE_MESSAGE_TYPE_ASSERTIVE}from"../constants";jest.mock("../../../../core",function(){return{UIEvents:{emit:jest.fn()}};});jest.useFakeTimers();describe('LiveMessenger helpers',function(){beforeEach(function(){jest.clearAllMocks();});describe('broadcastLiveMessage()',function(){var message='My Message';var defaultOptions={type:LIVE_MESSAGE_TYPE_POLITE,params:null,id:null};it('should not broadcast without a message',function(){broadcastLiveMessage();jest.runAllTimers();expect(UIEvents.emit).not.toHaveBeenCalled();});it('should broadcast with default options',function(){broadcastLiveMessage(message);expect(UIEvents.emit).toHaveBeenCalledTimes(1);expect(UIEvents.emit).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,message,defaultOptions);jest.runAllTimers();expect(UIEvents.emit).toHaveBeenCalledTimes(2);expect(UIEvents.emit).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,'',defaultOptions);});it('should broadcast with some options',function(){var options={type:LIVE_MESSAGE_TYPE_ASSERTIVE,params:{some:'params'},id:'some-id'};broadcastLiveMessage(message,options);expect(UIEvents.emit).toHaveBeenCalledTimes(1);expect(UIEvents.emit).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,message,_extends({},options));jest.runAllTimers();expect(UIEvents.emit).toHaveBeenCalledTimes(2);expect(UIEvents.emit).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,'',_extends({},options));});});});
@@ -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 React from'react';import{act}from'react-dom/test-utils';import{mount}from'enzyme';import{UIEvents}from"../../../../core";import LiveMessage from"../../LiveMessage";import{EVENT_LIVE_MESSAGE,LIVE_MESSAGE_TYPE_ASSERTIVE,LIVE_MESSAGE_TYPE_POLITE}from"../constants";import LiveMessenger from"../index";jest.mock("../../../../components",function(){return{I18n:{Text:function Translate(_ref){var string=_ref.string;return string;}}};});jest.mock("../../../../core",function(){return{UIEvents:{addListener:jest.fn(),removeListener:jest.fn()}};});describe('<LiveMessenger />',function(){beforeEach(function(){jest.clearAllMocks();});it('should render',function(){var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,null));expect(wrapper).toMatchSnapshot();var liveMessages=wrapper.find(LiveMessage);expect(liveMessages).toHaveLength(2);expect(liveMessages.at(0).props()).toEqual({'aria-live':'assertive',message:'',params:null});expect(liveMessages.at(1).props()).toEqual({'aria-live':'polite',message:'',params:null});});it('should register and remove the events as expected',function(){var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,null));var _UIEvents$addListener=_slicedToArray(UIEvents.addListener.mock.calls,1),_UIEvents$addListener2=_slicedToArray(_UIEvents$addListener[0],2),callback=_UIEvents$addListener2[1];expect(UIEvents.addListener).toHaveBeenCalledTimes(1);expect(UIEvents.addListener).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,expect.any(Function));expect(UIEvents.removeListener).not.toHaveBeenCalled();wrapper.unmount();expect(UIEvents.addListener).toHaveBeenCalledTimes(1);expect(UIEvents.removeListener).toHaveBeenCalledTimes(1);expect(UIEvents.removeListener).toHaveBeenCalledWith(EVENT_LIVE_MESSAGE,callback);});it('should update the polite message by default when the event comes in',function(){var message='My Message';var options={params:{some:'param'}};var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,null));var _UIEvents$addListener3=_slicedToArray(UIEvents.addListener.mock.calls,1),_UIEvents$addListener4=_slicedToArray(_UIEvents$addListener3[0],2),callback=_UIEvents$addListener4[1];act(function(){callback(message,options);});wrapper.update();expect(wrapper.find(LiveMessage).at(1).props()).toEqual({'aria-live':'polite',params:options.params,message:message});});it('should update the polite message when the event comes in with the appropriate type',function(){var message='My Polite Message';var options={type:LIVE_MESSAGE_TYPE_POLITE,params:{some:'param'}};var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,null));var _UIEvents$addListener5=_slicedToArray(UIEvents.addListener.mock.calls,1),_UIEvents$addListener6=_slicedToArray(_UIEvents$addListener5[0],2),callback=_UIEvents$addListener6[1];act(function(){callback(message,options);});wrapper.update();expect(wrapper.find(LiveMessage).at(1).props()).toEqual({'aria-live':'polite',message:message,params:options.params});});it('should update the assertive message when the event comes in with the appropriate type',function(){var message='My Assertive Message';var options={type:LIVE_MESSAGE_TYPE_ASSERTIVE,params:{some:'param'}};var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,null));var _UIEvents$addListener7=_slicedToArray(UIEvents.addListener.mock.calls,1),_UIEvents$addListener8=_slicedToArray(_UIEvents$addListener7[0],2),callback=_UIEvents$addListener8[1];act(function(){callback(message,options);});wrapper.update();expect(wrapper.find(LiveMessage).at(0).props()).toEqual({'aria-live':'assertive',params:options.params,message:message});});it('should only update the message when it has the correct id',function(){var id='my-id';var message='My Message';var options={};var wrapper=mount(/*#__PURE__*/React.createElement(LiveMessenger,{id:id}));var _UIEvents$addListener9=_slicedToArray(UIEvents.addListener.mock.calls,1),_UIEvents$addListener10=_slicedToArray(_UIEvents$addListener9[0],2),callback=_UIEvents$addListener10[1];act(function(){callback(message,options);});wrapper.update();expect(wrapper.find(LiveMessage).at(1).props()).toEqual({'aria-live':'polite',params:null,message:''});act(function(){callback(message,{id:id});});wrapper.update();expect(wrapper.find(LiveMessage).at(1).props()).toEqual({'aria-live':'polite',params:null,message:message});});});
@@ -1 +0,0 @@
1
- import React from'react';import{mount}from'enzyme';import Navigation from"../index";jest.mock("../../../../components",function(){return{I18n:{Text:function Translate(_ref){var string=_ref.string;return string;}},Link:function Link(_ref2){var children=_ref2.children;return children;}};});var mockTranslate=jest.fn(function(key){return key;});var mockRenderOptions={context:{i18n:function i18n(){return{__:mockTranslate};}}};var entries=[{title:'Title One',link:'/some-link'},{title:'Title Two',link:'/another-link'}];describe('<Navigation />',function(){it('should render with an aria label and entries',function(){var title='Navigation Title';var wrapper=mount(/*#__PURE__*/React.createElement(Navigation,{title:title,entries:entries}),mockRenderOptions);expect(wrapper).toMatchSnapshot();expect(wrapper.find('nav').prop('aria-label')).toEqual(title);expect(wrapper.find('ul').children()).toHaveLength(2);});it('should render empty when no entries are passed',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Navigation,null),mockRenderOptions);expect(wrapper).toMatchSnapshot();expect(wrapper.isEmptyRender()).toBe(true);});});
@@ -1 +0,0 @@
1
- import React from'react';import{mount}from'enzyme';import Section from"../index";var mockTranslate=jest.fn();jest.mock("../../../../components",function(){return{I18n:{Text:function Translate(props){mockTranslate(props);return props.string;}}};});var title='my.headline';var titleParams={some:'params'};describe('<Section />',function(){beforeEach(function(){jest.clearAllMocks();});it('should render with a label',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Section,{title:title,titleParams:titleParams},/*#__PURE__*/React.createElement("div",{id:"child-component"})));expect(wrapper).toMatchSnapshot();expect(wrapper.find('h2').exists()).toBe(true);expect(mockTranslate).toHaveBeenCalledWith({string:title,params:titleParams});});it('should render hidden when no children rendered',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Section,{title:title}));expect(wrapper).toMatchSnapshot();expect(wrapper.find('h2').exists()).toBe(false);expect(mockTranslate).toHaveBeenCalledTimes(0);});describe('MutationObserver',function(){var wrapper;beforeEach(function(){wrapper=mount(/*#__PURE__*/React.createElement(Section,{title:title}));});it('should create an observer instance',function(){expect(global.mutationConstructorSpy).toHaveBeenCalledTimes(1);expect(global.mutationConstructorSpy).toHaveBeenCalledWith(expect.any(Function));});it('should observe with the correct initialization',function(){expect(global.mutationObserveSpy).toHaveBeenCalledTimes(1);expect(global.mutationObserveSpy).toHaveBeenCalledWith(wrapper.find('section').instance(),{childList:true});});it('should call disconnect on unmount',function(){wrapper.unmount();expect(global.mutationDisconnectSpy).toHaveBeenCalledTimes(1);});});});
@@ -1 +0,0 @@
1
- function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}import*as a11y from'.';describe('engage > a11y',function(){it('should have exports',function(){expect(_typeof(a11y)).toEqual('object');});it('should not do undefined exports',function(){Object.keys(a11y).forEach(function(exportKey){expect(typeof a11y[exportKey]!=='undefined').toBe(true);});});});
@@ -1 +0,0 @@
1
- function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}import*as cart from'.';describe('engage > cart',function(){it('should have exports',function(){expect(_typeof(cart)).toEqual('object');});it('should not do undefined exports',function(){Object.keys(cart).forEach(function(exportKey){expect(typeof cart[exportKey]!=='undefined').toBe(true);});});});
@@ -1 +0,0 @@
1
- function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}import*as category from'.';describe('engage > category',function(){it('should have exports',function(){expect(_typeof(category)).toEqual('object');});it('should not do undefined exports',function(){Object.keys(category).forEach(function(exportKey){expect(typeof category[exportKey]!=='undefined').toBe(true);});});});
@@ -1 +0,0 @@
1
- function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}import*as checkout from'.';describe('engage > checkout',function(){it('should have exports',function(){expect(_typeof(checkout)).toEqual('object');});it('should not do undefined exports',function(){Object.keys(checkout).forEach(function(exportKey){expect(typeof checkout[exportKey]!=='undefined').toBe(true);});});});
@@ -1,8 +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);}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);Object.defineProperty(Constructor,"prototype",{writable:false});return Constructor;}import React from'react';import{mount}from'enzyme';import{getAbsoluteHeight}from'@shopgate/pwa-common/helpers/dom';import UIEvents from'@shopgate/pwa-core/emitters/ui';import{SHEET_EVENTS}from'@shopgate/pwa-ui-shared/Sheet';import{updateInsetBackgroundColor,updateFooterHeight}from"../Footer.style";import Footer from"../Footer";var mutationConstructorSpy=jest.fn();var mutationObserveSpy=jest.fn();/* eslint-disable require-jsdoc, extra-rules/potential-point-free, class-methods-use-this */global.MutationObserver=/*#__PURE__*/function(){function _class(callback){_classCallCheck(this,_class);mutationConstructorSpy(callback);}_createClass(_class,[{key:"observe",value:function observe(element,initObject){mutationObserveSpy(element,initObject);}}]);return _class;}();/* eslint-enable require-jsdoc, extra-rules/potential-point-free, class-methods-use-this */var mockedPortalContent;jest.mock("../Footer.style",function(){var actual=require.requireActual("../Footer.style");return _extends({},actual,{updateInsetBackgroundColor:jest.fn(),updateFooterHeight:jest.fn()});});jest.mock('@shopgate/pwa-core/emitters/ui',function(){return{addListener:jest.fn(),removeListener:jest.fn()};});jest.mock('@shopgate/pwa-common/helpers/dom',function(){var actual=require.requireActual('@shopgate/pwa-common/helpers/dom');return _extends({},actual,{getAbsoluteHeight:jest.fn()});});jest.mock('@shopgate/pwa-common/components/Portal',function(){// eslint-disable-next-line require-jsdoc
2
- function Portal(){return mockedPortalContent||null;}return Portal;});var FOOTER_CHILD_ID='footer-child';var PORTAL_CONTENT_ID='portal-content';var insetBackgroundUpdateSpy=jest.spyOn(Footer.prototype,'performFooterUpdate');var defaultBackgroundColor='red';var defaultChildren=/*#__PURE__*/React.createElement("div",{id:FOOTER_CHILD_ID,style:{backgroundColor:defaultBackgroundColor}});/**
3
- * @param {NodeList} children Children for the footer.
4
- * @returns {JSX}
5
- */var createComponent=function createComponent(){var children=arguments.length>0&&arguments[0]!==undefined?arguments[0]:defaultChildren;var wrapper=mount(/*#__PURE__*/React.createElement("div",null,/*#__PURE__*/React.createElement(Footer,null,children)));return wrapper.find(Footer);};/**
6
- * @param {Object} wrapper A wrapper.
7
- * @param {string} id Id of the element to change.
8
- */var addHeightToWrapperElement=function addHeightToWrapperElement(wrapper,id){var elements=wrapper.instance().ref.current.querySelectorAll("#".concat(id));if(elements){Array.from(elements).forEach(function(element){Object.defineProperty(element,'clientHeight',{get:function get(){return 30;}});});}};describe('<Footer />',function(){beforeEach(function(){jest.clearAllMocks();mockedPortalContent=null;});it('should render the component',function(){var wrapper=createComponent();expect(wrapper).toMatchSnapshot();expect(wrapper.find('Portal')).toHaveLength(2);expect(wrapper.find("div#AppFooter > #".concat(FOOTER_CHILD_ID))).toExist();expect(mutationConstructorSpy).toHaveBeenCalledWith(expect.any(Function));expect(insetBackgroundUpdateSpy).toHaveBeenCalledTimes(1);});describe('.hasVisibleContent()',function(){it('should return FALSE when footer has no visible content',function(){var wrapper=createComponent();expect(wrapper.instance().hasVisibleContent()).toBe(false);});it('should return FALSE when there are components, but they are not visible',function(){mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:PORTAL_CONTENT_ID});var wrapper=createComponent();expect(wrapper.instance().hasVisibleContent()).toBe(false);});it('should return FALSE when there are components, but they are supposed to be ignored',function(){mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:PORTAL_CONTENT_ID,"data-footer-inset-update-ignore":true});var wrapper=createComponent(null);addHeightToWrapperElement(wrapper,PORTAL_CONTENT_ID);expect(wrapper.instance().hasVisibleContent()).toBe(false);});it('should return TRUE when the core portal has visible content',function(){var wrapper=createComponent();addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);expect(wrapper.instance().hasVisibleContent()).toBe(true);});it('should return TRUE when the an extension portal has visible content',function(){mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:PORTAL_CONTENT_ID});var wrapper=createComponent(null);addHeightToWrapperElement(wrapper,PORTAL_CONTENT_ID);expect(wrapper.instance().hasVisibleContent()).toBe(true);});});describe('.getInsetBackgroundColor()',function(){it('should return null when there is no visible content',function(){var wrapper=createComponent(null);addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);var elements=wrapper.instance().ref.current.children;expect(wrapper.instance().getInsetBackgroundColor(elements)).toBe(null);});it('should return "red" when there is visible content within the core portal',function(){var wrapper=createComponent();addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);var elements=wrapper.instance().ref.current.children;expect(wrapper.instance().getInsetBackgroundColor(elements)).toBe(defaultBackgroundColor);});it('should return "blue" when there is visible content within the core portal',function(){var backgroundColor='blue';mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:FOOTER_CHILD_ID,style:{backgroundColor:backgroundColor}});var wrapper=createComponent();addHeightToWrapperElement(wrapper,PORTAL_CONTENT_ID);addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);var elements=wrapper.instance().ref.current.children;expect(wrapper.instance().getInsetBackgroundColor(elements)).toBe(backgroundColor);});it('should return "red" when there is visible content within the core portal',function(){var backgroundColor='blue';mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:FOOTER_CHILD_ID,style:{backgroundColor:backgroundColor},"data-footer-inset-update-ignore":true});var wrapper=createComponent();addHeightToWrapperElement(wrapper,PORTAL_CONTENT_ID);addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);var elements=wrapper.instance().ref.current.children;expect(wrapper.instance().getInsetBackgroundColor(elements)).toBe(defaultBackgroundColor);});it('should return null when the last visible content in invisible by the background color',function(){var backgroundColor='rgba(0, 0, 0, 0)';mockedPortalContent=/*#__PURE__*/React.createElement("div",{id:FOOTER_CHILD_ID,style:{backgroundColor:backgroundColor}});var wrapper=createComponent();addHeightToWrapperElement(wrapper,PORTAL_CONTENT_ID);addHeightToWrapperElement(wrapper,FOOTER_CHILD_ID);var elements=wrapper.instance().ref.current.children;expect(wrapper.instance().getInsetBackgroundColor(elements)).toBe(null);});});describe('.performFooterUpdate()',function(){it('should do nothing when the ref is empty',function(){var wrapper=createComponent();wrapper.instance().ref.current=null;updateInsetBackgroundColor.mockClear();wrapper.instance().performFooterUpdate();expect(updateInsetBackgroundColor).not.toHaveBeenCalled();});it('should update the inset background color',function(){var wrapper=createComponent();updateInsetBackgroundColor.mockClear();var instance=wrapper.instance();instance.performFooterUpdate();var backgroundColor=instance.getInsetBackgroundColor(instance.ref.current.children);expect(updateInsetBackgroundColor).toHaveBeenCalledTimes(1);expect(updateInsetBackgroundColor).toHaveBeenCalledWith(backgroundColor);});});describe('MutationObserver',function(){var callback;var instance;beforeEach(function(){var wrapper=createComponent();instance=wrapper.instance();insetBackgroundUpdateSpy.mockClear();var _mutationConstructorS=_slicedToArray(mutationConstructorSpy.mock.calls,1);var _mutationConstructorS2=_slicedToArray(_mutationConstructorS[0],1);callback=_mutationConstructorS2[0];});it('should observer with the correct initialization',function(){expect(mutationObserveSpy).toHaveBeenCalledWith(instance.ref.current,{attributes:true,childList:true,subtree:true});});it('should perform an inset update when the updated DOM element is not ignored',function(){var element=document.createElement('div');callback([{target:element}]);expect(insetBackgroundUpdateSpy).toHaveBeenCalledTimes(1);});it('should not perform an inset update when the updated DOM element is ignored',function(){var element=document.createElement('div');element.setAttribute('data-footer-inset-update-ignore','true');callback([{target:element}]);expect(insetBackgroundUpdateSpy).not.toHaveBeenCalled();});});describe('UI events subscriptions',function(){it('should subscribe / unsubscribe UI events',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Footer,null,/*#__PURE__*/React.createElement("div",null,"Footer")));var instance=wrapper.instance();expect(UIEvents.addListener).toBeCalledTimes(2);expect(UIEvents.addListener).nthCalledWith(1,SHEET_EVENTS.OPEN,instance.hide);expect(UIEvents.addListener).nthCalledWith(2,SHEET_EVENTS.CLOSE,instance.show);wrapper.unmount();expect(UIEvents.removeListener).toBeCalledTimes(2);expect(UIEvents.removeListener).nthCalledWith(1,SHEET_EVENTS.OPEN,instance.hide);expect(UIEvents.removeListener).nthCalledWith(2,SHEET_EVENTS.CLOSE,instance.show);});});describe('updateFooterHeight',function(){var instance;beforeEach(function(){var wrapper=createComponent();instance=wrapper.instance();});it('should set footer height to zero',function(){instance.hide();expect(updateFooterHeight).toHaveBeenCalledWith(0);});it('should set footer height',function(){getAbsoluteHeight.mockReturnValueOnce('48px');instance.show();expect(updateFooterHeight).toHaveBeenCalledWith('48px');});});});
@@ -1,19 +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 React from'react';import{mount}from'enzyme';import{Builder}from'.';describe('<Builder />',function(){it('should render empty form',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{}},name:"foo",handleUpdate:function handleUpdate(){}}));expect(wrapper).toMatchSnapshot();});it('should render two text fields',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{firstName:{label:'foo',type:'text',visible:true},lastName:{label:'bar',type:'text',visible:true}}},name:"foo",handleUpdate:function handleUpdate(){}}));expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(2);});it('should render invisible field with visibility prop set to false',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{firstName:{label:'foo',type:'text',visible:false}}},name:"foo",handleUpdate:function handleUpdate(){}}));// The TextField component is hidden by the ElementText component
2
- expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(0);});it('should modify the element visibility if setVisibilty rule applies',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{foo:{label:'foo',type:'text',visible:true},bar:{label:'bar',type:'text',actions:[{type:'setVisibility',rules:[{context:'foo',type:'notIn',data:['abc']}]}]}}},name:"foo",handleUpdate:function handleUpdate(){}}));// Both should be marked visible at the beginning.
3
- expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(2);// Simulate user input to the text field.
4
- wrapper.find('input').first().simulate('change',{target:{value:'abc'}});// Second field should be marked as hidden but be still rendered.
5
- // The TextField component is only rendered when the ElementText is visible.
6
- expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(1);});it('should reset value when rule applies',function(){var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{foo:{label:'foo',type:'text',visible:true,"default":'default'},bar:{label:'bar',type:'text',"default":'default',actions:[{type:'setValue',params:{value:'cheat',type:'fixed'},rules:[{context:'foo',type:'notIn',data:['default']}]}]}}},name:"foo",handleUpdate:function handleUpdate(){}}));// Default values should be in the inputs.
7
- expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(2);expect(wrapper.find('input').at(0).props().value).toEqual('default');expect(wrapper.find('input').at(1).props().value).toEqual('default');// Simulate text input to trigger rule.
8
- wrapper.find('input').first().simulate('change',{target:{value:'abc'}});wrapper.update();// Second field should be hidden now.
9
- expect(wrapper).toMatchSnapshot();expect(wrapper.find('TextField').length).toEqual(2);expect(wrapper.find('input').at(0).props().value).toEqual('abc');expect(wrapper.find('input').at(1).props().value).toEqual('cheat');});it('should call onChange callback when input is changed',function(){var handleUpdate=jest.fn();var wrapper=mount(/*#__PURE__*/React.createElement(Builder,{config:{fields:{foo:{label:'foo',type:'text',visible:true,"default":'default'}}},name:"foo",id:"foo",handleUpdate:handleUpdate}));// Should call with initial state.
10
- expect(wrapper).toMatchSnapshot();expect(handleUpdate).toHaveBeenCalledWith({foo:'default'},false,[]);handleUpdate.mockClear();// Update input
11
- wrapper.find('input').first().simulate('change',{target:{value:'abc'}});// Should call with updated state.
12
- expect(handleUpdate).toHaveBeenCalledWith({foo:'abc'},false,[]);});describe('Builder::elementChangeHandler',function(){it('should take the updated state from action listener',function(){// Create mocked Form builder.
13
- var handleUpdate=jest.fn();var builder=new Builder({validationErrors:[],config:{fields:{foo:{label:'foo',type:'text',visible:true,"default":'default'}}},handleUpdate:handleUpdate});builder.actionListener.notify=function(){return{formData:{foo:'bar'},validationErrors:{},elementVisibility:{foo:true}};};// Trigger update
14
- builder.elementChangeHandler('foo','bar');// Test
15
- expect(handleUpdate).toHaveBeenCalledWith({foo:'bar'},false,[]);});it('should forward validation errors from form actions',function(){// Create mocked Form builder.
16
- var handleUpdate=jest.fn();var builder=new Builder({validationErrors:[],config:{fields:{foo:{label:'foo',type:'text',visible:true,"default":'default'}}},handleUpdate:handleUpdate});// This mock handler adds a validation error for the field 'foo'
17
- builder.actionListener.notify=function(){return{formData:{foo:'bar'},validationErrors:{foo:'bar baz!'},elementVisibility:{foo:true}};};// Trigger update
18
- builder.elementChangeHandler('foo','bar');// Test
19
- expect(handleUpdate).toHaveBeenCalledWith({foo:'bar'},true,[{path:'foo',message:'bar baz!'}]);});});describe('Builder::elementSortFunc',function(){var builder=new Builder({validationErrors:[],config:{fields:{}},handleUpdate:jest.fn()});var field1={id:'foo',label:'foo'};var field2={id:'foo2',label:'foo2'};it('should keep sortOrder for undefined',function(){expect([field2,field1].sort(builder.elementSortFunc)).toEqual([field2,field1]);});it('should sort elements',function(){var fields=[_extends({},field1,{sortOrder:2}),_extends({},field2,{sortOrder:1})];expect(fields.sort(builder.elementSortFunc)).toEqual(fields.reverse());});it('should keep sortOrder',function(){var fields=[_extends({},field2,{sortOrder:1}),_extends({},field1,{sortOrder:2})];expect(fields.sort(builder.elementSortFunc)).toEqual([].concat(fields));});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1,21 +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;}import ActionListener from"./ActionListener";import{ACTION_TYPE_SET_VISIBILITY,ACTION_TYPE_SET_VALUE,ACTION_TYPE_TRANSFORM,ACTION_SET_VALUE_COPY_FROM,ACTION_RULE_TYPE_ONE_OF}from"./ActionListener.constants";jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:function error(){}}};});/**
2
- * Mock for provinces
3
- * @returns {{ST: string}}
4
- */var mockGetProvincesList=function mockGetProvincesList(){return{ST:'State',DF:'Default-State'};};describe('ActionListener',function(){describe('createSetVisibilityHandler',function(){it('should handle visibility changes correctly',function(){// -------------------------------------------------------------------------------------------
5
- var element={id:'province'};var action={type:ACTION_TYPE_SET_VISIBILITY,rules:[{context:'country',type:ACTION_RULE_TYPE_ONE_OF,data:['US']}]};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createSetVisibilityHandler(element,action);var nextState;var expected;// Perform "make visible" test
6
- nextState={formData:{country:'US'}};expected={formData:{country:'US'},elementVisibility:{province:true}};expect(handler({},nextState)).toEqual(expected);// Perform "make invisible" test
7
- nextState={formData:{country:''}};expected={formData:{country:''},elementVisibility:{province:false}};expect(handler({},nextState)).toEqual(expected);});it('should handle call follow up changes correctly when visibility changed',function(){// -------------------------------------------------------------------------------------------
8
- var element={id:'province'};var action={type:ACTION_TYPE_SET_VISIBILITY,rules:[{context:'country',type:ACTION_RULE_TYPE_ONE_OF,data:['US']}]};var actionListener=new ActionListener(mockGetProvincesList,{});var handleVisibility=actionListener.createSetVisibilityHandler(element,action);// Province element is supposed to be hidden and therefore the follow up
9
- var followUpHandler=jest.fn();actionListener.register('province',followUpHandler);var prevState={formData:{province:'to be changed'}};var nextStateBeforeVisibilityChange={formData:{country:'',province:'to be changed'}};var nextStateAfterVisibilityChange={elementVisibility:{province:false},formData:{country:''}};handleVisibility(prevState,nextStateBeforeVisibilityChange);expect(followUpHandler).toHaveBeenCalledWith(prevState,nextStateAfterVisibilityChange);});});describe('updateProvinceElementHandler',function(){it('should select the first province in the list, when country changes and no default is '+'available',function(){// -------------------------------------------------------------------------------------------
10
- var element={id:'province',required:true};var action={type:'update',rules:[{context:'country'}]};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createUpdateProvinceElementHandler(element,action);var prevState={formData:{province:''}};var nextState={formData:{country:'US'}};// eslint-disable-next-line extra-rules/no-single-line-objects
11
- var expected={formData:{country:'US',province:'ST'}};expect(handler(prevState,nextState)).toEqual(expected);});it('should select the default province in the list on country changes when a match with '+'default is available',function(){var _formData2;// -------------------------------------------------------------------------------------------
12
- var provinceElement={id:'province',"default":'DF',required:true};var countryElement={id:'country',"default":'US'};var action={type:'update',rules:[{context:countryElement.id}]};var prevState={};var nextState={formData:_defineProperty({},countryElement.id,countryElement["default"])};var expected={formData:(_formData2={},_defineProperty(_formData2,provinceElement.id,provinceElement["default"]),_defineProperty(_formData2,countryElement.id,countryElement["default"]),_formData2)};// Defaults matches the same object structure as 'formData'
13
- var actionListener=new ActionListener(mockGetProvincesList,expected.formData);var handler=actionListener.createUpdateProvinceElementHandler(provinceElement,action);// Expects the handler to take over the defaults in this test
14
- expect(handler(prevState,nextState)).toEqual(expected);});});describe('setValueHandler',function(){it('should create copy the referenced element value into the current element',function(){// -------------------------------------------------------------------------------------------
15
- var element={id:'street2'};var action={type:ACTION_TYPE_SET_VALUE,params:{type:ACTION_SET_VALUE_COPY_FROM,value:'street'}};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createSetValueHandler(element,action);// eslint-disable-next-line extra-rules/no-single-line-objects
16
- var prevState={formData:{street:'',street2:''}};// eslint-disable-next-line extra-rules/no-single-line-objects
17
- var nextState={formData:{street:'Street 1',street2:''}};// eslint-disable-next-line extra-rules/no-single-line-objects
18
- var expected={formData:{street:'Street 1',street2:'Street 1'}};expect(handler(prevState,nextState)).toEqual(expected);});});describe('transformHandler',function(){it('should apply the transformHandler correctly for "String" operations',function(){// -------------------------------------------------------------------------------------------
19
- var element={id:'street'};var action={type:ACTION_TYPE_TRANSFORM,params:{type:'toUpperCase'}};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createTransformHandler(element,action);var prevState={formData:{street:''}};var nextState={formData:{street:'Street'}};var expected={formData:{street:'STREET'}};expect(handler(prevState,nextState)).toEqual(expected);});it('should apply the transformHandler correctly for "Boolean" operations',function(){// -------------------------------------------------------------------------------------------
20
- var element={id:'boolTest'};var action={type:ACTION_TYPE_TRANSFORM,params:{type:'toString'}};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createTransformHandler(element,action);var prevState={formData:{boolTest:true}};var nextState={formData:{boolTest:true}};var expected={formData:{boolTest:'true'}};expect(handler(prevState,nextState)).toEqual(expected);});it('should apply the transformHandler correctly for "Number" operations',function(){// -------------------------------------------------------------------------------------------
21
- var element={id:'numberTest'};var action={type:ACTION_TYPE_TRANSFORM,params:{type:'isInteger'}};var actionListener=new ActionListener(mockGetProvincesList,{});var handler=actionListener.createTransformHandler(element,action);var prevState={formData:{numberTest:7.88}};var nextState={formData:{numberTest:7.88}};var expected={formData:{numberTest:false}};expect(handler(prevState,nextState)).toEqual(expected);});});});
@@ -1 +0,0 @@
1
- import buildCountryList from"./buildCountryList";jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:function error(){}}};});var countryElement={countries:['DE','US']};describe('Builder/helpers/buildCountryList',function(){it('should return empty list when config is wrong',function(){expect(buildCountryList({countries:''})).toEqual({});});it('should return list with 2 countries',function(){var expected={DE:'Germany',US:'United States'};expect(buildCountryList(countryElement)).toEqual(expected);});it('should return list with 2 countries and optional on top',function(){var expected={'':'',DE:'Germany',US:'United States'};expect(buildCountryList(countryElement,{'':''})).toEqual(expected);});it('should ignore unknown countries',function(){var expected={DE:'Germany'};expect(buildCountryList({countries:['DE','XX']})).toEqual(expected);});});
@@ -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{ELEMENT_TYPE_SELECT}from"../Builder.constants";import buildFormDefaults from"./buildFormDefaults";var formElement={id:'field',"default":'foo',custom:false};var defaults={field:'baz',customAttributes:{}};describe('Builder/helpers/buildFormDefaults',function(){it('should build defaults from element defaults',function(){var expected={field:'foo'};expect(buildFormDefaults([formElement],{})).toEqual(expected);});it('should build defaults from object defaults ',function(){var expected={field:'baz'};expect(buildFormDefaults([formElement],defaults)).toEqual(expected);});it('should build defaults for custom from element defaults',function(){var expected={field:'foo'};var el=_extends({},formElement,{custom:true});expect(buildFormDefaults([el],defaults)).toEqual(expected);});it('should build defaults for custom from object defaults',function(){var expected={field:'baz'};var el=_extends({},formElement,{custom:true});var def=_extends({},defaults,{customAttributes:{field:'baz'}});expect(buildFormDefaults([el],def)).toEqual(expected);});describe('ELEMENT_TYPE_SELECT',function(){var options={mr:'Mr.',mrs:'Mrs.'};it('should set default value',function(){var el=_extends({},formElement,{type:ELEMENT_TYPE_SELECT,options:options});expect(buildFormDefaults([el])).toEqual({field:'foo'});});it('should set first option',function(){var el=_extends({},formElement,{type:ELEMENT_TYPE_SELECT,options:options,"default":null});expect(buildFormDefaults([el])).toEqual({field:'mr'});});});});/* eslint-enable extra-rules/no-single-line-objects */
@@ -1,3 +0,0 @@
1
- var _excluded=["handleChange"],_excluded2=["handleChange"],_excluded3=["handleChange"];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 _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}import{ELEMENT_TYPE_COUNTRY}from"../Builder.constants";import buildFormElements from"./buildFormElements";jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:function error(){}}};});var formElementConfig={sortOrder:1,label:'Label',type:'text',"default":'default',placeholder:'locales',required:true,visible:true};var formElement={id:'field',sortOrder:1,label:'Label',type:'text',"default":'default',placeholder:'locales',required:true,visible:true,custom:false};describe('Builder/helpers/buildFormElements',function(){it('should not build custom field',function(){var config={fields:{custom:formElementConfig}};expect(buildFormElements(config)).toEqual([]);});it('should not build empty config',function(){var config={fields:{}};expect(buildFormElements(config)).toEqual([]);});it('should build text element',function(){var config={fields:{field:formElementConfig}};var _buildFormElements$=buildFormElements(config)[0],ignore=_buildFormElements$.handleChange,restElement=_objectWithoutProperties(_buildFormElements$,_excluded);expect(restElement).toEqual(formElement);});it('should build 1 country element',function(){var config={fields:{country:_extends({},formElementConfig,{type:ELEMENT_TYPE_COUNTRY}),// eslint-disable-next-line camelcase
2
- country_2:_extends({},formElementConfig,{type:ELEMENT_TYPE_COUNTRY})}};var expected=_extends({},formElement,{id:'country',type:ELEMENT_TYPE_COUNTRY});var _buildFormElements$2=buildFormElements(config)[0],ignore=_buildFormElements$2.handleChange,restElement=_objectWithoutProperties(_buildFormElements$2,_excluded2);expect(restElement).toEqual(expected);});it('should build custom text element',function(){var config={fields:{custom:{field:formElementConfig}}};var expected=_extends({},formElement,{custom:true});var _buildFormElements$3=buildFormElements(config)[0],ignore=_buildFormElements$3.handleChange,restElement=_objectWithoutProperties(_buildFormElements$3,_excluded3);expect(restElement).toEqual(expected);});it('should build correct change handler for text field',function(){var config={fields:{field:formElementConfig}};var mockHandler=jest.fn();var handleChange=buildFormElements(config,mockHandler)[0].handleChange;// Invoke handler with field value
3
- handleChange('bar');expect(mockHandler).toBeCalledWith('field','bar');});});
@@ -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);}import iso3166 from"./iso-3166-2";import buildProvinceList from"./buildProvinceList";describe('Builder/helpers/buildProvinceList',function(){it('should return empty list when country is unknown',function(){expect(buildProvinceList('SOME')).toEqual({});});it('should return a list with US provinces',function(){var expected=iso3166.US.divisions;expect(buildProvinceList('US')).toEqual(expected);});it('should return a list with US provinces and optional',function(){var expected=_extends({'':''},iso3166.US.divisions);expect(buildProvinceList('US',{'':''})).toEqual(expected);});});
@@ -1 +0,0 @@
1
- import IntersectionVisibility from"../index";describe('<IntersectionVisibility />',function(){it('should build a list of 5 thresholds',function(){expect(IntersectionVisibility.buildThresholdList(5)).toEqual([0.20,0.40,0.60,0.80,1.00]);});it('should build a list of 20 thresholds',function(){expect(IntersectionVisibility.buildThresholdList(20)).toEqual([0.05,0.1,0.15,0.2,0.25,0.3,0.35,0.4,0.45,0.5,0.55,0.6,0.65,0.7,0.75,0.8,0.85,0.9,0.95,1]);});});
@@ -1 +0,0 @@
1
- var context={top:20,bottom:40,ariaHidden:false,set:jest.fn(),setTop:jest.fn(),setBottom:jest.fn(),setContentRef:jest.fn(),getContentRef:jest.fn(),scrollTop:jest.fn(),setAriaHidden:jest.fn()};export var ViewContext={Consumer:function Consumer(props){return props.children(context);}};
@@ -1,5 +0,0 @@
1
- import React from'react';import PropTypes from'prop-types';// Export context mock
2
- export{ViewContext}from"./context";/**
3
- * @param {Object} props The component props.
4
- * @return {JSX}
5
- */var MockedView=function MockedView(_ref){var children=_ref.children;return/*#__PURE__*/React.createElement("div",null,children);};MockedView.defaultProps={children:null};export default MockedView;
@@ -1 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import{mockThemeConfig}from'@shopgate/pwa-common/helpers/config/mock';import{setBackgroundColor}from"../style";import View from"../index";jest.mock('@shopgate/pwa-common/helpers/config',function(){return{themeConfig:mockThemeConfig};});jest.mock('@shopgate/pwa-common/context',function(){return{RouteContext:{Consumer:jest.fn(function(_ref){var children=_ref.children;return children({visible:true});})}};});jest.mock("../provider",function(){return function(_ref2){var children=_ref2.children;return children;};});jest.mock("../context");jest.mock("../style",function(){return{__esModule:true,"default":jest.requireActual('../style')["default"],setBackgroundColor:jest.fn()};});describe('engage > components > view > index',function(){beforeEach(jest.clearAllMocks);var wrapper;beforeAll(function(){wrapper=shallow(/*#__PURE__*/React.createElement(View,null,/*#__PURE__*/React.createElement("div",null,"Page #1")));});it('should initialize with visible route',function(){expect(wrapper.dive()).toMatchSnapshot();});it('should have structured content',function(){expect(wrapper.dive().dive().dive().dive()).toMatchSnapshot();});it('should set background on intialization',function(){wrapper=shallow(/*#__PURE__*/React.createElement(View,{background:"#990000"},/*#__PURE__*/React.createElement("div",null,"Page #1"))).dive().dive();expect(setBackgroundColor).toBeCalledWith('#990000');});});
@@ -1 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import Provider from"../provider";jest.mock("../context");describe('engage > components > view > provider',function(){it('should initialize and provider context',function(){var wrapper=shallow(/*#__PURE__*/React.createElement(Provider,null,/*#__PURE__*/React.createElement("div",null,"Page #1")));expect(wrapper).toMatchSnapshot();});});
@@ -1 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import Above from"../index";jest.mock("../../../context");describe('engage > components > view > components > above',function(){it('should render above',function(){var wrapper=shallow(/*#__PURE__*/React.createElement(Above,null)).dive();expect(wrapper).toMatchSnapshot();});});
@@ -1 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import Below from"../index";jest.mock("../../../context");describe('engage > components > view > components > below',function(){it('should render below',function(){var wrapper=shallow(/*#__PURE__*/React.createElement(Below,null)).dive();expect(wrapper).toMatchSnapshot();});});
@@ -1,2 +0,0 @@
1
- import React from'react';import{shallow}from'enzyme';import Content from"../index";jest.mock('@shopgate/pwa-common/helpers/config',function(){return{shopName:'Test Shop'};});jest.mock('@shopgate/pwa-common/context',function(){return{RouteContext:{Consumer:jest.fn(function(_ref){var children=_ref.children;return children({visible:true,pattern:'page/:pageId,'});})}};});describe('engage > components > view > components > content',function(){beforeEach(jest.clearAllMocks);it('should render content',function(){var wrapper=shallow(/*#__PURE__*/React.createElement(Content,{setContentRef:jest.fn()},/*#__PURE__*/React.createElement("div",null,"Page #1")),{disableLifecycleMethods:true})// Dive through Route context and into render component
2
- .dive().dive();expect(wrapper).toMatchSnapshot();});});
@@ -1,4 +0,0 @@
1
- /* eslint-disable require-jsdoc */import Sheet from'@shopgate/pwa-ui-shared/Sheet';// ICONS IOS
2
- export{default as CartIconIOS}from'@shopgate/pwa-ui-ios/icons/CartIcon';export{default as FilterIconIOS}from'@shopgate/pwa-ui-ios/icons/FilterIcon';export{default as HomeIconIOS}from'@shopgate/pwa-ui-ios/icons/HomeIcon';export{default as ShareIconIOS}from'@shopgate/pwa-ui-ios/icons/ShareIcon';// ICONS ANDROID
3
- export{default as ShareIconAndroid}from'@shopgate/pwa-ui-material/icons/ShareIcon';// ICONS SHARED
4
- export{default as AccountBoxIcon}from'@shopgate/pwa-ui-shared/icons/AccountBoxIcon';export{default as AddMoreIcon}from'@shopgate/pwa-ui-shared/icons/AddMoreIcon';export{default as ArrowDropIcon}from'@shopgate/pwa-ui-shared/icons/ArrowDropIcon';export{default as ArrowIcon}from'@shopgate/pwa-ui-shared/icons/ArrowIcon';export{default as BarcodeScannerIcon}from'@shopgate/pwa-ui-shared/icons/BarcodeScannerIcon';export{default as BoxIcon}from'@shopgate/pwa-ui-shared/icons/BoxIcon';export{default as BrowseIcon}from'@shopgate/pwa-ui-shared/icons/BrowseIcon';export{default as BurgerIcon}from'@shopgate/pwa-ui-shared/icons/BurgerIcon';export{default as CartIcon}from'@shopgate/pwa-ui-shared/icons/CartIcon';export{default as CartPlusIcon}from'@shopgate/pwa-ui-shared/icons/CartPlusIcon';export{default as CheckedIcon}from'@shopgate/pwa-ui-shared/icons/CheckedIcon';export{default as CheckIcon}from'@shopgate/pwa-ui-shared/icons/CheckIcon';export{default as ChevronIcon}from'@shopgate/pwa-ui-shared/icons/ChevronIcon';export{default as CreditCardIcon}from'@shopgate/pwa-ui-shared/icons/CreditCardIcon';export{default as CrossIcon}from'@shopgate/pwa-ui-shared/icons/CrossIcon';export{default as DescriptionIcon}from'@shopgate/pwa-ui-shared/icons/DescriptionIcon';export{default as FilterIcon}from'@shopgate/pwa-ui-shared/icons/FilterIcon';export{default as FlashEnabledIcon}from'@shopgate/pwa-ui-shared/icons/FlashEnabledIcon';export{default as FlashDisabledIcon}from'@shopgate/pwa-ui-shared/icons/FlashDisabledIcon';export{default as GridIcon}from'@shopgate/pwa-ui-shared/icons/GridIcon';export{default as HeartIcon}from'@shopgate/pwa-ui-shared/icons/HeartIcon';export{default as HeartOutlineIcon}from'@shopgate/pwa-ui-shared/icons/HeartOutlineIcon';export{default as HomeIcon}from'@shopgate/pwa-ui-shared/icons/HomeIcon';export{default as InfoIcon}from'@shopgate/pwa-ui-shared/icons/InfoIcon';export{default as InfoOutlineIcon}from'@shopgate/pwa-ui-shared/icons/InfoOutlineIcon';export{default as ListIcon}from'@shopgate/pwa-ui-shared/icons/ListIcon';export{default as LocalShippingIcon}from'@shopgate/pwa-ui-shared/icons/LocalShippingIcon';export{default as LockIcon}from'@shopgate/pwa-ui-shared/icons/LockIcon';export{default as LogoutIcon}from'@shopgate/pwa-ui-shared/icons/LogoutIcon';export{default as MagnifierIcon}from'@shopgate/pwa-ui-shared/icons/MagnifierIcon';export{default as MoreIcon}from'@shopgate/pwa-ui-shared/icons/MoreIcon';export{default as MoreVertIcon}from'@shopgate/pwa-ui-shared/icons/MoreVertIcon';export{default as PlaceholderIcon}from'@shopgate/pwa-ui-shared/icons/PlaceholderIcon';export{default as RadioCheckedIcon}from'@shopgate/pwa-ui-shared/icons/RadioCheckedIcon';export{default as RadioUncheckedIcon}from'@shopgate/pwa-ui-shared/icons/RadioUncheckedIcon';export{default as SecurityIcon}from'@shopgate/pwa-ui-shared/icons/SecurityIcon';export{default as ShoppingCartIcon}from'@shopgate/pwa-ui-shared/icons/ShoppingCartIcon';export{default as SortIcon}from'@shopgate/pwa-ui-shared/icons/SortIcon';export{default as StarHalfIcon}from'@shopgate/pwa-ui-shared/icons/StarHalfIcon';export{default as StarIcon}from'@shopgate/pwa-ui-shared/icons/StarIcon';export{default as StarOutlineIcon}from'@shopgate/pwa-ui-shared/icons/StarOutlineIcon';export{default as TickIcon}from'@shopgate/pwa-ui-shared/icons/TickIcon';export{default as TrashIcon}from'@shopgate/pwa-ui-shared/icons/TrashIcon';export{default as UncheckedIcon}from'@shopgate/pwa-ui-shared/icons/UncheckedIcon';export{default as ViewListIcon}from'@shopgate/pwa-ui-shared/icons/ViewListIcon';export{default as VisibilityIcon}from'@shopgate/pwa-ui-shared/icons/VisibilityIcon';export{default as VisibilityOffIcon}from'@shopgate/pwa-ui-shared/icons/VisibilityOffIcon';/** @returns {ReactElement} */export var SurroundPortals=function SurroundPortals(_ref){var children=_ref.children;return children;};/** @returns {ReactElement} */export var HtmlSanitizer=function HtmlSanitizer(_ref2){var children=_ref2.children;return children;};export var SheetDrawer=Sheet;export var SheetList=function SheetList(_ref3){var children=_ref3.children;return children;};export var I18n={Text:function Text(){return'I18n.Text';}};export var PlaceholderParagraph=function PlaceholderParagraph(_ref4){var children=_ref4.children;return children;};export{default as View,ViewContext}from"../View/__mocks__/index";/* eslint-enable require-jsdoc */
@@ -1 +0,0 @@
1
- function _typeof(obj){"@babel/helpers - typeof";return _typeof="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(obj){return typeof obj;}:function(obj){return obj&&"function"==typeof Symbol&&obj.constructor===Symbol&&obj!==Symbol.prototype?"symbol":typeof obj;},_typeof(obj);}import*as components from'.';describe('engage > components',function(){it('should have exports',function(){expect(_typeof(components)).toEqual('object');});it('should not do undefined exports',function(){Object.keys(components).forEach(function(exportKey){expect(typeof components[exportKey]!=='undefined').toBe(true);});});});
@@ -1,2 +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 _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}function _defineProperties(target,props){for(var i=0;i<props.length;i++){var descriptor=props[i];descriptor.enumerable=descriptor.enumerable||false;descriptor.configurable=true;if("value"in descriptor)descriptor.writable=true;Object.defineProperty(target,descriptor.key,descriptor);}}function _createClass(Constructor,protoProps,staticProps){if(protoProps)_defineProperties(Constructor.prototype,protoProps);if(staticProps)_defineProperties(Constructor,staticProps);Object.defineProperty(Constructor,"prototype",{writable:false});return Constructor;}import grantGeolocationPermissions from"../grantGeolocationPermissions";import getGeolocation from"../getGeolocation";import{GEOLOCATION_ERROR_DENIED}from"../../constants/geolocationRequest";var mockedPosition={coords:{accuracy:25,latitude:50.4330,longitude:8.67447},timestamp:1563873516224};var mockedGeolocationRequest=jest.fn().mockResolvedValue(mockedPosition);jest.mock("../grantGeolocationPermissions",function(){return jest.fn().mockResolvedValue(true);});jest.mock("../../classes/GeolocationRequest",function(){return/*#__PURE__*/function(){function Foo(){_classCallCheck(this,Foo);}_createClass(Foo,[{key:"dispatch",value:// eslint-disable-next-line require-jsdoc, class-methods-use-this
2
- function dispatch(){return mockedGeolocationRequest();}}]);return Foo;}();});describe('engage > core > actions > grantCameraPermissions',function(){var dispatch=jest.fn(function(action){return action;});beforeEach(function(){jest.clearAllMocks();});it('should resolve the with current position',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var position;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return getGeolocation()(dispatch);case 2:position=_context.sent;expect(position).toBe(mockedPosition);expect(dispatch).toHaveBeenCalledTimes(1);expect(grantGeolocationPermissions).toHaveBeenCalledTimes(1);expect(grantGeolocationPermissions).toHaveBeenCalledWith({});expect(mockedGeolocationRequest).toHaveBeenCalledTimes(1);case 8:case"end":return _context.stop();}}},_callee);})));it('should pass through the options to the grantGeolocationPermissions action call',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var options;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:options={useSettingsModal:true,modal:{message:'Modal message',confirm:'Confirm label'}};_context2.next=3;return expect(getGeolocation(options)(dispatch)).resolves.toBe(mockedPosition);case 3:expect(grantGeolocationPermissions).toHaveBeenCalledWith(options);case 4:case"end":return _context2.stop();}}},_callee2);})));it('should reject with an error when permissions are not granted',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:grantGeolocationPermissions.mockResolvedValueOnce(false);expect.assertions(4);_context3.prev=2;_context3.next=5;return getGeolocation()(dispatch);case 5:_context3.next=13;break;case 7:_context3.prev=7;_context3.t0=_context3["catch"](2);expect(_context3.t0).toBeInstanceOf(Error);expect(_context3.t0.code).toBe(GEOLOCATION_ERROR_DENIED);expect(grantGeolocationPermissions).toHaveBeenCalledTimes(1);expect(mockedGeolocationRequest).not.toHaveBeenCalled();case 13:case"end":return _context3.stop();}}},_callee3,null,[[2,7]]);})));it('should reject with an error when permissions are not granted',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:mockedGeolocationRequest.mockRejectedValueOnce(new Error());expect.assertions(3);_context4.prev=2;_context4.next=5;return getGeolocation()(dispatch);case 5:_context4.next=12;break;case 7:_context4.prev=7;_context4.t0=_context4["catch"](2);expect(_context4.t0).toBeInstanceOf(Error);expect(grantGeolocationPermissions).toHaveBeenCalledTimes(1);expect(mockedGeolocationRequest).toHaveBeenCalledTimes(1);case 12:case"end":return _context4.stop();}}},_callee4,null,[[2,7]]);})));});
@@ -1 +0,0 @@
1
- import{PERMISSION_ID_CAMERA}from'@shopgate/pwa-core/constants/AppPermissions';import grantPermissions from"../grantPermissions";import grantCameraPermissions from"../grantCameraPermissions";jest.mock("../grantPermissions",function(){return jest.fn().mockReturnValue('grantPermissions');});describe('engage > core > actions > grantCameraPermissions',function(){var dispatch=jest.fn(function(action){return action;});beforeEach(function(){jest.clearAllMocks();});it('should dispatch as expected without options',function(){var result=grantCameraPermissions()(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_CAMERA,useSettingsModal:false,modal:{title:null,message:'permissions.access_denied.camera_message',confirm:'permissions.access_denied.settings_button'}});});it('should dispatch as expected with some custom modal options',function(){var customModalOptions={title:'Modal title',dismiss:'Dismiss label'};var result=grantCameraPermissions({useSettingsModal:true,modal:customModalOptions})(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_CAMERA,useSettingsModal:true,modal:{title:'Modal title',message:'permissions.access_denied.camera_message',confirm:'permissions.access_denied.settings_button',dismiss:'Dismiss label'}});});it('should dispatch as expected with complete custom modal options',function(){var customModalOptions={title:'Modal title',message:'Modal message',confirm:'Confirm label',dismiss:'Dismiss label',params:{param:'one'}};var result=grantCameraPermissions({useSettingsModal:true,modal:customModalOptions})(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_CAMERA,useSettingsModal:true,modal:customModalOptions});});});
@@ -1 +0,0 @@
1
- import{PERMISSION_ID_LOCATION}from'@shopgate/pwa-core/constants/AppPermissions';import grantPermissions from"../grantPermissions";import grantGeolocationPermissions from"../grantGeolocationPermissions";jest.mock("../grantPermissions",function(){return jest.fn().mockReturnValue('grantPermissions');});describe('engage > core > actions > grantGeolocationPermissions',function(){var dispatch=jest.fn(function(action){return action;});beforeEach(function(){jest.clearAllMocks();});it('should dispatch as expected without options',function(){var result=grantGeolocationPermissions()(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_LOCATION,useSettingsModal:false,modal:{title:null,message:'permissions.access_denied.geolocation_message',confirm:'permissions.access_denied.settings_button'}});});it('should dispatch as expected with some custom modal options',function(){var customModalOptions={title:'Modal title',dismiss:'Dismiss label'};var result=grantGeolocationPermissions({useSettingsModal:true,modal:customModalOptions})(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_LOCATION,useSettingsModal:true,modal:{title:'Modal title',message:'permissions.access_denied.geolocation_message',confirm:'permissions.access_denied.settings_button',dismiss:'Dismiss label'}});});it('should dispatch as expected with complete custom modal options',function(){var customModalOptions={title:'Modal title',message:'Modal message',confirm:'Confirm label',dismiss:'Dismiss label',params:{param:'one'}};var result=grantGeolocationPermissions({useSettingsModal:true,modal:customModalOptions})(dispatch);expect(result).toEqual(grantPermissions());expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(grantPermissions());expect(grantPermissions).toHaveBeenCalledTimes(3);expect(grantPermissions).toHaveBeenCalledWith({permissionId:PERMISSION_ID_LOCATION,useSettingsModal:true,modal:customModalOptions});});});
@@ -1,9 +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);}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 event from'@shopgate/pwa-core/classes/Event';import{APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND}from'@shopgate/pwa-core/constants/AppEvents';import openAppSettings from'@shopgate/pwa-core/commands/openAppSettings';import showModal from'@shopgate/pwa-common/actions/modal/showModal';import{STATUS_DENIED,STATUS_GRANTED,STATUS_NOT_DETERMINED,STATUS_NOT_SUPPORTED,PERMISSION_ID_CAMERA}from'@shopgate/pwa-core/constants/AppPermissions';import{getAppPermissions,requestAppPermissions}from'@shopgate/pwa-core/commands/appPermissions';import{logger}from'@shopgate/pwa-core/helpers';import grantPermissions from"../grantPermissions";jest.mock('@shopgate/pwa-core/classes/Event');jest.mock('@shopgate/pwa-core/commands/openAppSettings');jest.mock('@shopgate/pwa-core/commands/appPermissions',function(){return{getAppPermissions:jest.fn(),requestAppPermissions:jest.fn()};});jest.mock('@shopgate/pwa-common/actions/modal/showModal',function(){return jest.fn();});jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:jest.fn()}};});/**
2
- * @param {string} status The desired permission status.
3
- * @returns {Array}
4
- */var getPermissionsResponse=function getPermissionsResponse(){var status=arguments.length>0&&arguments[0]!==undefined?arguments[0]:STATUS_GRANTED;return[{status:status}];};/**
5
- * Flushes the promise queue.
6
- * @returns {Promise}
7
- */var flushPromises=function flushPromises(){return new Promise(function(resolve){return setImmediate(resolve);});};var customModalOptions={message:'Modal message',confirm:'Confirm label',dismiss:'Dismiss label',params:{param:'one'}};describe('engage > core > actions > grantPermissions',function(){var dispatch=jest.fn(function(action){return action;});jest.useFakeTimers();beforeAll(function(){getAppPermissions.mockResolvedValue(getPermissionsResponse(STATUS_GRANTED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(STATUS_GRANTED));showModal.mockResolvedValue(true);});beforeEach(function(){jest.clearAllMocks();event.removeAllListeners();});var permissionId=PERMISSION_ID_CAMERA;it('should resolve with TRUE when the permissions are granted',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var granted;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return grantPermissions({permissionId:permissionId})(dispatch);case 2:granted=_context.sent;expect(granted).toBe(true);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();case 9:case"end":return _context.stop();}}},_callee);})));it('should resolve with FALSE when called with an invalid permissionId',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var granted;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return grantPermissions({permissionId:'unknownId'})(dispatch);case 2:granted=_context2.sent;expect(granted).toBe(false);expect(getAppPermissions).not.toHaveBeenCalled();expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).toHaveBeenCalledTimes(1);case 10:case"end":return _context2.stop();}}},_callee2);})));it('should resolve with FALSE when the permissions are not supported',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var granted;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_NOT_SUPPORTED));_context3.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context3.sent;expect(granted).toBe(false);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).not.toHaveBeenCalled();expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 11:case"end":return _context3.stop();}}},_callee3);})));it('should resolve with TRUE when the permissions where not determined, but the user granted them',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var granted;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_NOT_DETERMINED));_context4.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context4.sent;expect(granted).toBe(true);expect(getAppPermissions).toHaveBeenCalledWith([permissionId]);expect(requestAppPermissions).toHaveBeenCalledWith([{permissionId:permissionId}]);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 11:case"end":return _context4.stop();}}},_callee4);})));it('should resolve with FALSE when the permissions where not determined, and the user denied them',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var granted;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_NOT_DETERMINED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(STATUS_DENIED));_context5.next=4;return grantPermissions({permissionId:permissionId})(dispatch);case 4:granted=_context5.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 10:case"end":return _context5.stop();}}},_callee5);})));it('should resolve with FALSE when the permissions where not determined, and the user denied them temporary',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var granted;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_NOT_DETERMINED));requestAppPermissions.mockResolvedValue(getPermissionsResponse(STATUS_NOT_DETERMINED));_context6.next=4;return grantPermissions({permissionId:permissionId})(dispatch);case 4:granted=_context6.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 10:case"end":return _context6.stop();}}},_callee6);})));it('should resolve with FALSE when the permissions are denied, and no settings modal is about to be shown',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var granted;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_DENIED));_context7.next=3;return grantPermissions({permissionId:permissionId})(dispatch);case 3:granted=_context7.sent;expect(granted).toBe(false);expect(dispatch).not.toHaveBeenCalled();expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();expect(logger.error).not.toHaveBeenCalled();case 9:case"end":return _context7.stop();}}},_callee7);})));it('should resolve with FALSE when the user denied to open the app settings',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){var granted;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_DENIED));showModal.mockResolvedValueOnce(false);_context8.next=4;return grantPermissions({permissionId:permissionId,useSettingsModal:true,modal:customModalOptions})(dispatch);case 4:granted=_context8.sent;expect(granted).toBe(false);expect(dispatch).toHaveBeenCalledTimes(1);expect(showModal).toHaveBeenCalledWith(_extends({title:null},customModalOptions));expect(openAppSettings).not.toHaveBeenCalled();expect(event.addCallbackSpy).not.toHaveBeenCalled();case 10:case"end":return _context8.stop();}}},_callee8);})));it('should resolve with FALSE when the user opened the settings, but did not grant permissions',function(done){getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_DENIED));getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_DENIED));grantPermissions({permissionId:permissionId,useSettingsModal:true})(dispatch).then(function(granted){expect(granted).toBe(false);expect(dispatch).toHaveBeenCalledTimes(1);expect(openAppSettings).toHaveBeenCalledTimes(1);expect(event.removeCallbackSpy).toHaveBeenCalledWith(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,expect.any(Function));done();});// Flush the promise queue, so that the code inside of promise from the action is executed.
8
- flushPromises().then(function(){event.call(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND);jest.runAllTimers();});});it('should resolve with TRUE when the user opened the settings, and granted permissions',function(done){getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_DENIED));getAppPermissions.mockResolvedValueOnce(getPermissionsResponse(STATUS_GRANTED));grantPermissions({permissionId:permissionId,useSettingsModal:true})(dispatch).then(function(granted){expect(granted).toBe(true);expect(dispatch).toHaveBeenCalledTimes(1);expect(openAppSettings).toHaveBeenCalledTimes(1);expect(event.removeCallbackSpy).toHaveBeenCalledWith(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND,expect.any(Function));done();});// Flush the promise queue, so that the code inside of promise from the action is executed.
9
- flushPromises().then(function(){event.call(APP_EVENT_APPLICATION_WILL_ENTER_FOREGROUND);jest.runAllTimers();});});});
@@ -1 +0,0 @@
1
- import{isIos}from'@shopgate/pwa-common/selectors/client';import{updateLegacyNavigationBar}from"../../helpers/updateLegacyNavigationBar";import updateStatusBarBackground from"../updateStatusBarBackground";jest.mock("../../helpers/updateLegacyNavigationBar",function(){return{updateLegacyNavigationBar:jest.fn()};});jest.mock('@shopgate/pwa-common/selectors/client',function(){return{isIos:jest.fn().mockReturnValue(true)};});describe('engage > core > actions > updateStatusBarBackground()',function(){var color='#000';var state={some:'state'};var getState=jest.fn().mockReturnValue(state);beforeEach(function(){jest.clearAllMocks();});it('should do nothing when the device does not run with iOS',function(){isIos.mockReturnValueOnce(false);updateStatusBarBackground(color)(null,getState);expect(isIos).toHaveBeenCalledWith(state);expect(updateLegacyNavigationBar).not.toHaveBeenCalled();});it('should call the updateLegacyNavigationBar helper with the passed color',function(){updateStatusBarBackground(color)(null,getState);expect(isIos).toHaveBeenCalledWith(state);expect(updateLegacyNavigationBar).toHaveBeenCalledTimes(1);expect(updateLegacyNavigationBar).toHaveBeenCalledWith({statusBarBackground:color,isDefault:false});});it('should call the updateLegacyNavigationBar helper with the isDefault flag',function(){updateStatusBarBackground(null,true)(null,getState);expect(isIos).toHaveBeenCalledWith(state);expect(updateLegacyNavigationBar).toHaveBeenCalledTimes(1);expect(updateLegacyNavigationBar).toHaveBeenCalledWith({isDefault:true});});it('should call the updateLegacyNavigationBar helper with just the isDefault property when no color was passed',function(){updateStatusBarBackground()(null,getState);expect(isIos).toHaveBeenCalledWith(state);expect(updateLegacyNavigationBar).toHaveBeenCalledTimes(1);expect(updateLegacyNavigationBar).toHaveBeenCalledWith({isDefault:false});});});
@@ -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 GeolocationRequest,{GEOLOCATION_DEFAULT_TIMEOUT}from"../GeolocationRequest";import{GEOLOCATION_ERROR_UNKNOWN,GEOLOCATION_ERROR_DENIED,GEOLOCATION_ERROR_UNAVAILABLE,GEOLOCATION_ERROR_TIMEOUT}from"../../constants/geolocationRequest";var successPayload;var errorPayload;var getCurrentPosition=jest.fn().mockImplementation(function(successCb,errorCb){if(errorPayload){errorCb(errorPayload);return;}successCb(successPayload);});global.navigator.geolocation={getCurrentPosition:getCurrentPosition};var mockSuccessPayload={coords:{accuracy:25,latitude:50.4330,longitude:8.67447},timestamp:1563873516224};describe('GeolocationRequest',function(){var instance;beforeEach(function(){jest.clearAllMocks();successPayload=_extends({},mockSuccessPayload);errorPayload=null;instance=new GeolocationRequest();});it('should initialize the options as expected',function(){expect(instance.options).toEqual({timeout:GEOLOCATION_DEFAULT_TIMEOUT});});describe('.setTimeout()',function(){it('should set a new timeout',function(){var result=instance.setTimeout(5000);expect(instance.options.timeout).toBe(5000);expect(result).toBe(instance);});it('should set the default timeout when called without a value',function(){instance.setTimeout(5000);expect(instance.options.timeout).toBe(5000);var result=instance.setTimeout();expect(instance.options.timeout).toBe(GEOLOCATION_DEFAULT_TIMEOUT);expect(result).toBe(instance);});});describe('.dispatch()',function(){it('should invoke getCurrentPosition() as expected',/*#__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 instance.dispatch();case 2:expect(getCurrentPosition).toHaveBeenCalledTimes(1);expect(getCurrentPosition).toHaveBeenCalledWith(expect.any(Function),expect.any(Function),instance.options);case 4:case"end":return _context.stop();}}},_callee);})));it('should resolve as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var coords;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:coords=mockSuccessPayload.coords;_context2.next=3;return expect(instance.dispatch()).resolves.toEqual({accuracy:coords.accuracy,latitude:coords.latitude,longitude:coords.longitude});case 3:case"end":return _context2.stop();}}},_callee2);})));it('should reject with the expected errors',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var mockError;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:/**
2
- * @param {string} code Error code.
3
- * @param {string} message Error message.
4
- * @returns {Error}
5
- */mockError=function mockError(code,message){var error=new Error(message);error.code=code;return error;};/* eslint-disable extra-rules/no-single-line-objects */errorPayload={code:0,message:'One'};_context3.next=4;return expect(instance.dispatch()).rejects.toEqual(mockError(GEOLOCATION_ERROR_UNKNOWN,'One'));case 4:errorPayload={code:1,message:'Two'};_context3.next=7;return expect(instance.dispatch()).rejects.toEqual(mockError(GEOLOCATION_ERROR_DENIED,'Two'));case 7:errorPayload={code:2,message:'Three'};_context3.next=10;return expect(instance.dispatch()).rejects.toEqual(mockError(GEOLOCATION_ERROR_UNAVAILABLE,'Three'));case 10:errorPayload={code:3,message:'Four'};_context3.next=13;return expect(instance.dispatch()).rejects.toEqual(mockError(GEOLOCATION_ERROR_TIMEOUT,'Four'));case 13:case"end":return _context3.stop();}}},_callee3);})));});});
@@ -1 +0,0 @@
1
- import{getPageConfig}from"../getPageConfig";import{getThemeConfig}from"../getThemeConfig";jest.mock("../getThemeConfig",function(){return{getThemeConfig:jest.fn()};});var requestedPagePattern='/requested/page';describe('engage > core > config',function(){describe('getPageConfig()',function(){it('should return an empty object if no pages are defined in the theme config.',function(){getThemeConfig.mockReturnValueOnce({});expect(getPageConfig(requestedPagePattern)).toEqual({});});it('should return an empty object if the page is not found.',function(){getThemeConfig.mockReturnValueOnce({pages:[]});expect(getPageConfig(requestedPagePattern)).toEqual({});});it('should only return the page, which matches the given pattern.',function(){getThemeConfig.mockReturnValueOnce({pages:[{pattern:'/some/other/page',name:'Other Page'},{pattern:requestedPagePattern,name:'Correct page'},{pattern:'/yet/another/page',name:'Yet Another Page'}]});expect(getPageConfig(requestedPagePattern)).toEqual({pattern:requestedPagePattern,name:'Correct page'});});});});
@@ -1,2 +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;}import{getPageSettings}from"../getPageSettings";import{getThemeSettings}from"../getThemeSettings";import{getPageConfig}from"../getPageConfig";jest.mock("../getThemeSettings",function(){return{getThemeSettings:jest.fn()};});jest.mock("../getPageConfig",function(){return{getPageConfig:jest.fn()};});var requestedPagePattern='/requested/page';describe('engage > core > config',function(){describe('getPageSettings()',function(){beforeEach(function(){jest.resetAllMocks();});it('should return an empty object when no page settings are available and no key set.',function(){getThemeSettings.mockReturnValueOnce(undefined);getPageConfig.mockReturnValueOnce({});expect(getPageSettings(requestedPagePattern)).toEqual({});});it('should return all settings of the given page without inheriting from higher scope.',function(){getThemeSettings.mockReturnValueOnce({higher:{scope:'settings'}});getPageConfig.mockReturnValueOnce({pattern:requestedPagePattern,name:'PageName',settings:{all:{page:'settings'}}});expect(getPageSettings(requestedPagePattern)).toEqual({all:{page:'settings'}});});it('should pass down the key to the lower level functions for filtered inheritance.',function(){var matchingKey='someKey';getThemeSettings.mockReturnValueOnce({});getPageConfig.mockReturnValueOnce({});getPageSettings(requestedPagePattern,matchingKey);expect(getThemeSettings).toBeCalledWith(matchingKey);expect(getThemeSettings).toBeCalledTimes(1);});it('should return undefined when the given key does not exist in any scope of settings.',function(){getThemeSettings.mockReturnValueOnce(undefined);getPageConfig.mockReturnValueOnce({});expect(getPageSettings(requestedPagePattern,'nonExistentKey')).toBeUndefined();getThemeSettings.mockReturnValueOnce(undefined);getPageConfig.mockReturnValueOnce({settings:{someOtherKey:'someOtherValue'}});expect(getPageSettings(requestedPagePattern,'nonExistentKey')).toBeUndefined();});it('should inherit matching keys from theme settings.',function(){// Return unpacked object, not containing the key anymore, because the match is guaranteed
2
- getThemeSettings.mockReturnValueOnce({things:{to:{inherit:'some inherited value'}}});getPageConfig.mockReturnValueOnce({});expect(getPageSettings(requestedPagePattern,'matchingKey')).toEqual({things:{to:{inherit:'some inherited value'}}});});it('should inherit and mix properties for keys matching theme and page settings.',function(){var _settings;var matchingKey='someKey';getThemeSettings.mockReturnValueOnce({things:{toMix:{inherit:'some inherited value',keep:'low priority'}}});getPageConfig.mockReturnValueOnce({settings:(_settings={},_defineProperty(_settings,matchingKey,{things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'}),_defineProperty(_settings,"nonMatchingKey",{ignore:'this'}),_settings)});expect(getPageSettings(requestedPagePattern,matchingKey)).toEqual({things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting',inherit:'some inherited value'}},moreToKeep:'keep full key'});});it('should not fail when there is nothing to inherit from.',function(){var _settings2;var matchingKey='someKey';getThemeSettings.mockReturnValueOnce(undefined);getPageConfig.mockReturnValueOnce({settings:(_settings2={},_defineProperty(_settings2,matchingKey,{things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'}),_defineProperty(_settings2,"nonMatchingKey",{ignore:'this'}),_settings2)});expect(getPageSettings(requestedPagePattern,matchingKey)).toEqual({things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'});});});});
@@ -1 +0,0 @@
1
- import{getThemeAssets}from"../getThemeAssets";import{getThemeConfig}from"../getThemeConfig";jest.mock("../getThemeConfig",function(){return{getThemeConfig:jest.fn()};});describe('engage > core > config',function(){describe('getThemeAssets()',function(){it('should return an empty object if no assets are available without using a key.',function(){getThemeConfig.mockReturnValueOnce({});var assets=getThemeAssets();expect(assets).toEqual({});});it('should return all theme assets when no key is passed.',function(){getThemeConfig.mockReturnValueOnce({assets:{logo:'some-logo',icons:{}}});var assets=getThemeAssets();expect(assets).toEqual({logo:'some-logo',icons:{}});});it('should return only a single theme asset entry, matching the given key.',function(){getThemeConfig.mockReturnValueOnce({assets:{logo:'some-logo',icons:{}}});var assets=getThemeAssets('logo');expect(assets).toEqual('some-logo');});it('should return undefined if the requested asset key does not exist.',function(){getThemeConfig.mockReturnValueOnce({assets:{logo:'some-logo',icons:{}}});var assets=getThemeAssets('other');expect(assets).toBeUndefined();});});});
@@ -1 +0,0 @@
1
- import{getThemeColors}from"../getThemeColors";import{getThemeConfig}from"../getThemeConfig";jest.mock("../getThemeConfig",function(){return{getThemeConfig:jest.fn()};});describe('engage > core > config',function(){describe('getThemeColors()',function(){it('should return an empty object if no colors are available without using a key.',function(){getThemeConfig.mockReturnValueOnce({});var colors=getThemeColors();expect(colors).toEqual({});});it('should return all theme colors when no key is passed.',function(){getThemeConfig.mockReturnValueOnce({colors:{primary:'#ff0000'}});var colors=getThemeColors();expect(colors).toEqual({primary:'#ff0000'});});it('should return only a single theme color entry, matching the given key.',function(){getThemeConfig.mockReturnValueOnce({colors:{primary:'#ff0000',accent:'#47f'}});var colors=getThemeColors('accent');expect(colors).toEqual('#47f');});it('should return undefined if the requested color key does not exist.',function(){getThemeConfig.mockReturnValueOnce({colors:{primary:'#ff0000',accent:'#47f'}});var settings=getThemeColors('other');expect(settings).toBeUndefined();});});});
@@ -1,2 +0,0 @@
1
- import{getThemeConfig}from"../getThemeConfig";var mockAppConfig={beta:true};// Mock the config object using class getters
2
- jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get beta(){return mockAppConfig.beta;},get theme(){return mockAppConfig.theme;}};});describe('engage > core > config',function(){describe('getThemeConfig()',function(){it('should return all theme config props.',function(){mockAppConfig.theme='someThemeConfig';expect(getThemeConfig()).toEqual('someThemeConfig');delete mockAppConfig.theme;});it('should return an empty object if the app config is empty.',function(){expect(getThemeConfig()).toEqual({});});});});
@@ -1 +0,0 @@
1
- import{getThemeSettings}from"../getThemeSettings";import{getThemeConfig}from"../getThemeConfig";jest.mock("../getThemeConfig",function(){return{getThemeConfig:jest.fn()};});describe('engage > core > config',function(){describe('getThemeSettings()',function(){it('should return an empty object if no settings are available without using a key.',function(){getThemeConfig.mockReturnValueOnce({});var settings=getThemeSettings();expect(settings).toEqual({});});it('should return all theme settings when no key is passed.',function(){getThemeConfig.mockReturnValueOnce({settings:{currency:'USD',language:'en-US'}});var settings=getThemeSettings();expect(settings).toEqual({currency:'USD',language:'en-US'});});it('should return only a single theme settings entry, matching the given key.',function(){getThemeConfig.mockReturnValueOnce({settings:{currency:'USD',language:'en-US'}});var settings=getThemeSettings('currency');expect(settings).toEqual('USD');});it('should return undefined if the requested settings key does not exist.',function(){getThemeConfig.mockReturnValueOnce({settings:{currency:'USD',language:'en-US'}});var settings=getThemeSettings('other');expect(settings).toBeUndefined();});});});
@@ -1 +0,0 @@
1
- import{getThemeStyles}from"../getThemeStyles";import{getThemeConfig}from"../getThemeConfig";jest.mock("../getThemeConfig",function(){return{getThemeConfig:jest.fn()};});describe('engage > core > config',function(){describe('getThemeStyles()',function(){it('should return an empty object if no styles property exists',function(){getThemeConfig.mockReturnValueOnce({});var styles=getThemeStyles();expect(styles).toEqual({});});it('should return all styles if no key is given',function(){var mockStyles={'@shopgate/engage/product/ProductGrid':{color:'red'},'@shopgate/engage/product/ProductSlider':{color:'blue'}};getThemeConfig.mockReturnValueOnce({styles:mockStyles});var styles=getThemeStyles();expect(styles).toEqual(mockStyles);});it('should return specific styles if key is given',function(){var mockStyles={'@shopgate/engage/product/ProductGrid':{color:'red'},'@shopgate/engage/product/ProductSlider':{color:'blue'}};getThemeConfig.mockReturnValueOnce({styles:mockStyles});var styles=getThemeStyles('@shopgate/engage/product/ProductSlider');expect(styles).toEqual({color:'blue'});});it('should return undefined if key is no available',function(){getThemeConfig.mockReturnValueOnce({});var styles=getThemeStyles('keyNotAvailable');expect(styles).toBeUndefined();});});});
@@ -1 +0,0 @@
1
- import{getWidgetConfig}from"../getWidgetConfig";import{getPageConfig}from"../getPageConfig";jest.mock("../getPageConfig",function(){return{getPageConfig:jest.fn()};});var pagePattern='/requested/page';var widgetId='testWidgetId';describe('engage > core > config',function(){describe('getWidgetConfig()',function(){it('should return an empty object if no widgets are defined on the page.',function(){getPageConfig.mockReturnValueOnce({});var result=getWidgetConfig(pagePattern,widgetId);expect(result).toEqual({});});it('should return an empty object if the widget is not found.',function(){getPageConfig.mockReturnValueOnce({widgets:[]});expect(getWidgetConfig(pagePattern)).toEqual({});});it('should only return the first widget, which matches the given widgetId.',function(){getPageConfig.mockReturnValueOnce({widgets:[{id:'/some/other/page',name:'Other Widget'},{id:widgetId,name:'Correct Widget Id And First Found'},{id:widgetId,name:'Correct Widget Id But Not First'},{id:'/yet/another/widgetid',name:'Yet Another Widget'}]});expect(getWidgetConfig(pagePattern,widgetId)).toEqual({id:widgetId,name:'Correct Widget Id And First Found'});});it('should return the same config then an index of zero was given as if it was undefined.',function(){getPageConfig.mockReturnValue({widgets:[{id:widgetId,name:'Correct Widget Id And First Found'}]});var firstResult=getWidgetConfig(pagePattern,widgetId,0);expect(firstResult).toEqual(getWidgetConfig(pagePattern,widgetId,undefined));jest.resetAllMocks();});it('should only return the correct widget, which matches the given widgetId and given index.',function(){getPageConfig.mockReturnValueOnce({widgets:[{id:'/some/other/page',name:'Other Widget'},{id:widgetId,name:'Correct Widget Id Wrong Index'},{id:widgetId,name:'Correct Widget Id And Index'},{id:widgetId,name:'Correct Widget Id Too High Index'},{id:'/yet/another/widgetid',name:'Yet Another Widget'}]});expect(getWidgetConfig(pagePattern,widgetId,2)).toEqual({id:widgetId,name:'Correct Widget Id And Index'});});});});
@@ -1,3 +0,0 @@
1
- import{getWidgetSettings}from"../getWidgetSettings";import{getPageSettings}from"../getPageSettings";import{getWidgetConfig}from"../getWidgetConfig";jest.mock("../getPageSettings",function(){return{getPageSettings:jest.fn()};});jest.mock("../getWidgetConfig",function(){return{getWidgetConfig:jest.fn()};});var pagePattern='/requested/page';var widgetId='testWidgetId';describe('engage > core > config',function(){describe('getWidgetSettings()',function(){beforeEach(function(){jest.resetAllMocks();});it('should return an empty object when no widget settings are available in any scope.',function(){getPageSettings.mockReturnValueOnce(undefined);getWidgetConfig.mockReturnValueOnce({});expect(getWidgetSettings(pagePattern,widgetId)).toEqual({});});it('should return all local settings if there is nothing to inherit from.',function(){getPageSettings.mockReturnValueOnce(undefined);getWidgetConfig.mockReturnValueOnce({id:widgetId,name:'WidgetName',settings:{all:{widget:'settings'}}});expect(getWidgetSettings(pagePattern,widgetId)).toEqual({all:{widget:'settings'}});});it('should pass down the params to the lower level functions for filtered inheritance.',function(){getPageSettings.mockReturnValueOnce({});getWidgetConfig.mockReturnValueOnce({});getWidgetSettings(pagePattern,widgetId,7);expect(getPageSettings).toBeCalledWith(pagePattern,widgetId);expect(getPageSettings).toBeCalledTimes(1);expect(getWidgetConfig).toBeCalledWith(pagePattern,widgetId,7);expect(getWidgetConfig).toBeCalledTimes(1);});it('should inherit matching keys from page settings.',function(){// Return unpacked object, not containing the key anymore, because the match is guaranteed
2
- getPageSettings.mockReturnValueOnce({things:{to:{inherit:'some inherited value'}}});getWidgetConfig.mockReturnValueOnce({});expect(getWidgetSettings(pagePattern,widgetId)).toEqual({things:{to:{inherit:'some inherited value'}}});});it('should inherit and mix properties for keys matching page and widget settings.',function(){// Return unpacked object, not containing the key anymore, because the match is guaranteed
3
- getPageSettings.mockReturnValueOnce({things:{toMix:{inherit:'some inherited value',keep:'low priority'}}});getWidgetConfig.mockReturnValueOnce({settings:{things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'}});expect(getWidgetSettings(pagePattern,widgetId)).toEqual({things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting',inherit:'some inherited value'}},moreToKeep:'keep full key'});});it('should not fail when there is nothing to inherit from.',function(){getPageSettings.mockReturnValueOnce(undefined);getWidgetConfig.mockReturnValueOnce({settings:{things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'}});expect(getWidgetSettings(pagePattern,widgetId)).toEqual({things:{toMix:{keep:'high priority',alsoKeep:'non-conflicting'}},moreToKeep:'keep full key'});});});});
@@ -1 +0,0 @@
1
- export var i18n={ready:true,init:function init(){},text:function text(input){return input||'';},price:function price(){return'p';},number:function number(){return'n';},date:function date(){return'd';},time:function time(){return't';}};
@@ -1 +0,0 @@
1
- import{i18n}from"../i18n";jest.unmock("../i18n");var mockedWarn=jest.fn();var mockedError=jest.fn();jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{warn:function warn(){return mockedWarn.apply(void 0,arguments);},error:function error(){return mockedError.apply(void 0,arguments);}}};});describe('i18n',function(){beforeEach(function(){jest.clearAllMocks();});var methods=['text','price','date','time','number'];methods.forEach(function(m){it("should log error when i18n.".concat(m," is used before init"),function(){i18n[m]();expect(mockedError).toHaveBeenCalled();});});it('should translate',function(){var locales={test:{string:'Test string: {bar}'}};i18n.init({locales:locales,lang:'en-US'});expect(i18n.text('test.string',{bar:'testProperty'})).toBe('Test string: testProperty');expect(i18n.price(1000,'USD',2)).toBe('$1,000.00');expect(i18n.date(new Date(0).getDate())).toBe('Jan 1, 1970');expect(i18n.time(new Date(0).getDate()).match(/PM|AM/).length).toBe(1);expect(i18n.number(1000,2)).toBe('1,000.00');});it('should consider a custom currency locale',function(){i18n.init({locales:{},lang:'en-US',currencyLocale:'en-IL'});expect(i18n.price(1000,'EUR',2)).toBe('€1,000.00');});it('should warn on another init',function(){i18n.init({});expect(mockedWarn).toHaveBeenCalled();});it('should return default text for missing translation',function(){var locales={test:{string:'Test string: {bar}'}};i18n.init({locales:locales,lang:'en-US'});expect(i18n.textWithDefault('test.missing','Default text')).toBe('Default text');});});
@@ -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);}import broadcastEvent from'@shopgate/pwa-core/commands/broadcastEvent';import{updateLegacyNavigationBar}from"../updateLegacyNavigationBar";jest.mock('@shopgate/pwa-core/commands/broadcastEvent',function(){return jest.fn();});describe('updateLegacyNavigationBar()',function(){it('should broadcast when called without parameters',function(){updateLegacyNavigationBar();expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{targetTab:'main',styles:{}}]});});it('should broadcast when called with colors that contain a bright background',function(){var options={color:'#000',background:'#fff',buttonColor:'red',buttonColorDisabled:'blue'};updateLegacyNavigationBar(options);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{targetTab:'main',styles:_extends({},options,{statusBarBackground:options.background}),statusBarStyle:'dark'}]});});it('should broadcast when called with colors that contain a light background',function(){var options={background:'#000'};updateLegacyNavigationBar(options);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{targetTab:'main',styles:_extends({},options,{statusBarBackground:options.background}),statusBarStyle:'light'}]});});it('should broadcast when called with a status bar background',function(){var options={statusBarBackground:'#fff'};updateLegacyNavigationBar(options);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{targetTab:'main',styles:_extends({},options),statusBarStyle:'dark'}]});});it('should broadcast when called with custom targetTab and statusBarStyle',function(){var options={statusBarStyle:'dark',targetTab:'cart'};updateLegacyNavigationBar(options);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{targetTab:'cart',styles:{},statusBarStyle:'dark'}]});});it('should broadcast when called with the isDefault option',function(){var options={isDefault:true,statusBarStyle:'dark',targetTab:'cart',statusBarBackground:'red'};updateLegacyNavigationBar(options);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBarStyle',parameters:[{isDefault:true,targetTab:'cart',styles:{statusBarBackground:'red'},statusBarStyle:'dark'}]});});});
@@ -1,5 +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);}import React from'react';/**
2
- * Mock for the withWidgetSettings HOC.
3
- * @param {Function} WrappedComponent The react component to wrap.
4
- * @returns {JSX}
5
- */export function withWidgetSettings(WrappedComponent){var settings={mocked:'widgetSetting'};return function(props){return/*#__PURE__*/React.createElement(WrappedComponent,_extends({widgetSettings:settings},props));};}
@@ -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);}import React from'react';import{mount}from'enzyme';import{withApp}from"../withApp";var mockApp={some:'prop'};var mockContext=jest.fn().mockReturnValue(mockApp);jest.mock("../../contexts/AppContext",function(){return{Consumer:function Consumer(_ref){var children=_ref.children;return children(mockContext());}};});// eslint-disable-next-line require-jsdoc
2
- var MockComponent=function MockComponent(){return null;};describe('engage > core > hocs > withApp',function(){beforeEach(function(){jest.clearAllMocks();});it('should inject a property called "app" into the component',function(){var ComposedComponent=withApp(MockComponent);var wrapper=mount(/*#__PURE__*/React.createElement(ComposedComponent,{someProp:true}));expect(wrapper).toMatchSnapshot();expect(wrapper.find(MockComponent).props()).toEqual({someProp:true,app:_extends({},mockApp)});});});
@@ -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);}import React from'react';import{mount}from'enzyme';import{withCurrentProduct}from"../withCurrentProduct";var mockCurrentProduct={id:'123',name:'acme',price:{currency:'EUR',unitPrice:22.95,unitPriceStriked:25.95}};var mockContext=jest.fn().mockReturnValue(mockCurrentProduct);jest.mock('@shopgate/pwa-common/context',function(){return{ThemeContext:{Consumer:function Consumer(_ref){var themeChildren=_ref.children;return themeChildren({contexts:{ProductContext:{Consumer:function Consumer(_ref2){var productChildren=_ref2.children;return productChildren(mockContext());}}}});}}};});// eslint-disable-next-line require-jsdoc
2
- var MockComponent=function MockComponent(){return null;};describe('engage > core > hocs > withCurrentProduct',function(){beforeEach(function(){jest.clearAllMocks();});it('should inject the context properties into the component',function(){var ComposedComponent=withCurrentProduct(MockComponent);var wrapper=mount(/*#__PURE__*/React.createElement(ComposedComponent,{someProp:true}));expect(wrapper).toMatchSnapshot();expect(wrapper.find(MockComponent).props()).toEqual(_extends({someProp:true},mockCurrentProduct));});it('should inject a single property with the context into the component',function(){var ComposedComponent=withCurrentProduct(MockComponent,{prop:'product'});var wrapper=mount(/*#__PURE__*/React.createElement(ComposedComponent,{someProp:true}));expect(wrapper).toMatchSnapshot();expect(wrapper.find(MockComponent).props()).toEqual({someProp:true,product:_extends({},mockCurrentProduct)});});});
@@ -1 +0,0 @@
1
- /* eslint-disable require-jsdoc, react/prop-types */import React,{createRef}from'react';import{renderIntoDocument}from'react-dom/test-utils';import{shallow}from'enzyme';import{withForwardedRef}from"../withForwardedRef";var MockComponent=function MockComponent(_ref){var children=_ref.children,className=_ref.className,forwardedRef=_ref.forwardedRef;return/*#__PURE__*/React.createElement("div",{className:className,ref:forwardedRef},children);};describe('engage > core > hocs > withForwardedRef',function(){it('should render',function(){var ComposedComponent=withForwardedRef(MockComponent);var ref=/*#__PURE__*/createRef();var wrapper=shallow(/*#__PURE__*/React.createElement(ComposedComponent,{className:"foo",ref:ref},"Testing 123"));expect(wrapper).toMatchSnapshot();expect(wrapper.props()).toEqual({className:'foo',children:'Testing 123',forwardedRef:{current:null}});});it('should inject the ref with a custom prop name',function(){var ComposedComponent=withForwardedRef(MockComponent,{prop:'custom'});var ref=/*#__PURE__*/createRef();var wrapper=shallow(/*#__PURE__*/React.createElement(ComposedComponent,{className:"foo",ref:ref},"Testing 123"));expect(wrapper).toMatchSnapshot();expect(wrapper.props()).toEqual({className:'foo',children:'Testing 123',custom:{current:null}});});it('should create a ref that points to a HTMLDivElement',function(){var ComposedComponent=withForwardedRef(MockComponent);var ref=/*#__PURE__*/createRef();renderIntoDocument(/*#__PURE__*/React.createElement(ComposedComponent,{className:"foo",ref:ref},"Testing 123"));expect(ref.current).toBeInstanceOf(HTMLDivElement);});});/* eslint-enable require-jsdoc, react/prop-types */