@shopgate/pwa-common 6.22.0-beta.3 → 6.22.0-beta.5
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.
- package/CHANGELOG.md +199 -0
- package/action-creators/app/index.js +5 -1
- package/actions/client/fetchClientInformation.js +1 -1
- package/constants/ActionTypes.js +1 -1
- package/package.json +3 -3
- package/streams/app.js +5 -5
- package/subscriptions/error.js +2 -2
- package/actions/app/handleLink.spec.js +0 -1
- package/actions/modal/showModal.spec.js +0 -10
- package/actions/router/historyRedirect.spec.js +0 -1
- package/collections/AuthRoutes.spec.js +0 -1
- package/collections/EmbeddedMedia.spec.js +0 -4
- package/collections/Redirects.spec.js +0 -1
- package/collections/media-providers/MediaProvider.spec.js +0 -5
- package/collections/media-providers/Vimeo.spec.js +0 -11
- package/collections/media-providers/YouTube.spec.js +0 -5
- package/components/ProductCharacteristics/helpers/index.spec.js +0 -12
- package/components/ScannerContainer/index.spec.js +0 -5
- package/components/Widgets/helpers/shouldShowWidget.spec.js +0 -1
- package/helpers/config/__mocks__/index.js +0 -1
- package/helpers/dom/index.spec.js +0 -1
- package/helpers/html/handleDOM.spec.js +0 -1
- package/helpers/i18n/getNumberFormatter.spec.js +0 -3
- package/helpers/i18n/getTranslator.spec.js +0 -1
- package/helpers/i18n/mergeTranslations.spec.js +0 -2
- package/helpers/legacy/index.spec.js +0 -1
- package/helpers/mocks/mockRenderOptions.js +0 -2
- package/helpers/mocks/spec.js +0 -1
- package/helpers/portals/__tests__/routePortals.js +0 -3
- package/helpers/redux/__tests__/compareObjects.spec.js +0 -2
- package/helpers/redux/__tests__/generateSortedHash.spec.js +0 -1
- package/helpers/redux/__tests__/mutable.spec.js +0 -5
- package/helpers/redux/__tests__/shouldFetchData.spec.js +0 -1
- package/providers/loading/index.spec.js +0 -7
- package/reducers/client/connectivity.spec.js +0 -1
- package/reducers/client/info.spec.js +0 -1
- package/reducers/index.spec.js +0 -6
- package/selectors/client.spec.js +0 -9
- package/selectors/modal.spec.js +0 -1
- package/selectors/router.spec.js +0 -1
- package/streams/app.spec.js +0 -1
- package/streams/user.spec.js +0 -5
- package/subscriptions/app.spec.js +0 -1
- package/subscriptions/helpers/buildRegisterUrl.spec.js +0 -1
- package/subscriptions/helpers/clearUpInAppBrowser.spec.js +0 -1
- package/subscriptions/helpers/handleLinks.spec.js +0 -1
- package/subscriptions/helpers/pipeline.spec.js +0 -1
- package/subscriptions/router.spec.js +0 -21
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,199 @@
|
|
|
1
|
+
|
|
2
|
+
# Changelog
|
|
3
|
+
|
|
4
|
+
## [Unreleased]
|
|
5
|
+
### Added
|
|
6
|
+
- New `Portal` constant `PAGE_LOGIN` and `PAGE_LOGIN_REGISTER_LINK` added.
|
|
7
|
+
|
|
8
|
+
### [2.4.0](https://github.com/shopgate/pwa-common/compare/v2.3.0...v2.4.0) - February 07, 2018
|
|
9
|
+
#### Added
|
|
10
|
+
- Toast messages supports an action button functionality
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
### [2.3.0](https://github.com/shopgate/pwa-common/compare/v2.2.0...v2.3.0) - February 07, 2018
|
|
15
|
+
#### Added
|
|
16
|
+
* `mergeTranslations` helper function
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
### [2.2.0](https://github.com/shopgate/pwa-common/compare/v2.1.2...v2.2.0) - February 06, 2018
|
|
21
|
+
#### Added
|
|
22
|
+
- `generateResultHash` now includes a `includeFilters` parameter.
|
|
23
|
+
#### Changed
|
|
24
|
+
- Extended `unsetViewLoading` with `flush` variable that forces the action to reset loading view counter.
|
|
25
|
+
|
|
26
|
+
---
|
|
27
|
+
|
|
28
|
+
### [2.1.2](https://github.com/shopgate/pwa-common/compare/v2.1.1...v2.1.2) - February 05, 2018
|
|
29
|
+
#### Added
|
|
30
|
+
- Data attribute to Button component for automated testing
|
|
31
|
+
- Default `app.json` for test mode
|
|
32
|
+
- The `successLogin` action is now dispatched if a login pipeline request fails because the user is already logged in at the backed
|
|
33
|
+
|
|
34
|
+
#### Fixed
|
|
35
|
+
- Invalid portal components are now ignored
|
|
36
|
+
|
|
37
|
+
---
|
|
38
|
+
### [2.1.1](https://github.com/shopgate/pwa-common/compare/v2.1.0...v2.1.1) - February 01, 2018
|
|
39
|
+
#### Added
|
|
40
|
+
- Data attribute to Button component for automated testing
|
|
41
|
+
- Default `app.json` for test mode
|
|
42
|
+
|
|
43
|
+
#### Fixed
|
|
44
|
+
- Invalid portal components are now ignored
|
|
45
|
+
|
|
46
|
+
---
|
|
47
|
+
|
|
48
|
+
### [2.1.0](https://github.com/shopgate/pwa-common/compare/v2.0.2...v2.1.0) - January 30, 2018
|
|
49
|
+
#### Added
|
|
50
|
+
- `Portal` component and `PortalCollection` helper.
|
|
51
|
+
|
|
52
|
+
### [2.0.2](https://github.com/shopgate/pwa-common/compare/v2.0.1...v2.0.2) - January 29, 2018
|
|
53
|
+
#### Removed
|
|
54
|
+
- Widget type conversion
|
|
55
|
+
|
|
56
|
+
---
|
|
57
|
+
|
|
58
|
+
### [2.0.1](https://github.com/shopgate/pwa-common/compare/v2.0.0...v2.0.1) - January 25, 2018
|
|
59
|
+
#### Changed
|
|
60
|
+
- Removed `/favorite_list` from legacy links whitelist
|
|
61
|
+
|
|
62
|
+
#### Fixed
|
|
63
|
+
- Fixed `isNumeric` and `isNumber` problem with falsy validations for numeric strings.
|
|
64
|
+
|
|
65
|
+
---
|
|
66
|
+
### [2.0.0](https://github.com/shopgate/pwa-common/compare/v1.3.0...v2.0.0) - January 24, 2018
|
|
67
|
+
#### Added
|
|
68
|
+
- A new stream that emits when the "index" route was opened.
|
|
69
|
+
- A new history subscriber that listens on the opening of "index" routes and resets the history.
|
|
70
|
+
- Support for the "className" prop in the i18n FormatPrice component to support styling.
|
|
71
|
+
- Toast component.
|
|
72
|
+
|
|
73
|
+
#### Changed
|
|
74
|
+
- Combined related action creators to single files and updated the depending modules.
|
|
75
|
+
|
|
76
|
+
---
|
|
77
|
+
|
|
78
|
+
### [1.3.0](https://github.com/shopgate/pwa-common/compare/v1.2.0...v1.3.0) - January 08, 2018
|
|
79
|
+
|
|
80
|
+
#### Added
|
|
81
|
+
- Observable `clientInformationDidUpdate$`
|
|
82
|
+
|
|
83
|
+
#### Fixed
|
|
84
|
+
- Images inside the product gallery are now shown on iOS 10
|
|
85
|
+
|
|
86
|
+
---
|
|
87
|
+
|
|
88
|
+
### [1.2.0](https://github.com/shopgate/pwa-common/compare/v1.1.3...v1.2.0) - January 08, 2018
|
|
89
|
+
|
|
90
|
+
#### Added
|
|
91
|
+
- Constant `CHECKOUT_PATH`
|
|
92
|
+
- Constant `LEGACY_URL`
|
|
93
|
+
- Constant `URL_TYPE_REGISTER`
|
|
94
|
+
- Selector `getHistoryLocation`
|
|
95
|
+
- Observable `openedRegisterLink`
|
|
96
|
+
- Opening the `/register` route will now trigger the fetching of a registration URL, if one is available
|
|
97
|
+
|
|
98
|
+
#### Changed
|
|
99
|
+
- The localstorage key now has the following format: `sgCloud-<appId>-<themeName>`. Different themes will no longer share the same storage space
|
|
100
|
+
- Converted `<List>` to be a stateless component
|
|
101
|
+
|
|
102
|
+
#### Removed
|
|
103
|
+
- Custom router lifecycle events `routeWillEnter` and `routeWillLeave`
|
|
104
|
+
|
|
105
|
+
---
|
|
106
|
+
|
|
107
|
+
### [1.1.3](https://github.com/shopgate/pwa-common/compare/v1.1.2...v1.1.3) - December 28, 2017
|
|
108
|
+
|
|
109
|
+
#### Fixed
|
|
110
|
+
- Updated `@shopgate/pwa-core` peer dependency to 1.1.x
|
|
111
|
+
|
|
112
|
+
---
|
|
113
|
+
|
|
114
|
+
### [1.1.2](https://github.com/shopgate/pwa-common/compare/v1.1.1...v1.1.2) - December 22, 2017
|
|
115
|
+
|
|
116
|
+
#### Changed
|
|
117
|
+
- Updated `@shopgate/pwa-core` to ^1.1.0
|
|
118
|
+
|
|
119
|
+
---
|
|
120
|
+
|
|
121
|
+
### [1.1.1](https://github.com/shopgate/pwa-common/compare/v1.1.0...v1.1.1) - December 22, 2017
|
|
122
|
+
|
|
123
|
+
#### Changed
|
|
124
|
+
- Reverted `react-id-swiper` to 1.4.0
|
|
125
|
+
|
|
126
|
+
---
|
|
127
|
+
|
|
128
|
+
### [1.1.0](https://github.com/shopgate/pwa-common/compare/v1.0.12...v1.1.0) - December 22, 2017
|
|
129
|
+
|
|
130
|
+
#### Added
|
|
131
|
+
- React 16 support
|
|
132
|
+
|
|
133
|
+
#### Changed
|
|
134
|
+
- Updated `@shopgate/eslint-config` to ^1.0.3
|
|
135
|
+
- Updated `@shopgate/pwa-unit-test` to ^1.3.0
|
|
136
|
+
- Updated `react` to ^16.2.0
|
|
137
|
+
- Updated `react-dom` to ^16.2.0
|
|
138
|
+
- Updated `react-id-swiper` to ^1.5.7
|
|
139
|
+
- Updated `react-tap-event-plugin` to ^3.0.2
|
|
140
|
+
- Updated `lint-staged` to ^4.3.0
|
|
141
|
+
|
|
142
|
+
---
|
|
143
|
+
|
|
144
|
+
### [1.0.12](https://github.com/shopgate/pwa-common/compare/v1.0.11...v1.0.12) - December 21, 2017
|
|
145
|
+
|
|
146
|
+
#### Added
|
|
147
|
+
- isAndroid selector
|
|
148
|
+
- Callback for closeInAppBrowser that will redirect to the received location from the event
|
|
149
|
+
|
|
150
|
+
#### Changed
|
|
151
|
+
- Updated `@shopgate/pwa-core` to ^1.0.5
|
|
152
|
+
|
|
153
|
+
---
|
|
154
|
+
|
|
155
|
+
### [1.0.11](https://github.com/shopgate/pwa-common/compare/v1.0.5...v1.0.11) - December 15, 2017
|
|
156
|
+
|
|
157
|
+
#### Added
|
|
158
|
+
- getClientInformation selector
|
|
159
|
+
|
|
160
|
+
---
|
|
161
|
+
|
|
162
|
+
### [1.0.5](https://github.com/shopgate/pwa-common/compare/v1.0.4...v1.0.5) - December 11, 2017
|
|
163
|
+
|
|
164
|
+
#### Changed
|
|
165
|
+
- Updated `@shopgate/pwa-core` to ^1.0.4
|
|
166
|
+
|
|
167
|
+
---
|
|
168
|
+
|
|
169
|
+
### [1.0.4](https://github.com/shopgate/pwa-common/compare/v1.0.3...v1.0.4) - December 11, 2017
|
|
170
|
+
|
|
171
|
+
#### Added
|
|
172
|
+
- Added a default callback for `viewDidDisappear`
|
|
173
|
+
|
|
174
|
+
#### Changed
|
|
175
|
+
- Updated `@shopgate/pwa-core` to ^1.0.3
|
|
176
|
+
|
|
177
|
+
#### Removed
|
|
178
|
+
- checkoutSuccess event registration on app start event
|
|
179
|
+
|
|
180
|
+
---
|
|
181
|
+
|
|
182
|
+
### [1.0.3](https://github.com/shopgate/pwa-common/compare/v1.0.2...v1.0.3) - December 7, 2017
|
|
183
|
+
|
|
184
|
+
#### Removed
|
|
185
|
+
- Default subscriptions to Observables
|
|
186
|
+
|
|
187
|
+
---
|
|
188
|
+
|
|
189
|
+
### [1.0.2](https://github.com/shopgate/pwa-common/compare/v1.0.1...v1.0.2) - December 7, 2017
|
|
190
|
+
|
|
191
|
+
#### Changed
|
|
192
|
+
- Updated `@shopgate/pwa-core` to ^1.0.0
|
|
193
|
+
|
|
194
|
+
---
|
|
195
|
+
|
|
196
|
+
### [1.0.1](https://github.com/shopgate/pwa-common/compare/v1.0.0...v1.0.1) - December 7, 2017
|
|
197
|
+
|
|
198
|
+
#### Changed
|
|
199
|
+
- Added a custom travis template for Slack
|
|
@@ -1,4 +1,8 @@
|
|
|
1
|
-
import{APP_WILL_START,APP_DID_START,PWA_DID_APPEAR,PWA_DID_DISAPPEAR,RESET_APP,WILL_REGISTER_LINK_EVENTS,DID_REGISTER_LINK_EVENTS,OPEN_DEEP_LINK,OPEN_PUSH_NOTIFICATION,OPEN_UNIVERSAL_LINK}from"../../constants/ActionTypes";/**
|
|
1
|
+
import{APP_WILL_INIT,APP_WILL_START,APP_DID_START,PWA_DID_APPEAR,PWA_DID_DISAPPEAR,RESET_APP,WILL_REGISTER_LINK_EVENTS,DID_REGISTER_LINK_EVENTS,OPEN_DEEP_LINK,OPEN_PUSH_NOTIFICATION,OPEN_UNIVERSAL_LINK}from"../../constants/ActionTypes";/**
|
|
2
|
+
* Creates the dispatched APP_WILL_INIT action object.
|
|
3
|
+
* @param {Object} location The initial history entry location.
|
|
4
|
+
* @return {Object} The dispatched action object.
|
|
5
|
+
*/export var appWillInit=function appWillInit(location){return{type:APP_WILL_INIT,location:location};};/**
|
|
2
6
|
* Creates the dispatched APP_WILL_START action object.
|
|
3
7
|
* @param {Object} location The initial history entry location.
|
|
4
8
|
* @return {Object} The dispatched action object.
|
|
@@ -1,4 +1,4 @@
|
|
|
1
1
|
import{hasSGJavaScriptBridge,defaultClientInformation,getWebStorageEntry}from'@shopgate/pwa-core';import{requestClientInformation,receiveClientInformation,errorClientInformation}from"../../action-creators/client";/**
|
|
2
2
|
* Requests the client information from the web storage.
|
|
3
3
|
* @return {Function} A redux thunk.
|
|
4
|
-
*/function fetchClientInformation(){return function(dispatch){dispatch(requestClientInformation());if(!hasSGJavaScriptBridge()){dispatch(receiveClientInformation(defaultClientInformation));return;}getWebStorageEntry({name:'clientInformation'}).then(function(response){return dispatch(receiveClientInformation(response.value));})["catch"](function(){dispatch(errorClientInformation());});};}export default fetchClientInformation;
|
|
4
|
+
*/function fetchClientInformation(){return function(dispatch){dispatch(requestClientInformation());if(!hasSGJavaScriptBridge()){dispatch(receiveClientInformation(defaultClientInformation));return Promise.resolve(defaultClientInformation);}return getWebStorageEntry({name:'clientInformation'}).then(function(response){return dispatch(receiveClientInformation(response.value));})["catch"](function(){dispatch(errorClientInformation());});};}export default fetchClientInformation;
|
package/constants/ActionTypes.js
CHANGED
|
@@ -4,7 +4,7 @@
|
|
|
4
4
|
* ------- CLIENT CONNECTIVITY -------
|
|
5
5
|
*/export var RECEIVE_CLIENT_CONNECTIVITY='RECEIVE_CLIENT_CONNECTIVITY';/**
|
|
6
6
|
* ------- APP -------
|
|
7
|
-
*/export var APP_DID_START='APP_DID_START';export var APP_WILL_START='APP_WILL_START';export var WILL_REGISTER_LINK_EVENTS='WILL_REGISTER_LINK_EVENTS';export var DID_REGISTER_LINK_EVENTS='DID_REGISTER_LINK_EVENTS';export var RESET_APP='RESET_APP';export var PWA_DID_APPEAR='PWA_DID_APPEAR';export var PWA_DID_DISAPPEAR='PWA_DID_DISAPPEAR';/**
|
|
7
|
+
*/export var APP_DID_START='APP_DID_START';export var APP_WILL_START='APP_WILL_START';export var APP_WILL_INIT='APP_WILL_INIT';export var WILL_REGISTER_LINK_EVENTS='WILL_REGISTER_LINK_EVENTS';export var DID_REGISTER_LINK_EVENTS='DID_REGISTER_LINK_EVENTS';export var RESET_APP='RESET_APP';export var PWA_DID_APPEAR='PWA_DID_APPEAR';export var PWA_DID_DISAPPEAR='PWA_DID_DISAPPEAR';/**
|
|
8
8
|
* ------- MENU -------
|
|
9
9
|
*/export var REQUEST_MENU='REQUEST_MENU';export var RECEIVE_MENU='RECEIVE_MENU';export var ERROR_MENU='ERROR_MENU';/**
|
|
10
10
|
* ------- VIEW -------
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopgate/pwa-common",
|
|
3
|
-
"version": "6.22.0-beta.
|
|
3
|
+
"version": "6.22.0-beta.5",
|
|
4
4
|
"description": "Common library for the Shopgate Connect PWA.",
|
|
5
5
|
"license": "Apache-2.0",
|
|
6
6
|
"author": "Shopgate <support@shopgate.com>",
|
|
@@ -16,7 +16,7 @@
|
|
|
16
16
|
],
|
|
17
17
|
"dependencies": {
|
|
18
18
|
"@sentry/browser": "^4.6.3",
|
|
19
|
-
"@shopgate/pwa-benchmark": "6.22.0-beta.
|
|
19
|
+
"@shopgate/pwa-benchmark": "6.22.0-beta.5",
|
|
20
20
|
"@virtuous/conductor": "~2.4.0",
|
|
21
21
|
"@virtuous/react-conductor": "~2.4.0",
|
|
22
22
|
"@virtuous/redux-persister": "1.1.0-beta.7",
|
|
@@ -44,7 +44,7 @@
|
|
|
44
44
|
"url-search-params": "^0.10.0"
|
|
45
45
|
},
|
|
46
46
|
"devDependencies": {
|
|
47
|
-
"@shopgate/pwa-core": "6.22.0-beta.
|
|
47
|
+
"@shopgate/pwa-core": "6.22.0-beta.5",
|
|
48
48
|
"lodash": "^4.17.4",
|
|
49
49
|
"prop-types": "~15.7.2",
|
|
50
50
|
"react": "~16.12.0",
|
package/streams/app.js
CHANGED
|
@@ -1,11 +1,11 @@
|
|
|
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{getCurrentRoute}from"../selectors/router";import{APP_DID_START,APP_WILL_START,PWA_DID_APPEAR,PWA_DID_DISAPPEAR}from"../constants/ActionTypes";import{main$}from"./main";/**
|
|
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{getCurrentRoute}from"../selectors/router";import{APP_WILL_INIT,APP_DID_START,APP_WILL_START,PWA_DID_APPEAR,PWA_DID_DISAPPEAR}from"../constants/ActionTypes";import{main$}from"./main";export var appWillInit$=main$.filter(function(_ref){var action=_ref.action;return action.type===APP_WILL_INIT;});/**
|
|
2
2
|
* Gets triggered before the app starts.
|
|
3
3
|
* @type {Observable}
|
|
4
|
-
*/export var appWillStart$=main$.filter(function(
|
|
4
|
+
*/export var appWillStart$=main$.filter(function(_ref2){var action=_ref2.action;return action.type===APP_WILL_START;});/**
|
|
5
5
|
* Gets triggered when the app starts.
|
|
6
6
|
* @type {Observable}
|
|
7
|
-
*/export var appDidStart$=main$.filter(function(
|
|
7
|
+
*/export var appDidStart$=main$.filter(function(_ref3){var action=_ref3.action;return action.type===APP_DID_START;});/**
|
|
8
8
|
* Emits when the PWA appeared again after navigating back from a legacy page.
|
|
9
|
-
*/export var pwaDidAppear$=main$.filter(function(
|
|
9
|
+
*/export var pwaDidAppear$=main$.filter(function(_ref4){var action=_ref4.action;return action.type===PWA_DID_APPEAR;}).map(function(params){return _extends({},params,{action:_extends({},params.action,{route:getCurrentRoute(params.getState())})});});/**
|
|
10
10
|
* Emits when the PWA disappears
|
|
11
|
-
*/export var pwaDidDisappear$=main$.filter(function(
|
|
11
|
+
*/export var pwaDidDisappear$=main$.filter(function(_ref5){var action=_ref5.action;return action.type===PWA_DID_DISAPPEAR;}).map(function(params){return _extends({},params,{action:_extends({},params.action,{route:getCurrentRoute(params.getState())})});});
|
package/subscriptions/error.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import after from'lodash/after';import before from'lodash/before';import over from'lodash/over';import{init,configureScope,captureException,captureMessage,captureEvent,withScope,Severity as SentrySeverity}from'@sentry/browser';import{EBIGAPI,emitter,errorManager,ETIMEOUT,ENETUNREACH,EUNKNOWN,EFAVORITE}from'@shopgate/pwa-core';import{SOURCE_TRACKING,SOURCE_CONSOLE,Severity}from'@shopgate/pwa-core/constants/ErrorManager';import{// eslint-disable-next-line import/no-named-default
|
|
2
|
-
default as appConfig,themeName,pckVersion}from"../helpers/config";import{env}from"../helpers/environment";import{transformGeneralPipelineError}from"./helpers/pipeline";import{historyPop}from"../actions/router";import showModal from"../actions/modal/showModal";import{getUserData}from"../selectors/user";import{userDidUpdate$}from"../streams/user";import{clientInformationDidUpdate$}from"../streams/client";import{appWillStart$,appDidStart$}from"../streams/app";import{appError$,pipelineError$}from"../streams/error";import{getRouterStack}from"../selectors/router";import{MODAL_PIPELINE_ERROR}from"../constants/ModalTypes";import ToastProvider from"../providers/toast";/**
|
|
2
|
+
default as appConfig,themeName,pckVersion}from"../helpers/config";import{env}from"../helpers/environment";import{transformGeneralPipelineError}from"./helpers/pipeline";import{historyPop}from"../actions/router";import showModal from"../actions/modal/showModal";import{getUserData}from"../selectors/user";import{userDidUpdate$}from"../streams/user";import{clientInformationDidUpdate$}from"../streams/client";import{appWillInit$,appWillStart$,appDidStart$}from"../streams/app";import{appError$,pipelineError$}from"../streams/error";import{getRouterStack}from"../selectors/router";import{MODAL_PIPELINE_ERROR}from"../constants/ModalTypes";import ToastProvider from"../providers/toast";/**
|
|
3
3
|
* App errors subscriptions.
|
|
4
4
|
* @param {Function} subscribe The subscribe function.
|
|
5
5
|
*/export default(function(subscribe){var _severityMap;/** Set general error transformations */subscribe(appWillStart$,function(){errorManager.setMessage({code:EUNKNOWN,message:transformGeneralPipelineError}).setMessage({code:EBIGAPI,message:transformGeneralPipelineError}).setMessage({code:ETIMEOUT,message:'modal.body_error'}).setMessage({code:ENETUNREACH,message:'modal.body_error'}).setMessage({code:EFAVORITE,message:'favorites.error_general'});});/** Show a message to the user in case of pipeline error */subscribe(pipelineError$,function(_ref){var dispatch=_ref.dispatch,action=_ref.action,events=_ref.events;var error=action.error;var message=error.message,code=error.code,context=error.context,meta=error.meta;/** Show modal thunk */var showModalError=function showModalError(){dispatch(showModal({confirm:'modal.ok',dismiss:null,title:null,message:message,type:MODAL_PIPELINE_ERROR,params:{pipeline:context,request:meta.input,message:meta.message,code:code}}));};var shouldShowToast=message==='error.general';if([ETIMEOUT,ENETUNREACH].includes(code)&&message==='modal.body_error'){shouldShowToast=true;}// It was transformed general error. let it popup after 10 toast clicks
|
|
@@ -7,7 +7,7 @@ if(shouldShowToast){var showToastAfter=after(9,showModalError);// Recursively sh
|
|
|
7
7
|
var showToast=before(10,function(){events.emit(ToastProvider.ADD,{id:'pipeline.error',message:'error.general',action:over([showToast,showToastAfter])});});showToast();return;}showModalError();});// This subscription is always active despite sentry activation
|
|
8
8
|
subscribe(appError$,function(_ref2){var dispatch=_ref2.dispatch;// Show modal to user
|
|
9
9
|
dispatch(showModal({confirm:null,message:'modal.body_error',title:'modal.title_error'}));dispatch(historyPop());});var _appConfig$sentry=appConfig.sentry,enabled=_appConfig$sentry.enabled,level=_appConfig$sentry.level,sampleRate=_appConfig$sentry.sampleRate;// Is not enabled
|
|
10
|
-
if(!enabled){return;}var severityMap=(_severityMap={},_defineProperty(_severityMap,Severity.Fatal,SentrySeverity.Fatal),_defineProperty(_severityMap,Severity.Error,SentrySeverity.Error),_defineProperty(_severityMap,Severity.Critical,SentrySeverity.Critical),_defineProperty(_severityMap,Severity.Warning,SentrySeverity.Warning),_defineProperty(_severityMap,Severity.Info,SentrySeverity.Info),_defineProperty(_severityMap,Severity.Debug,SentrySeverity.Debug),_severityMap);var trackedSeverities=Object.getOwnPropertySymbols(severityMap).map(function(s){return severityMap[s];});var minSeverityIndex=trackedSeverities.indexOf(level);if(minSeverityIndex>-1){trackedSeverities=trackedSeverities.slice(0,minSeverityIndex+1);}subscribe(
|
|
10
|
+
if(!enabled){return;}var severityMap=(_severityMap={},_defineProperty(_severityMap,Severity.Fatal,SentrySeverity.Fatal),_defineProperty(_severityMap,Severity.Error,SentrySeverity.Error),_defineProperty(_severityMap,Severity.Critical,SentrySeverity.Critical),_defineProperty(_severityMap,Severity.Warning,SentrySeverity.Warning),_defineProperty(_severityMap,Severity.Info,SentrySeverity.Info),_defineProperty(_severityMap,Severity.Debug,SentrySeverity.Debug),_severityMap);var trackedSeverities=Object.getOwnPropertySymbols(severityMap).map(function(s){return severityMap[s];});var minSeverityIndex=trackedSeverities.indexOf(level);if(minSeverityIndex>-1){trackedSeverities=trackedSeverities.slice(0,minSeverityIndex+1);}subscribe(appWillInit$,function(_ref3){var getState=_ref3.getState;init({dsn:'https://1a444b262ac6405594ab33fb0102b377@sentry.io/1398210',environment:env,debug:env==='development',release:pckVersion,attachStacktrace:true,sampleRate:sampleRate,beforeSend:function beforeSend(event){if(event.level&&!trackedSeverities.includes(event.level)){return null;}// eslint-disable-next-line no-param-reassign
|
|
11
11
|
event.extra=_extends({},event.extra||{},{routerStack:getRouterStack(getState()).slice(-5)});return event;}});configureScope(function(scope){scope.setTag('marketId',appConfig.marketId);scope.setTag('appId',appConfig.appId);scope.setTag('pwaVersion',pckVersion);scope.setTag('theme',themeName);scope.setTag('language',appConfig.language);});if(window){window.onerror=function(message,source,lineno,colno,error){captureException(error);};}emitter.addListener(SOURCE_TRACKING,function(error){withScope(function(scope){if(error.context){scope.setExtra('trackerName',error.context);}captureException(error);});});emitter.addListener(SOURCE_CONSOLE,function(args){withScope(function(scope){scope.setLevel(SentrySeverity.Error);scope.setExtra('error',args);captureMessage('Console error');});});});subscribe(userDidUpdate$,function(_ref4){var getState=_ref4.getState;var _getUserData=getUserData(getState()),userId=_getUserData.id;configureScope(function(scope){scope.setTag('userId',userId);});});// Add client lib versions
|
|
12
12
|
subscribe(clientInformationDidUpdate$,function(_ref5){var action=_ref5.action;var _action$data=action.data,appVersion=_action$data.appVersion,libVersion=_action$data.libVersion,deviceId=_action$data.deviceId;configureScope(function(scope){scope.setTag('appVersion',appVersion);scope.setTag('libVersion',libVersion);scope.setTag('deviceId',deviceId);});});// Add app start event for debugging
|
|
13
13
|
subscribe(appDidStart$,function(){withScope(function(scope){scope.setLevel(SentrySeverity.Debug);captureMessage('App did start');});});// Add some stack trace and log to sentry
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{historyPush,historyReset}from"../router";import{INDEX_PATH_DEEPLINK}from"../../constants/RoutePaths";import handleLink from"./handleLink";jest.mock("../../actions/router",function(){return{historyPush:jest.fn(),historyReset:jest.fn()};});var mockedError=jest.fn();jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:function error(){return mockedError.apply(void 0,arguments);}}};});describe('handleLink()',function(){var dispatch=jest.fn();beforeEach(function(){jest.clearAllMocks();});it('should return a redux thunk',function(){expect(handleLink()).toBeInstanceOf(Function);});it('should do nothing when the link is empty',function(){handleLink({})(dispatch);expect(dispatch).not.toHaveBeenCalled();});describe('handle deep link',function(){it('should dispatch historyReset() when the link is a deeplink to the index page',function(){handleLink({link:"shopgate-10006:/".concat(INDEX_PATH_DEEPLINK)})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyReset).toHaveBeenCalledTimes(1);});it('should dispatch historyPush for common deeplinks',function(){var link='/some/page';var deeplink="shopgate-10006:/".concat(link);handleLink({link:deeplink})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledWith({pathname:link});});});describe('handle universal link',function(){it('should dispatch historyPush for universal link',function(){var link='/page/test';var universalLink="https://example.com".concat(link);handleLink({link:universalLink})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledWith({pathname:link});});it('should dispatch historyReset() when the link is an universal link to the index page',function(){handleLink({link:'https://example.com/'})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyReset).toHaveBeenCalledTimes(1);});it('should dispatch historyReset() when the link is invalid URL',function(){handleLink({link:'http !@@##%$^&^*&* s://example.com/'})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyReset).toHaveBeenCalledTimes(1);expect(mockedError).toHaveBeenCalledTimes(1);});});describe('handle external push message links',function(){it('should dispatch historyPush for the external link',function(){var link='http://www.google.de';handleLink({link:link},true)(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledWith({pathname:link});});it('should dispatch historyPush with only the pathname for the external links which are no push messages',function(){var link='http://www.google.de/path/test';handleLink({link:link})(dispatch);expect(dispatch).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledTimes(1);expect(historyPush).toHaveBeenCalledWith({pathname:'/path/test'});});});});
|
|
@@ -1,10 +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 configureStore from'redux-mock-store';import thunk from'redux-thunk';import{logger}from'@shopgate/pwa-core/helpers';import showModal,{getModalId}from"./showModal";import{CREATE_MODAL}from"../../constants/ActionTypes";jest.unmock('@shopgate/pwa-core');jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{warn:jest.fn()}};});var modalEntry={confirm:null,dismiss:'modal.dismiss',message:'Message',params:{},title:'Title',type:null};var mockedState={modal:[_extends({},modalEntry)]};mockedState.modal[0].id=getModalId(modalEntry);/**
|
|
2
|
-
* Creates a mocked store.
|
|
3
|
-
* @param {Object} state The mocked state.
|
|
4
|
-
* @return {Object}
|
|
5
|
-
*/var createStore=function createStore(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return configureStore([thunk])(state);};describe('Modal actions - showModal()',function(){it('should work as expected for a new modal',function(){var _createStore=createStore(mockedState),dispatch=_createStore.dispatch,getState=_createStore.getState,getActions=_createStore.getActions;// Use a fresh set of modal options which is not available whith the store.
|
|
6
|
-
var modalOptions=_extends({},modalEntry,{message:'Fresh entry'});// Simulate dispatch of the action.
|
|
7
|
-
var result=showModal(modalOptions)(dispatch,getState);// Should return a pending promise.
|
|
8
|
-
expect(result).toBeInstanceOf(Promise);var actions=getActions();expect(actions).toHaveLength(1);var createModalAction=actions[0];// Inspect the action payload of the actual modal creation.
|
|
9
|
-
expect(createModalAction.type).toEqual(CREATE_MODAL);expect(createModalAction.options).toEqual(_extends({},modalOptions,{id:getModalId(modalOptions)}));});it('should resolve with null when a duplicate would be created',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var _createStore2,dispatch,getState,getActions,modalOptions,result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_createStore2=createStore(mockedState),dispatch=_createStore2.dispatch,getState=_createStore2.getState,getActions=_createStore2.getActions;modalOptions=_extends({},modalEntry);// Simulate dispatch of the action.
|
|
10
|
-
_context.next=4;return showModal(modalOptions)(dispatch,getState);case 4:result=_context.sent;expect(result).toBeNull();expect(getActions()).toHaveLength(0);expect(logger.warn).toHaveBeenCalledTimes(1);case 8:case"end":return _context.stop();}}},_callee);})));});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{historyPop,historyReplace,historyRedirect}from"./index";jest.mock("./historyPop");jest.mock("./historyReplace");describe('historyRedirect action',function(){var dispatch=jest.fn();beforeEach(function(){jest.clearAllMocks();});it('should pop when no params where passed',function(){var thunk=historyRedirect();thunk(dispatch);expect(historyPop).toHaveBeenCalledTimes(1);});it('should pop when no location was passed',function(){var thunk=historyRedirect({some:'prop'});thunk(dispatch);expect(historyPop).toHaveBeenCalledTimes(1);});it('should replace when a location was passed',function(){var location='/some_route';var thunk=historyRedirect({location:location});thunk(dispatch);expect(historyReplace).toHaveBeenCalledTimes(1);expect(historyReplace).toHaveBeenCalledWith({pathname:location});});it('should replace when a location and a state was passed',function(){var location='/some_route';var state={some:'prop'};var thunk=historyRedirect({location:location,state:state});thunk(dispatch);expect(historyReplace).toHaveBeenCalledTimes(1);expect(historyReplace).toHaveBeenCalledWith({pathname:location,state:state});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import authRoutes from"./AuthRoutes";describe('AuthRoutes',function(){var PROTECTOR='/protector';var PROTECTED='/protected';beforeEach(function(){authRoutes.constructor();authRoutes.set('/protected_not_relevant','/protector_not_relevant');authRoutes.set(PROTECTED,PROTECTOR);});describe('.get()',function(){it('should return the protector for a protected route',function(){expect(authRoutes.get(PROTECTED)).toBe(PROTECTOR);});it('should return NULL when no protector was set for the passed route',function(){expect(authRoutes.get('/some_route')).toBeNull();});});describe('.getAll()',function(){it('should return the routes Map',function(){var result=authRoutes.getAll();expect(result).toBeInstanceOf(Map);expect(result.size).toBe(2);});});describe('.set()',function(){beforeEach(function(){authRoutes.constructor();});it('should only add routes when both method parameters are set',function(){expect(authRoutes.routes.size).toBe(0);authRoutes.set();expect(authRoutes.routes.size).toBe(0);authRoutes.set(PROTECTED);expect(authRoutes.routes.size).toBe(0);authRoutes.set(PROTECTED,PROTECTOR);expect(authRoutes.routes.size).toBe(1);expect(authRoutes.get(PROTECTED)).toBe(PROTECTOR);});});describe('.isProtector()',function(){it('should return true for a protector route',function(){expect(authRoutes.isProtector(PROTECTOR)).toBe(true);});it('should return false for a protected route',function(){expect(authRoutes.isProtector(PROTECTED)).toBe(false);});});describe('.getProtector()',function(){beforeEach(function(){authRoutes.constructor();});it('should return a protector for a distinct route',function(){authRoutes.set(PROTECTED,PROTECTOR);expect(authRoutes.getProtector(PROTECTED)).toBe(PROTECTOR);});it('should return a protector for a route which matches a registered pattern',function(){authRoutes.set("".concat(PROTECTED,"/:id"),PROTECTOR);expect(authRoutes.getProtector("".concat(PROTECTED,"/abc123"))).toBe(PROTECTOR);});it('should return a protector for a route which matches a registered pattern',function(){authRoutes.set(PROTECTED,PROTECTOR);expect(authRoutes.getProtector("".concat(PROTECTED,"?some=param"))).toBe(PROTECTOR);});it('should return NULL when no protector can be determined',function(){authRoutes.set("".concat(PROTECTED,"/:id"),PROTECTOR);expect(authRoutes.getProtector('/protected/abc123/foobar')).toBeNull();});});});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
import{embeddedMedia}from"./index";/**
|
|
2
|
-
* Creates a mocked media provider.
|
|
3
|
-
* @return {Object}
|
|
4
|
-
*/var createMockedProvider=function createMockedProvider(){return{add:jest.fn(),remove:jest.fn(),stop:jest.fn()};};describe('EmbeddedMedia collection',function(){var providerOne=createMockedProvider();var providerTwo=createMockedProvider();beforeEach(function(){jest.clearAllMocks();embeddedMedia.constructor();});describe('.constructor()',function(){it('should construct as expected',function(){expect(embeddedMedia.providers).toBeInstanceOf(Set);expect(embeddedMedia.providers.size).toBe(0);});});describe('.addProvider()',function(){it('should add a providers',function(){embeddedMedia.addProvider(providerOne);embeddedMedia.addProvider(providerTwo);embeddedMedia.addProvider(providerOne);expect(embeddedMedia.providers.size).toBe(2);expect(embeddedMedia.providers.has(providerOne)).toBeTruthy();expect(embeddedMedia.providers.has(providerTwo)).toBeTruthy();});});describe('.removeProvider()',function(){it('should remove providers',function(){embeddedMedia.addProvider(providerOne);embeddedMedia.addProvider(providerTwo);embeddedMedia.removeProvider(providerTwo);expect(embeddedMedia.providers.size).toBe(1);expect(embeddedMedia.providers.has(providerTwo)).toBeFalsy();expect(embeddedMedia.providers.has(providerOne)).toBeTruthy();embeddedMedia.removeProvider(providerOne);expect(embeddedMedia.providers.size).toBe(0);expect(embeddedMedia.providers.has(providerOne)).toBeFalsy();});});describe('Interactions with entries',function(){var mockedEntry={mocked:'entry'};beforeEach(function(){embeddedMedia.addProvider(providerOne);embeddedMedia.addProvider(providerTwo);});describe('.add()',function(){it('should add entries',function(){embeddedMedia.add(mockedEntry);expect(providerOne.add).toHaveBeenCalledTimes(1);expect(providerOne.add).toHaveBeenCalledWith(mockedEntry);expect(providerTwo.add).toHaveBeenCalledTimes(1);expect(providerTwo.add).toHaveBeenCalledWith(mockedEntry);});});describe('.remove()',function(){it('should remove entries',function(){embeddedMedia.add(mockedEntry);embeddedMedia.remove(mockedEntry);expect(providerOne.remove).toHaveBeenCalledTimes(1);expect(providerOne.remove).toHaveBeenCalledWith(mockedEntry);expect(providerTwo.remove).toHaveBeenCalledTimes(1);expect(providerTwo.remove).toHaveBeenCalledWith(mockedEntry);});});describe('.stop()',function(){it('should call the stop methods of registered providers',function(){embeddedMedia.stop();expect(providerOne.stop).toHaveBeenCalledTimes(1);expect(providerTwo.stop).toHaveBeenCalledTimes(1);});});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import redirects from"./Redirects";var FROM='/from';var TO='/to';describe('Redirects',function(){beforeEach(function(){redirects.constructor();});describe('.get()',function(){it('should get a valid redirect',function(){redirects.set(FROM,TO);expect(redirects.get(FROM)).toEqual(TO);});it('should get NULL for an unknown pathname',function(){expect(redirects.get(FROM)).toBeNull();});});describe('.getRedirect()',function(){it('should get a redirect for a distinct pathname',function(){redirects.set(FROM,TO);expect(redirects.getRedirect(FROM)).toBe(TO);});it('should get a redirect for a pathname which matches a registered pattern',function(){redirects.set("".concat(FROM,"/:id"),TO);expect(redirects.getRedirect("".concat(FROM,"/abc123"))).toBe(TO);});it('should get NULL for an unknown pathname',function(){expect(redirects.getRedirect(FROM)).toBeNull();});});describe('.getRedirectExtended()',function(){it('should get a redirect for a distinct pathname',function(){redirects.set(FROM,TO);expect(redirects.getRedirectExtended(FROM)).toEqual({matcher:FROM,handler:TO,pathParams:{},queryParams:{}});});it('should get a redirect for a pathname which matches a registered pattern',function(){var FROM_WITH_PARAM="".concat(FROM,"/:id");redirects.set(FROM_WITH_PARAM,TO);expect(redirects.getRedirectExtended("".concat(FROM,"/abc123"))).toEqual({matcher:FROM_WITH_PARAM,handler:TO,pathParams:{id:'abc123'},queryParams:{}});});it('should get a redirect for urls with path and query params',function(){var url='https://some.shop.de/product/some-product-name/abc123?some=param';var matcher='https://some.shop.de/product/:seoProductName/:productCode';redirects.set(matcher,TO);expect(redirects.getRedirectExtended(url)).toEqual({matcher:matcher,handler:TO,pathParams:{seoProductName:'some-product-name',productCode:'abc123'},queryParams:{some:'param'}});});it('should get NULL for an unknown pathname',function(){expect(redirects.getRedirectExtended(FROM)).toBeNull();});});describe('.set()',function(){it('should add a redirect',function(){redirects.set(FROM,TO);expect(redirects.redirects.size).toEqual(1);expect(redirects.get(FROM)).toEqual(TO);});it('should not override an existing redirect',function(){redirects.set(FROM,TO);redirects.set(FROM,'/somewhere_else');expect(redirects.redirects.size).toEqual(1);expect(redirects.get(FROM)).toEqual(TO);});it('should forcefully add a redirect',function(){redirects.set(FROM,TO);redirects.set(FROM,'/somewhere_else',true);expect(redirects.redirects.size).toEqual(1);expect(redirects.get(FROM)).toEqual('/somewhere_else');});it('should not add when a from path is not given',function(){redirects.set();expect(redirects.redirects.size).toEqual(0);});it('should not add when a to path is not given',function(){redirects.set(FROM);expect(redirects.redirects.size).toEqual(0);});it('should add a promise as redirect',function(){var promise=new Promise(function(){});redirects.set(FROM,promise);expect(redirects.redirects.size).toEqual(1);expect(redirects.get(FROM)).toBe(promise);});});describe('.unset()',function(){it('should remove a found redirect',function(){redirects.set(FROM,TO);redirects.set('/somewhere','/somewhere_else');redirects.unset(FROM);expect(redirects.redirects.size).toEqual(1);expect(redirects.get('/somewhere')).toEqual('/somewhere_else');});});});
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{JSDOM}from'jsdom';import{logger}from'@shopgate/pwa-core/helpers';import MediaProvider from"./MediaProvider";import styles from"./style";jest.mock('@shopgate/pwa-core/helpers',function(){return{logger:{error:jest.fn()}};});/**
|
|
2
|
-
* Creates a DOM container with iframes.
|
|
3
|
-
* @param {Array} srcs A list of video URLs.
|
|
4
|
-
* @return {Object}
|
|
5
|
-
*/var createContainer=function createContainer(srcs){var html=srcs.map(function(src){return"<iframe src=\"".concat(src,"\"></iframe>");}).join('');return new JSDOM(html).window.document;};describe('MediaProvider',function(){beforeEach(function(){jest.clearAllMocks();});describe('.constructor()',function(){it('should construct as expected',function(){var instance=new MediaProvider();expect(instance.containers).toBeInstanceOf(Map);expect(Array.from(instance.containers)).toHaveLength(0);});});describe('.add()',function(){it('should log an error when it is not overwritten',function(){var instance=new MediaProvider();instance.add();expect(logger.error).toHaveBeenCalledTimes(1);});});describe('.stop()',function(){it('should log an error when it is not overwritten',function(){var instance=new MediaProvider();instance.stop();expect(logger.error).toHaveBeenCalledTimes(1);});});describe('.remove()',function(){it('should remove containers as expected',function(){var instance=new MediaProvider();var containerOne=createContainer(['http://www.provider-one.com/video']);var containerTwo=createContainer(['http://www.provider-two.com/video']);instance.containers.set(containerOne,containerOne);instance.containers.set(containerTwo,containerTwo);instance.remove(containerTwo);expect(instance.containers.size).toBe(1);expect(instance.containers.get(containerTwo)).toBeUndefined();expect(instance.containers.get(containerOne)).toEqual(containerOne);instance.remove(containerOne);expect(instance.containers.size).toBe(0);});});describe('.responsify()',function(){it('should responsify a dom container',function(){var dom=document.createElement('body');dom.innerHTML='<iframe width="560" height="315" />';var container=dom.querySelectorAll('iframe')[0];var instance=new MediaProvider();instance.responsify(container);expect(dom).toMatchSnapshot();expect(container.getAttribute('height')).toBeNull();expect(container.getAttribute('width')).toBeNull();expect(container.closest('div').className).toBe(styles);});it('should not responsify already responsive element',function(){var dom=document.createElement('body');dom.innerHTML='<div style="padding:52.71% 0 0 0;position:relative;"><iframe src="https://player.vimeo.com/video/326436012?autoplay=1&title=0&byline=0&portrait=0" style="position:absolute;top:0;left:0;width:100%;height:100%;" frameborder="0" allow="autoplay; fullscreen" allowfullscreen></iframe></div>';var container=dom.querySelectorAll('iframe')[0];var instance=new MediaProvider();instance.responsify(container);expect(dom).toMatchSnapshot();expect(container.getAttribute('height')).toBeNull();expect(container.getAttribute('width')).toBeNull();expect(container.closest('div').className).toBe(styles);});});});
|
|
@@ -1,11 +0,0 @@
|
|
|
1
|
-
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;}function _classCallCheck(instance,Constructor){if(!(instance instanceof Constructor)){throw new TypeError("Cannot call a class as a function");}}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{JSDOM}from'jsdom';import{Vimeo}from"./index";var videos=['https://player.vimeo.com/video/484765967?color=32ac5c&title=0&byline=0&portrait=0','https://player.vimeo.com/video/224765967?color=32ac5c&title=0&byline=0&portrait=0'];/**
|
|
2
|
-
* Creates a DOM container with iframes.
|
|
3
|
-
* @param {Array} srcs A list of video URLs.
|
|
4
|
-
* @return {Object}
|
|
5
|
-
*/var createContainer=function createContainer(srcs){var html=srcs.map(function(src){return"<iframe src=\"".concat(src,"\"></iframe>");}).join('');return new JSDOM(html).window.document;};describe('Vimeo media provider',function(){var instance;var pauseMock=jest.fn();/**
|
|
6
|
-
* Updates the global Vimeo player object.
|
|
7
|
-
* @param {boolean} [available=true] Should the vimeo player object be injected.
|
|
8
|
-
*/var updatePlayer=function updatePlayer(){var available=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;if(available){window.Vimeo={Player:/*#__PURE__*/_createClass(function MockPlayer(){_classCallCheck(this,MockPlayer);_defineProperty(this,"pause",function(){pauseMock();});})};return;}delete window.Vimeo;};/**
|
|
9
|
-
* Creates a Vimeo media provider instance.
|
|
10
|
-
* @param {boolean} [addPlayer=true] Should the vimeo player object be injected.
|
|
11
|
-
*/var createInstance=function createInstance(){var addPlayer=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;updatePlayer(addPlayer);document.getElementsByTagName('html')[0].innerHTML='';instance=new Vimeo();instance.responsify=jest.fn();};beforeEach(function(){jest.clearAllMocks();createInstance();});describe('.constructor()',function(){it('should construct as expected',function(){createInstance(false);expect(instance.containers).toBeInstanceOf(Map);expect(instance.isPending).toBe(true);expect(instance.deferred).toEqual([]);});});describe('.add()',function(){it('should add multiple containers as expected',function(){var containerOne=createContainer([videos[0]]);var containerTwo=createContainer([videos[1]]);var iframesOne=containerOne.querySelectorAll('iframe');var iframesTwo=containerTwo.querySelectorAll('iframe');instance.add(containerOne);instance.add(containerTwo);instance.add(containerOne);expect(instance.containers.size).toBe(2);expect(instance.containers.get(containerOne)).toEqual([expect.any(window.Vimeo.Player)]);expect(instance.containers.get(containerTwo)).toEqual([expect.any(window.Vimeo.Player)]);expect(instance.responsify).toHaveBeenCalledWith(iframesOne[0]);expect(instance.responsify).toHaveBeenCalledWith(iframesTwo[0]);});it('should defer addition of a container if the player is not ready',function(){createInstance(false);var container=createContainer([videos[0]]);instance.add(container);expect(instance.containers.size).toBe(0);expect(instance.deferred).toEqual([container]);});it('should not add a container when it does not contain a video',function(){var container=new JSDOM('<p>Some HTML content</p>').window.document;instance.add(container);expect(instance.containers.size).toBe(0);});});describe('.remove()',function(){it('should remove containers as expected',function(){var containerOne=createContainer([videos[0]]);var containerTwo=createContainer([videos[1]]);instance.add(containerOne);instance.add(containerTwo);instance.remove(containerTwo);expect(instance.containers.size).toBe(1);expect(instance.containers.get(containerTwo)).toBeUndefined();expect(instance.containers.get(containerOne)).toEqual([expect.any(window.Vimeo.Player)]);instance.remove(containerOne);expect(instance.containers.size).toBe(0);});});describe('.stop()',function(){it('should stop the videos within mutiple containers',function(){var containerOne=createContainer(videos);var containerTwo=createContainer([videos[1]]);instance.add(containerOne);instance.add(containerTwo);instance.stop();expect(pauseMock).toHaveBeenCalledTimes(3);});});describe('.onScriptLoaded()',function(){it('should mark as ready (not pending)',function(){instance.onScriptLoaded();expect(instance.isPending).toBe(false);});it('should run deferred containers on script ready',function(){instance.deferred=['container 1','container 2'];jest.spyOn(instance,'add').mockReturnValue(true);instance.onScriptLoaded();expect(instance.add).toHaveBeenCalledTimes(2);expect(instance.add).nthCalledWith(1,'container 1');expect(instance.add).nthCalledWith(2,'container 2');expect(instance.deferred).toHaveLength(0);});});});
|
|
@@ -1,5 +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{JSDOM}from'jsdom';import URLSearchParams from'url-search-params';import{YouTube}from"./index";var videos=['https://youtube.com/fooo?enablejsapi=0&controls=0','https://youtube.com/fooo?controls=0&enablejsapi=0','https://youtube.com/fooo','https://youtube-nocookie.com/fooo?controls=0'];/**
|
|
2
|
-
* Creates a DOM container with iframes.
|
|
3
|
-
* @param {Array} srcs A list of video URLs.
|
|
4
|
-
* @return {Object}
|
|
5
|
-
*/var createContainer=function createContainer(srcs){var iframes=srcs.map(function(src){return"<iframe src=\"".concat(src,"\"></iframe>");}).join('');var html="<div>".concat(iframes,"</div>");return new JSDOM(html).window.document;};describe('YouTube media provider',function(){var instance;beforeEach(function(){instance=new YouTube();instance.responsify=jest.fn();});describe('.constructor()',function(){it('should construct as expected',function(){expect(instance.containers).toBeInstanceOf(Map);expect(instance.containers.size).toBe(0);});});describe('.add()',function(){it('should add multiple containers as expected',function(){var containerOne=createContainer([videos[0]]);var containerTwo=createContainer([videos[1]]);var iframesOne=containerOne.querySelectorAll('iframe');var iframesTwo=containerTwo.querySelectorAll('iframe');instance.add(containerOne);instance.add(containerTwo);instance.add(containerOne);expect(instance.containers.size).toBe(2);expect(instance.containers.get(containerOne)).toEqual(iframesOne);expect(instance.containers.get(containerTwo)).toEqual(iframesTwo);expect(instance.responsify).toHaveBeenCalledWith(iframesOne[0]);expect(instance.responsify).toHaveBeenCalledWith(iframesTwo[0]);});it('should add a container with different types of YouTube videos',function(){var container=createContainer(videos);var iframes=container.querySelectorAll('iframe');instance.add(container);expect(instance.containers.size).toBe(1);expect(iframes).toHaveLength(videos.length);iframes.forEach(function(_ref){var src=_ref.src;var _src$split=src.split('?'),_src$split2=_slicedToArray(_src$split,2),query=_src$split2[1];var urlParams=new URLSearchParams(query);expect(urlParams.get('enablejsapi')).toBe('1');expect(urlParams.get('controls')).toBe('1');});});it('should not add a container when it does not contain a video',function(){var container=new JSDOM('<p>Some HTML content</p>').window.document;instance.add(container);expect(instance.containers.size).toBe(0);});});describe('.remove()',function(){it('should remove containers as expected',function(){var containerOne=createContainer([videos[0]]);var containerTwo=createContainer([videos[1]]);var iframesOne=containerOne.querySelectorAll('iframe');instance.add(containerOne);instance.add(containerTwo);instance.remove(containerTwo);expect(instance.containers.size).toBe(1);expect(instance.containers.get(containerTwo)).toBeUndefined();expect(instance.containers.get(containerOne)).toEqual(iframesOne);instance.remove(containerOne);expect(instance.containers.size).toBe(0);});});describe('.stop()',function(){it('should stop the videos within multiple containers',function(){var postMessageMock=jest.fn();var containerOne=createContainer([videos[0]]);var containerTwo=createContainer([videos[1],videos[2]]);instance.add(containerOne);instance.add(containerTwo);var iframesOne=containerOne.querySelectorAll('iframe');var iframesTwo=containerTwo.querySelectorAll('iframe');iframesOne[0].contentWindow.postMessage=postMessageMock;iframesTwo[0].contentWindow.postMessage=postMessageMock;iframesTwo[1].contentWindow.postMessage=postMessageMock;instance.stop();expect(postMessageMock).toHaveBeenCalledTimes(3);expect(postMessageMock).toHaveBeenCalledWith('{"event":"command","func":"stopVideo","args":""}','*');});});});
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
/* eslint-disable extra-rules/no-single-line-objects,global-require */var products=[{id:'007-001',characteristics:{1:'1',2:'1',3:'1'// equals L, Black, None
|
|
2
|
-
}},{id:'007-002',characteristics:{1:'1',2:'2',3:'1'// equals L, Blue, None
|
|
3
|
-
}},{id:'007-003',characteristics:{1:'1',2:'2',3:'3'// equals L, Blue, Stripes
|
|
4
|
-
}},{id:'007-004',characteristics:{1:'2',2:'2',3:'3'// equals XL, Blue, Stripes
|
|
5
|
-
}}];var characteristics=[{id:'1',label:'Size',values:[{id:'0',label:'Resilient'},{id:'1',label:'L'},{id:'2',label:'XL'}]},{id:'2',label:'Color',values:[{id:'0',label:'Transparent'},{id:'1',label:'Black'},{id:'2',label:'Blue'}]},{id:'3',label:'Pattern',values:[{id:'0',label:'No pattern'},{id:'1',label:'None'},{id:'2',label:'Checked'},{id:'3',label:'Stripes'}]}];describe('ProductCharacteristics helpers',function(){afterEach(function(){jest.resetModules();});describe('findSelectionIndex()',function(){var _require=require("./index"),findSelectionIndex=_require.findSelectionIndex;it('should return the index',function(){expect(findSelectionIndex(characteristics,'2')).toBe(1);});it('should return -1 when the the characteristic was not found',function(){expect(findSelectionIndex(characteristics,'5')).toBe(-1);});});describe('prepareState()',function(){var _require2=require("./index"),prepareState=_require2.prepareState;it('should return the current selections, when the selected ID is not found',function(){var selections={1:'1',2:'1',3:'1'};var result=prepareState('4','2',selections,characteristics,products);expect(result).toEqual(selections);});it('should return partial states when a full selection was not selected yet',function(){var selections={};// L
|
|
6
|
-
var result=prepareState('1','1',selections,characteristics,products);expect(result).toEqual({1:'1'});// equals L, Blue
|
|
7
|
-
result=prepareState('2','2',result,characteristics,products);expect(result).toEqual({1:'1',2:'2'});// equals L, Blue, Stripes
|
|
8
|
-
result=prepareState('3','3',result,characteristics,products);expect(result).toEqual({1:'1',2:'2',3:'3'});});it('should return a full selections object when the middle selection was changed, but there is a product for the resulting selections',function(){// L, Black, None => L, Blue, None
|
|
9
|
-
var selections={1:'1',2:'1',3:'1'};var result=prepareState('2','2',selections,characteristics,products);expect(result).toEqual({1:'1',2:'2',3:'1'});});it('should return a full selections object when there is only one product that matches the selected characteristics',function(){// XL => XL, Blue, Stripes
|
|
10
|
-
var selections={};var result=prepareState('1','2',selections,characteristics,products);expect(result).toEqual({1:'2',2:'2',3:'3'});});it('should not reset when a value of the last selection is changed',function(){// L, Blue, None => L, Blue, Stripes
|
|
11
|
-
var selections={1:'1',2:'2',3:'1'};var result=prepareState('3','3',selections,characteristics,products);expect(result).toEqual({1:'1',2:'2',3:'3'});});it('should reset the last selection when the middle selection was changed, but there is no matching product',function(){// L, Black, Checked => L, Blue
|
|
12
|
-
var selections={1:'1',2:'1',3:'2'};var result=prepareState('2','2',selections,characteristics,products);expect(result).toEqual({1:'1',2:'2'});});});describe('selectCharacteristics()',function(){describe('default config',function(){var _require3=require("./index"),selectCharacteristics=_require3.selectCharacteristics;it('should return empty characteristics',function(){expect(selectCharacteristics({})).toEqual({});});it('should return characteristics for selected variant',function(){expect(selectCharacteristics({variantId:'007-001',variants:{products:products}})).toEqual(products[0].characteristics);});it('should preselect characteristics for only 1 variant',function(){expect(selectCharacteristics({variants:{products:[products[0]]}})).toEqual(products[0].characteristics);});it('should not preselect characteristics by config',function(){expect(selectCharacteristics({variants:{products:products}})).toEqual({});});});describe('preselect config',function(){jest.doMock('@shopgate/pwa-common/helpers/config',function(){return{product:{variantPreselect:true}};});it('should preselect characteristics for selectable product',function(){var _require4=require("./index"),selectCharacteristicsPreselect=_require4.selectCharacteristics;expect(selectCharacteristicsPreselect({variants:{characteristics:characteristics,products:products}})).toEqual(products[0].characteristics);});});});});/* eslint-enable extra-rules/no-single-line-objects,global-require */
|
|
@@ -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 React from'react';import{mount}from'enzyme';import{Provider}from'react-redux';import configureStore from'redux-mock-store';import AppScanner from'@shopgate/pwa-core/classes/Scanner';import{defaultClientInformation}from'@shopgate/pwa-core/helpers/version';import{SCANNER_SCOPE_DEFAULT,SCANNER_TYPE_BARCODE,SCANNER_MIN_APP_LIB_VERSION}from'@shopgate/pwa-core/constants/Scanner';import ScannerContainer from"./index";jest.mock('@shopgate/pwa-core/helpers',function(){var actual=require.requireActual('@shopgate/pwa-core/helpers');return _extends({},actual,{logger:{groupCollapsed:jest.fn(),error:jest.fn()}});});var scannerDidClose=jest.fn();var scannerDidOpen=jest.fn();/**
|
|
2
|
-
* @param {string} libVersion An app lib version.
|
|
3
|
-
* @return {JSX}
|
|
4
|
-
*/var createWrapper=function createWrapper(){var libVersion=arguments.length>0&&arguments[0]!==undefined?arguments[0]:SCANNER_MIN_APP_LIB_VERSION;// Change the lib version of the client information for the internal checks of the Scanner class.
|
|
5
|
-
defaultClientInformation.libVersion=libVersion;var store=configureStore()({client:{info:{libVersion:libVersion}}});return mount(/*#__PURE__*/React.createElement(Provider,{store:store},/*#__PURE__*/React.createElement(ScannerContainer,{scannerDidOpen:scannerDidOpen,scannerDidClose:scannerDidClose,scope:SCANNER_SCOPE_DEFAULT,type:SCANNER_TYPE_BARCODE},/*#__PURE__*/React.createElement("div",null,"Container Children"))));};describe('<ScannerContainer />',function(){var scannerOpenSpy=jest.spyOn(AppScanner,'open');var scannerCloseSpy=jest.spyOn(AppScanner,'close');beforeEach(function(){jest.resetAllMocks();});it('should render the component when the scanner is supported',function(){var wrapper=createWrapper();expect(wrapper.find(ScannerContainer)).not.toBeEmptyRender();});it('should not render the component when the scanner is not supported',function(){var wrapper=createWrapper('10.0.0');expect(wrapper.find(ScannerContainer)).toBeEmptyRender();});it('should open the scanner when the component mounts',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var wrapper;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:wrapper=createWrapper();_context.next=3;return wrapper.find(ScannerContainer).instance().componentDidMount();case 3:expect(scannerDidOpen).toHaveBeenCalledTimes(1);expect(scannerOpenSpy).toHaveBeenCalledTimes(1);case 5:case"end":return _context.stop();}}},_callee);})));it('should not open the scanner when the component mounts and the scanner is not supported',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var wrapper;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:wrapper=createWrapper('10.0.0');_context2.next=3;return wrapper.find(ScannerContainer).instance().componentDidMount();case 3:expect(scannerDidOpen).not.toHaveBeenCalled();expect(scannerOpenSpy).not.toHaveBeenCalled();case 5:case"end":return _context2.stop();}}},_callee2);})));it('should close the scanner when the component unmounts',function(){var wrapper=createWrapper();wrapper.unmount();expect(scannerDidClose).toHaveBeenCalledTimes(1);expect(scannerCloseSpy).toHaveBeenCalledTimes(1);});it('should not close the scanner when the component unmounts and the scanner is not supported',function(){var wrapper=createWrapper('10.0.0');wrapper.unmount();expect(scannerDidClose).not.toHaveBeenCalled();expect(scannerCloseSpy).not.toHaveBeenCalled();});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import shouldShowWidget from"./shouldShowWidget";describe('shouldShowWidget',function(){it('should return true when widget has no schedule related flags',function(){expect(shouldShowWidget({})).toBe(true);});it('should return false, when widget is not published',function(){expect(shouldShowWidget({published:false})).toBe(false);});it('should return false, when widget is not yet available',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()+1000).toISOString()}})).toBe(false);});it('should return false, when widget is not yet available and has valid_to',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()+10000).toISOString(),valid_to:new Date(Date.now()+20000).toISOString()}})).toBe(false);});it('should return false, when widget is no longer available',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_to:new Date(Date.now()-1000).toISOString()}})).toBe(false);});it('should return false, when widget was but is no longer available',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()-2000).toISOString(),valid_to:new Date(Date.now()-1000).toISOString()}})).toBe(false);});it('should return true, when widget is already available',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()-1000).toISOString()}})).toBe(true);});it('should return true, when widget is already available and has endDate',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()-1000).toISOString(),valid_to:new Date(Date.now()+1000).toISOString()}})).toBe(true);});it('should return true, when widget is has only endDate in the future',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_to:new Date(Date.now()+1000).toISOString()}})).toBe(true);});it('should return true, when widget has plan but no valid_* fields',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{}})).toBe(true);});it('should return false, when valid_to is higher than valid_from',function(){expect(shouldShowWidget({published:true,plan:true,planDate:{valid_from:new Date(Date.now()+2000).toISOString(),valid_to:new Date(Date.now()+1000).toISOString()}})).toBe(false);});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{themeConfig}from"../mock";export{themeConfig};export var themeColors=themeConfig.colors;export var themeShadows=themeConfig.shadows;export var themeVariables=themeConfig.variables;export var themeIcons=themeConfig.icons;export var themeName='theme';var appConfig={get hideProductImageShadow(){return true;},get hasFavorites(){return true;}};export default appConfig;
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{getStyle}from"./index";describe('DOM Helpers',function(){describe('getStyle()',function(){var getComputedStyleSpy=jest.spyOn(window,'getComputedStyle');beforeEach(function(){jest.clearAllMocks();});describe('without getComputedStyle',function(){it('should return the expected value',function(){var element=document.createElement('div');element.style.backgroundColor='#FFF';expect(getStyle(element,'backgroundColor')).toBe('rgb(255, 255, 255)');expect(getComputedStyleSpy).toHaveBeenCalledTimes(1);});it('should return an empty string when the property is not set',function(){var element=document.createElement('div');expect(getStyle(element,'backgroundColor')).toBe('');expect(getComputedStyleSpy).toHaveBeenCalledTimes(1);});});describe('without getComputedStyle',function(){var computedStyle=window.getComputedStyle;beforeAll(function(){window.getComputedStyle=null;});afterAll(function(){window.getComputedStyle=computedStyle;});it('should return the expected value',function(){var element=document.createElement('div');element.style.backgroundColor='#FFF';expect(getStyle(element,'backgroundColor')).toBe('rgb(255, 255, 255)');expect(getComputedStyleSpy).not.toHaveBeenCalled();});it('should return an empty string when the property is not set',function(){var element=document.createElement('div');expect(getStyle(element,'backgroundColor')).toBe('');expect(getComputedStyleSpy).not.toHaveBeenCalled();});});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{JSDOM}from'jsdom';import{handleYouTube,getStyles}from"./handleDOM";var mockedEvent=jest.fn();jest.mock('@shopgate/pwa-core/classes/Event',function(){return{addCallback:function addCallback(){mockedEvent.apply(void 0,arguments);}};});describe('handleDOM',function(){describe('handleYouTube',function(){var postMessageMock=jest.fn();var srcs=['https://youtube.com/fooo?enablejsapi=0&controls=0','https://youtube.com/fooo?controls=0&enablejsapi=0','https://youtube.com/fooo'];it('should sanitize youtube iframes',function(){var html=srcs.map(function(src){return"<iframe src=\"".concat(src,"\"></iframe>");}).join('');var dom=new JSDOM(html);handleYouTube(dom.window.document);var iframes=dom.window.document.querySelectorAll('iframe');iframes.forEach(function(iframeConstantForLinter){var ifr=iframeConstantForLinter;ifr.contentWindow.postMessage=postMessageMock;var newSrc=ifr.src;expect(newSrc.includes('enablejsapi=1')).toBe(true);expect(newSrc.includes('controls=1')).toBe(true);});expect(mockedEvent).toHaveBeenCalledTimes(2);});it('should call stopPlayer',function(){mockedEvent.mock.calls[0][1]();mockedEvent.mock.calls[1][1]();expect(postMessageMock).toHaveBeenCalledTimes(6);expect(postMessageMock).toHaveBeenCalledWith('{"event":"command","func":"stopVideo","args":""}','*');});});describe('getStyles',function(){it('should get styles',function(){var dom=new JSDOM('<style>body { background: red;}</style>');var styles=getStyles(dom.window.document);expect(styles.length).toBe(1);});});});
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
var mockedMessageCache={};jest.mock("./messageCache",function(){return mockedMessageCache;});describe('getNumberFormatter',function(){var CACHE_KEY='en-US_number_fr_2';var getNumberFormatter;beforeAll(function(){// eslint-disable-next-line global-require
|
|
2
|
-
getNumberFormatter=require("./getNumberFormatter")["default"];});it('should try to format a number',function(){var result=getNumberFormatter('en-US',1,2);expect(result).toBe('1.00');expect(mockedMessageCache[CACHE_KEY].format({value:1})).toBe('1.00');});it('should use cache',function(){// Changing the cached instance to check if it really uses cache.
|
|
3
|
-
mockedMessageCache[CACHE_KEY]={format:function format(){return 100;}};expect(getNumberFormatter('en-US',1,2)).toBe(100);});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import getTranslator from"./getTranslator";jest.mock("./messageCache",function(){return{};});describe('getTranslator',function(){var translate=getTranslator({common:{cancel:'Cancel'}},'en-US');it('should get common.cancel string',function(){var result=translate('common.cancel');expect(result).toEqual('Cancel');});it('should return not string type',function(){var result=translate({id:1});expect(result).toEqual({id:1});});it('should return original nullable key',function(){var result=translate(null);expect(result).toEqual(null);});it('should return original undefined key',function(){var result=translate(undefined);expect(result).toEqual(undefined);});});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import merge from'lodash/merge';import mergeTranslations from"./mergeTranslations";global.process.env={LOCALE_FILE:'en-US'};var themeTranslations={common:{cancel:'Cancel',submit:'Submit'},search:{no_result:{heading:'Oops!'},placeholder:'Search'}};var extensionTranslations={'@shopgate/awesome-extension_12345/locale/en':{search:{no_result:{heading:'Ouch!'}}},'@acme/some-extension/locale/de-DE':{custom_scope:{string:'Wert',other_string:'Anderer Wert'},common:{submit:'Senden'}},'@acme/some-extension/locale/en-US':{common:{submit:'Send'},custom_scope:{string:'Value',other_string:'Other value'}},'@acme/wrong/en-US/translations':{common:{cancel:'Abort'}}};// Manually merged translations to eleminate false positives through wrong configured lodash merge.
|
|
2
|
-
var mergedTranslations={common:{cancel:'Cancel',submit:'Send'},custom_scope:{string:'Value',other_string:'Other value'},search:{no_result:{heading:'Ouch!'},placeholder:'Search'}};describe('mergeTranslations helper',function(){it('should merge the translations as expected based on the env locale',function(){var result=mergeTranslations(themeTranslations,extensionTranslations);expect(result).toEqual(mergedTranslations);});it('should merge the translations as expected for a passed en-US locale',function(){var result=mergeTranslations(themeTranslations,extensionTranslations,'en-US');expect(result).toEqual(mergedTranslations);});it('should merge the translations as expected for a passed de-DE locale',function(){var result=mergeTranslations(themeTranslations,extensionTranslations,'de-DE');expect(result).toEqual(merge(themeTranslations,extensionTranslations['@acme/some-extension/locale/de-DE']));});it('should return the theme translations if no extension translations match the locale',function(){var result=mergeTranslations(themeTranslations,extensionTranslations,'fr-FR');expect(result).toEqual(themeTranslations);});it('should return the theme translations if no extension translations are passed',function(){var result=mergeTranslations(themeTranslations);expect(result).toEqual(themeTranslations);});it('should return the theme translations if the extension translations are empty',function(){var result=mergeTranslations(themeTranslations,{},'en-US');expect(result).toEqual(themeTranslations);});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import hideMenuBar from'@shopgate/pwa-core/commands/hideMenuBar';import broadcastEvent from'@shopgate/pwa-core/commands/broadcastEvent';import{prepareLegacyNavigation}from"./index";jest.mock('@shopgate/pwa-core/classes/AppCommand');jest.mock('@shopgate/pwa-core/commands/hideMenuBar',function(){return jest.fn();});jest.mock('@shopgate/pwa-core/commands/broadcastEvent',function(){return jest.fn();});describe('Legacy helpers',function(){describe('prepareLegacyNavigation()',function(){it('should dispatch the correct commands',function(){prepareLegacyNavigation();expect(broadcastEvent).toHaveBeenCalledTimes(1);expect(broadcastEvent).toHaveBeenCalledWith({event:'updateNavigationBar',parameters:['','none',{type:'none'}]});expect(hideMenuBar).toHaveBeenCalledTimes(1);expect(hideMenuBar).toHaveBeenCalledWith({animation:null});});});});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import PropTypes from'prop-types';var options={context:{i18n:function i18n(){return{// eslint-disable-next-line no-underscore-dangle
|
|
2
|
-
__:function __(input){if(input){return input;}return'';},_p:function _p(){return'p';},_d:function _d(){return'd';},_n:function _n(){return'n';}};}},childContextTypes:{i18n:PropTypes.func}};export default options;
|
package/helpers/mocks/spec.js
DELETED
|
@@ -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 mockRenderOptions from"./mockRenderOptions";describe('MockRenderOptions',function(){it('should return object',function(){expect(_typeof(mockRenderOptions)).toBe('object');expect(_typeof(mockRenderOptions.context.i18n)).toBe('function');var i18n=mockRenderOptions.context.i18n();/* eslint-disable no-underscore-dangle */expect(i18n.__('foo')).toBe('foo');expect(i18n.__()).toBe('');expect(i18n._p()).toBe('p');expect(i18n._d()).toBe('d');/* eslint-enable no-underscore-dangle */});});
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import collection from"../portalCollection";import{APP_ROUTES}from"../../../constants/Portals";jest.mock("../../config",function(){return{componentsConfig:{portals:{route1:{path:'route1.jsx',target:'app.routes'},component1:{path:'component1.jsx',target:'view.before'},route2:{path:'route2.jsx',target:'app.routes'}}}};});describe('helpers/portals/routePortals.js',function(){var routePortals;var portals={route1:jest.fn(function(){return'route1 content';}),route2:jest.fn(function(){return null;}),route10:jest.fn(function(){return'route10 content';}),route20:jest.fn(function(){return null;})};jest.spyOn(collection,'getPortals').mockReturnValue(portals);it('should read from static config',function(){jest.isolateModules(function(){// eslint-disable-next-line global-require
|
|
2
|
-
routePortals=require("../routePortals")["default"];});expect(routePortals).toEqual(['route1 content']);});it('should read from registered config',function(){jest.spyOn(collection,'getConfig').mockReturnValue({route10:{path:'route10.jsx',target:APP_ROUTES},component10:{path:'component10.jsx',target:'view.before'},route20:{path:'route20.jsx',target:APP_ROUTES}});jest.isolateModules(function(){// eslint-disable-next-line global-require
|
|
3
|
-
routePortals=require("../routePortals")["default"];});expect(routePortals).toEqual(['route10 content']);});});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
import{compareObjects}from"../compareObjects";describe('compareObjects',function(){var obj1={abc:123,def:456,hij:789};var obj2={abc:123,def:456,hij:789};var obj3={abc:123,def:456,xyz:234// DIFFERENT !!
|
|
2
|
-
};it('should compare equal objects',function(){expect(compareObjects(obj1,obj2)).toEqual(true);expect(compareObjects(obj2,obj1)).toEqual(true);});it('should compare unequal objects',function(){expect(compareObjects(obj1,obj3)).toEqual(false);expect(compareObjects(obj2,obj3)).toEqual(false);expect(compareObjects(obj3,obj1)).toEqual(false);expect(compareObjects(obj3,obj2)).toEqual(false);});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{generateSortedHash}from"../generateSortedHash";describe('generateSortedHash',function(){it('should generate a hash',function(){var obj1={abc:12,hij:567,def:345};var obj2={abc:12,hij:['asdasd','asdasdasd',{56:'34534',67:'sdfdf',12:'sdsdf'}],def:345};expect(generateSortedHash(obj1)).toEqual('{"abc":12,"def":345,"hij":567}');expect(generateSortedHash(obj2)).toEqual('{"abc":12,"def":345,"hij":["asdasd","asdasdasd",{"12":"sdsdf","56":"34534","67":"sdfdf"}]}');});});
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import noop from'lodash/noop';import{mutable,next,skipRest,stop}from"../mutable";describe('Mutable',function(){var original;beforeEach(function(){// Processes only one param by returning it by default
|
|
2
|
-
original=jest.fn(function(data){return data;});});it('should call original',function(){var mutated=mutable(original);var res=mutated(100);expect(original).toBeCalledWith(100);expect(res).toEqual(100);});it('should replace original',function(){var mutated=mutable(original);var rewrite=jest.fn(function(data){return data*2;});mutated.replace(rewrite);var res=mutated(100);expect(rewrite).toBeCalledWith(100);expect(original).toBeCalledTimes(0);expect(res).toEqual(200);});it('should restore and call original again',function(){var mutated=mutable(original);var rewrite=jest.fn();mutated.replace(rewrite);mutated.restore();var res=mutated(100);expect(rewrite).toBeCalledTimes(0);expect(original).toBeCalledWith(100);expect(res).toEqual(100);});it('should call useBefore pre-processor step without modifying params and call the original',function(){var mutated=mutable(original);var use=jest.fn();mutated.useBefore(use);var res=mutated(100);expect(use).toBeCalledWith(100);expect(original).toBeCalledWith(100);expect(res).toEqual(100);});it('should not call any pre-processor steps anymore and revert to the original',function(){var mutated=mutable(original);var use=jest.fn();mutated.useBefore(use);var rewrite=jest.fn();mutated.replace(rewrite);mutated.reset();var res=mutated(100);expect(use).toBeCalledTimes(0);expect(rewrite).toBeCalledTimes(0);expect(original).toBeCalledWith(100);expect(res).toEqual(100);});it('should transform params for the follow up step and action',function(){var mutated=mutable(original);var use1=jest.fn(function(){return next(200,50);});var use2=jest.fn();// Does not transform and keep params from "use1" this time.
|
|
3
|
-
mutated.useBefore(use1);mutated.useBefore(use2);var res=mutated(100,300);expect(use1).toBeCalledWith(100,300);expect(use2).toBeCalledWith(200,50);expect(original).toBeCalledWith(200,50);expect(res).toEqual(200);});it('should transform params for the follow up step and once again for action',function(){var mutated=mutable(original);var use1=jest.fn(function(){return next(200,50);});var use2=jest.fn(function(){return next('foo','bar');});mutated.useBefore(use1);mutated.useBefore(use2);var res=mutated(100,300);expect(use1).toBeCalledWith(100,300);expect(use2).toBeCalledWith(200,50);expect(original).toBeCalledWith('foo','bar');expect(res).toEqual('foo');});it('should prevent further steps and the action from being executed at all after the first steps',function(){var mutated=mutable(original);var result=noop;var use1=jest.fn(function(){return stop(result);});var use2=jest.fn(function(){return next(200,50);});mutated.useBefore(use1);mutated.useBefore(use2);var res=mutated(100,300);expect(use1).toBeCalledTimes(1);expect(use2).toBeCalledTimes(0);expect(original).toBeCalledTimes(0);expect(res).toEqual(result);});it('should skip forward to the original action directly',function(){var mutated=mutable(original);var use1=jest.fn(function(){return skipRest('hello','world');});var use2=jest.fn();var use3=jest.fn(function(){return next(200,50);});mutated.useBefore(use1);mutated.useBefore(use2);mutated.useBefore(use3);var res=mutated(100,300);expect(use1).toBeCalledTimes(1);expect(use2).toBeCalledTimes(0);expect(use3).toBeCalledTimes(0);expect(original).toBeCalledWith('hello','world');expect(res).toEqual('hello');});it('should skip forward to the replaced action directly',function(){var mutated=mutable(original);var use1=jest.fn(function(){return skipRest('hello','world','!!!111');});var use2=jest.fn();var use3=jest.fn(function(){return next(200,50);});mutated.useBefore(use1);mutated.useBefore(use2);// Rewrite returns the third param only
|
|
4
|
-
var rewrite=jest.fn(function(data1,data2,data3){return data3;});// Shows that replace can be called between "useBefore" calls and still work.
|
|
5
|
-
mutated.replace(rewrite);mutated.useBefore(use3);var res=mutated(100,300);expect(use1).toBeCalledTimes(1);expect(use2).toBeCalledTimes(0);expect(use3).toBeCalledTimes(0);expect(original).toBeCalledTimes(0);expect(rewrite).toBeCalledWith('hello','world','!!!111');expect(res).toEqual('!!!111');});it('should always provide access to the original and the current replacement function',function(){var mutated=mutable(original);var rewrite=jest.fn();mutated.replace(rewrite);expect(mutated.original).toBe(original);expect(mutated.current).toEqual(rewrite);});});
|
|
@@ -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;}/* eslint-disable extra-rules/no-single-line-objects */import{shouldFetchData}from"../shouldFetchData";describe('shouldFetchData',function(){describe('should return false',function(){var tests=[['when currently fetching',{isFetching:true}],['when not yet expired',{items:Array(10),totalResultCount:20,expires:Date.now()+1e3}],['when not yet expired and requiredCount pass',{items:Array(10),totalResultCount:20,expires:Date.now()+1e3},10],['when enough items in store',{items:Array(10),totalResultCount:20}],['when enough items in store by requiredCount',{items:Array(20),totalResultCount:20},20]];tests.forEach(function(_ref){var _ref2=_slicedToArray(_ref,3),title=_ref2[0],item=_ref2[1],_ref2$=_ref2[2],requiredCount=_ref2$===void 0?null:_ref2$;it("should return false ".concat(title),function(){expect(shouldFetchData(item,'items',requiredCount)).toBeFalsy();});});});describe('should return true',function(){var tests=[['when item is empty',null],['when item is empty object',{}],['when not cached: expire=0',{isFetching:false,expires:0}],['when expired',{isFetching:false,expires:Date.now()-1e3}],['when totalResultCount is less then items count',{items:Array(10),totalResultCount:5}],['when requiredCount is less then items count',{items:Array(10),totalResultCount:5},5]];tests.forEach(function(_ref3){var _ref4=_slicedToArray(_ref3,3),title=_ref4[0],item=_ref4[1],_ref4$=_ref4[2],requiredCount=_ref4$===void 0?null:_ref4$;it("should return true ".concat(title),function(){expect(shouldFetchData(item,'items',requiredCount)).toBeTruthy();});});});});/* eslint-enable extra-rules/no-single-line-objects */
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _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 PropTypes from'prop-types';import{mount}from'enzyme';import{UIEvents}from'@shopgate/pwa-core';import LoadingContext from"./context";import LoadingProvider from"./index";jest.unmock('@shopgate/pwa-core');var MOCKED_PATH='some/path';/**
|
|
2
|
-
* @param {Object} props The component props.
|
|
3
|
-
* @return {JSX}
|
|
4
|
-
*/var MockComponent=function MockComponent(_ref){var isLoading=_ref.isLoading,path=_ref.path;return isLoading(path)?/*#__PURE__*/React.createElement("div",null):null;};/**
|
|
5
|
-
* @param {string} path A mocked path.
|
|
6
|
-
* @return {JSX}
|
|
7
|
-
*/var createWrapper=function createWrapper(){var path=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'/';var wrapper=mount(/*#__PURE__*/React.createElement(LoadingProvider,null,/*#__PURE__*/React.createElement(LoadingContext.Consumer,null,function(props){return/*#__PURE__*/React.createElement(MockComponent,_extends({},props,{path:path}));})));return wrapper;};describe('LoadingProvider',function(){beforeAll(function(){jest.resetAllMocks();jest.spyOn(UIEvents,'addListener');jest.spyOn(UIEvents,'removeListener');jest.spyOn(UIEvents,'emit');});beforeEach(function(){jest.clearAllMocks();});it('should not render the child component when the current path is not loading',function(){var wrapper=createWrapper();expect(wrapper).toMatchSnapshot();expect(wrapper.state('loading')).toEqual(new Map());expect(wrapper.find('MockComponent > div').exists()).toBe(false);});it('should render the child component when the current path is loading',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var wrapper;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:wrapper=createWrapper(MOCKED_PATH);expect(wrapper).toMatchSnapshot();wrapper.instance().setLoading(MOCKED_PATH);wrapper.update();setTimeout(function(){expect(wrapper.find('MockComponent > div').exists()).toBe(true);wrapper.instance().unsetLoading(MOCKED_PATH);wrapper.update();expect(wrapper.find('MockComponent > div').exists()).toBe(false);},0);case 5:case"end":return _context.stop();}}},_callee);})));it('should populate internal methods its children',function(){var wrapper=createWrapper();expect(wrapper).toMatchSnapshot();var child=wrapper.find('MockComponent');expect(child.prop('setLoading')).toEqual(wrapper.instance().setLoading);expect(child.prop('unsetLoading')).toEqual(wrapper.instance().unsetLoading);expect(child.prop('isLoading')).toEqual(wrapper.instance().isLoading);expect(child.prop('loading')).toEqual(wrapper.state('loading'));});it('should register event listeners within the constructor',function(){var wrapper=createWrapper();expect(UIEvents.addListener).toHaveBeenCalledTimes(3);expect(UIEvents.addListener).toHaveBeenCalledWith(LoadingProvider.SET,wrapper.instance().setLoading);expect(UIEvents.addListener).toHaveBeenCalledWith(LoadingProvider.RESET,wrapper.instance().resetLoading);expect(UIEvents.addListener).toHaveBeenCalledWith(LoadingProvider.UNSET,wrapper.instance().unsetLoading);});it('should remove event listeners within componentWillUnmount',function(){var wrapper=createWrapper();wrapper.unmount();expect(UIEvents.removeListener).toHaveBeenCalledTimes(3);expect(UIEvents.removeListener).toHaveBeenCalledWith(LoadingProvider.SET,expect.any(Function));expect(UIEvents.removeListener).toHaveBeenCalledWith(LoadingProvider.RESET,expect.any(Function));expect(UIEvents.removeListener).toHaveBeenCalledWith(LoadingProvider.UNSET,expect.any(Function));});describe('LoadingProvider.setLoading()',function(){it('should emit the SET event',function(){LoadingProvider.setLoading(MOCKED_PATH);expect(UIEvents.emit).toHaveBeenCalledTimes(1);expect(UIEvents.emit).toHaveBeenCalledWith(LoadingProvider.SET,MOCKED_PATH);});});describe('LoadingProvider.resetLoading()',function(){it('should emit the RESET event',function(){LoadingProvider.resetLoading(MOCKED_PATH);expect(UIEvents.emit).toHaveBeenCalledTimes(1);expect(UIEvents.emit).toHaveBeenCalledWith(LoadingProvider.RESET,MOCKED_PATH);});});describe('LoadingProvider.unsetLoading()',function(){it('should emit the UNSET event',function(){LoadingProvider.unsetLoading(MOCKED_PATH);expect(UIEvents.emit).toHaveBeenCalledTimes(1);expect(UIEvents.emit).toHaveBeenCalledWith(LoadingProvider.UNSET,MOCKED_PATH);});});describe('.setLoading()',function(){it('should increase the loading counter for a path',function(){var instance=createWrapper().instance();var loading=instance.state.loading;expect(loading.has(MOCKED_PATH)).toBe(false);instance.setLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(true);expect(loading.get(MOCKED_PATH)).toBe(1);instance.setLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(true);expect(loading.get(MOCKED_PATH)).toBe(2);});});describe('.resetLoading()',function(){it('should resets the loading counter for a path',function(){var instance=createWrapper().instance();var loading=instance.state.loading;expect(loading.has(MOCKED_PATH)).toBe(false);instance.resetLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(false);instance.setLoading(MOCKED_PATH);instance.setLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(true);expect(loading.get(MOCKED_PATH)).toBe(2);instance.resetLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(false);});});describe('.unsetLoading()',function(){it('should decrease the loading counter for a path',function(){var instance=createWrapper().instance();var loading=instance.state.loading;instance.setLoading(MOCKED_PATH);instance.setLoading(MOCKED_PATH);instance.unsetLoading(MOCKED_PATH);expect(loading.get(MOCKED_PATH)).toBe(1);instance.unsetLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(false);instance.unsetLoading(MOCKED_PATH);expect(loading.has(MOCKED_PATH)).toBe(false);});});describe('.isLoading()',function(){it('should work as expected',function(){var ANOTHER_PATH='/some/other/path';var instance=createWrapper().instance();expect(instance.isLoading(MOCKED_PATH)).toBe(false);expect(instance.isLoading(ANOTHER_PATH)).toBe(false);instance.setLoading(MOCKED_PATH);expect(instance.isLoading(MOCKED_PATH)).toBe(true);expect(instance.isLoading(ANOTHER_PATH)).toBe(false);instance.setLoading(ANOTHER_PATH);expect(instance.isLoading(MOCKED_PATH)).toBe(true);expect(instance.isLoading(ANOTHER_PATH)).toBe(true);instance.unsetLoading(MOCKED_PATH);instance.unsetLoading(MOCKED_PATH);instance.unsetLoading(ANOTHER_PATH);instance.unsetLoading(ANOTHER_PATH);expect(instance.isLoading(MOCKED_PATH)).toBe(false);expect(instance.isLoading(ANOTHER_PATH)).toBe(false);});});});
|
|
@@ -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{RECEIVE_CLIENT_CONNECTIVITY}from"../../constants/ActionTypes";import{CONNECTIVITY_NETWORK_UNKNOWN,CONNECTIVITY_TYPE_UNKNOWN,CONNECTIVITY_TYPE_WIFI}from"../../constants/client";import reducer from"./connectivity";describe('Client connectivity reducer',function(){it('should return the default state when no previous state is present, and no action type was passed',function(){var state=reducer(undefined,{});var expected={connected:true,network:CONNECTIVITY_NETWORK_UNKNOWN,type:CONNECTIVITY_TYPE_UNKNOWN};expect(state).toEqual(expected);});it('should return the state when no action type was passed',function(){var previous={connected:false,network:CONNECTIVITY_TYPE_WIFI,type:CONNECTIVITY_TYPE_WIFI};var state=reducer(previous,{});expect(state).toBe(previous);});it('should update the state at RECEIVE_CLIENT_CONNECTIVITY ',function(){var previous={connected:false,network:CONNECTIVITY_NETWORK_UNKNOWN,type:CONNECTIVITY_TYPE_UNKNOWN};var updated={connected:true,network:CONNECTIVITY_TYPE_WIFI,type:CONNECTIVITY_TYPE_WIFI};var state=reducer(previous,{data:_extends({},updated),type:RECEIVE_CLIENT_CONNECTIVITY});expect(state).toEqual(updated);});it('should update the state at RECEIVE_CLIENT_CONNECTIVITY when only the connected property is present in the action data',function(){var previous={connected:true,network:CONNECTIVITY_TYPE_WIFI,type:CONNECTIVITY_TYPE_WIFI};var expected={connected:false,network:CONNECTIVITY_NETWORK_UNKNOWN,type:CONNECTIVITY_TYPE_UNKNOWN};var state=reducer(previous,{data:{connected:false},type:RECEIVE_CLIENT_CONNECTIVITY});expect(state).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);}import{REQUEST_CLIENT_INFORMATION,RECEIVE_CLIENT_INFORMATION,ERROR_CLIENT_INFORMATION}from"../../constants/ActionTypes";import reducer from"./info";var mockState={libVersion:'17.0',data:{},isFetching:false};describe('Client information reducer',function(){it('should return the default state when no previous state is present, and no action type was passed',function(){var state=reducer(undefined,{});expect(state).toEqual({});});it('should return the previous state when no action type was passed',function(){var previous=_extends({},mockState);var state=reducer(previous,{});expect(state).toBe(previous);});it('should set isFetching to TRUE at REQUEST_CLIENT_INFORMATION ',function(){var previous={libVersion:'17.0',isFetching:false};var expected={libVersion:'17.0',isFetching:true};var state=reducer(previous,{type:REQUEST_CLIENT_INFORMATION,data:{libVersion:'17.0'}});expect(state).toEqual(expected);});it('should set isFetching to FALSE at RECEIVE_CLIENT_INFORMATION ',function(){var previous={libVersion:'17.0',isFetching:true};var expected={libVersion:'21.0',isFetching:false};var state=reducer(previous,{type:RECEIVE_CLIENT_INFORMATION,data:{libVersion:'21.0'}});expect(state).toEqual(expected);});it('should set isFetching to FALSE at ERROR_CLIENT_INFORMATION ',function(){var previous={libVersion:'17.0',isFetching:true};var expected={libVersion:'17.0',isFetching:false};var state=reducer(previous,{type:ERROR_CLIENT_INFORMATION,data:{libVersion:'21.0'}});expect(state).toEqual(expected);});});
|
package/reducers/index.spec.js
DELETED
|
@@ -1,6 +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 configuration from"../collections/Configuration";import{RESET_APP}from"../constants/ActionTypes";import makeRootReducer from"./index";describe('makeRootReducer',function(){var state={};var action={type:RESET_APP};var appReducers;var rootReducer;beforeEach(function(){appReducers=jest.fn();rootReducer=makeRootReducer(appReducers);state.app={};state.view={};});it('should pass state to app reducers',function(){rootReducer(state,action);var _appReducers$mock$cal=_slicedToArray(appReducers.mock.calls,1),_appReducers$mock$cal2=_slicedToArray(_appReducers$mock$cal[0],2),arg1=_appReducers$mock$cal2[0],arg2=_appReducers$mock$cal2[1];expect(arg1).toBe(state);expect(arg2).toBe(action);});it('should reset default reducers from config',function(){var spy=jest.spyOn(configuration,'get').mockReturnValueOnce(['view']);rootReducer(state,action);var _appReducers$mock$cal3=_slicedToArray(appReducers.mock.calls,1),_appReducers$mock$cal4=_slicedToArray(_appReducers$mock$cal3[0],2),arg1=_appReducers$mock$cal4[0],arg2=_appReducers$mock$cal4[1];expect(spy).toBeCalledTimes(1);expect(arg1).toBe(state);expect(arg2).toBe(action);// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
2
|
-
expect(arg1).toEqual({app:{},view:undefined});});it('should reset reducers from action',function(){// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
3
|
-
var resetAction={type:RESET_APP,reducers:['app']};rootReducer(state,resetAction);var _appReducers$mock$cal5=_slicedToArray(appReducers.mock.calls,1),_appReducers$mock$cal6=_slicedToArray(_appReducers$mock$cal5[0],2),arg1=_appReducers$mock$cal6[0],arg2=_appReducers$mock$cal6[1];expect(arg1).toBe(state);expect(arg2).toBe(resetAction);// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
4
|
-
expect(arg1).toEqual({app:undefined,view:{}});});it('should skip unknown reducers',function(){// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
5
|
-
var resetAction={type:RESET_APP,reducers:['foobar']};rootReducer(state,resetAction);var _appReducers$mock$cal7=_slicedToArray(appReducers.mock.calls,1),_appReducers$mock$cal8=_slicedToArray(_appReducers$mock$cal7[0],2),arg1=_appReducers$mock$cal8[0],arg2=_appReducers$mock$cal8[1];expect(arg1).toBe(state);expect(arg2).toBe(resetAction);// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
6
|
-
expect(arg1).toEqual({app:{},view:{}});});});
|
package/selectors/client.spec.js
DELETED
|
@@ -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{SCANNER_MIN_APP_LIB_VERSION}from'@shopgate/pwa-core/constants/Scanner';import{getClientInformation,getClientConnectivity,hasScannerSupport,getDeviceInformation,getPlatform,getDeviceModel,isAndroid,isIos,getPageInsets,getIsConnected,getClientConnectivityNetwork,getClientConnectivityType,makeGetSupportedIdentityServices,makeSupportsIdentityService}from"./client";import{OS_ANDROID,OS_IOS,MODEL_NAMES_IPHONE_X,PAGE_INSETS_ANDROID,PAGE_INSETS_IOS,PAGE_INSETS_IPHONE_X}from"../constants/Device";import{CONNECTIVITY_TYPE_4G}from"../constants/client";var mockedHasSGJavaScriptBridge;jest.mock('@shopgate/pwa-core/helpers',function(){return{hasSGJavaScriptBridge:function hasSGJavaScriptBridge(){return mockedHasSGJavaScriptBridge();},logger:{error:jest.fn()}};});describe('Client selectors',function(){describe('Client information',function(){var mockedStateAndroid={isFetching:false,device:{model:'Samsung Galaxy S9',type:'phone',os:{platform:'android',ver:'9.0'}}};var mockedStateIPhoneX={isFetching:false,device:{model:MODEL_NAMES_IPHONE_X[0],type:'phone',os:{platform:'ios',ver:'11.0'}},supportedIdentityServices:['apple','facebook']};/**
|
|
2
|
-
* Creates a mocked state.
|
|
3
|
-
* @param {Object} state The sub-state of the client state.
|
|
4
|
-
* @returns {Object}
|
|
5
|
-
*/var createMockState=function createMockState(state){return{client:{info:_extends({},state)}};};describe('getClientInformation()',function(){it('should return an empty object if the client state is not ready yet',function(){var result=getClientInformation(createMockState({}));expect(result).toEqual({});});it('should return the expected state',function(){var result=getClientInformation(createMockState(mockedStateAndroid));expect(result).toEqual(mockedStateAndroid);});});describe('hasScannerSupport()',function(){it('should return true when the app supports the scanner',function(){var result=hasScannerSupport(createMockState({libVersion:SCANNER_MIN_APP_LIB_VERSION}));expect(result).toBeTruthy();});it('should return false when the app does not support the scanner',function(){var result=hasScannerSupport(createMockState({libVersion:'17.0'}));expect(result).toBeFalsy();});it('should return false when the app lib version is unknown',function(){var result=hasScannerSupport(createMockState({}));expect(result).toBeFalsy();});});describe('getDeviceInformation()',function(){it('should return null if the client state is not ready yet',function(){var result=getDeviceInformation(createMockState({}));expect(result).toBeNull();});it('should return null if the client state does not contain the requested data',function(){var state=createMockState(_extends({},mockedStateAndroid,{device:undefined}));var result=getDeviceInformation(state);expect(result).toBeNull();});it('should return the expected state',function(){var result=getDeviceInformation(createMockState(mockedStateAndroid));expect(result).toEqual(mockedStateAndroid.device);});});describe('getPlatform()',function(){it('should return null if the client state is not ready yet',function(){var result=getPlatform(createMockState({}));expect(result).toBeNull();});it('should return Android as platform',function(){var result=getPlatform(createMockState(mockedStateAndroid));expect(result).toEqual(OS_ANDROID);});it('should return iOS as platform',function(){var result=getPlatform(createMockState(mockedStateIPhoneX));expect(result).toEqual(OS_IOS);});});describe('getDeviceModel()',function(){it('should return null if the client state is not ready yet',function(){var result=getDeviceModel(createMockState({}));expect(result).toBeNull();});it('should return the correct device model',function(){var result=getDeviceModel(createMockState(mockedStateIPhoneX));expect(result).toEqual(MODEL_NAMES_IPHONE_X[0]);});});describe('isAndroid()',function(){it('should return false if the client state is not ready yet',function(){var result=isAndroid(createMockState({}));expect(result).toBe(false);});it('should return false on iOS devices',function(){var result=isAndroid(createMockState(mockedStateIPhoneX));expect(result).toBe(false);});it('should return true on Android devices',function(){var result=isAndroid(createMockState(mockedStateAndroid));expect(result).toBe(true);});});describe('isIos()',function(){it('should return false if the client state is not ready yet',function(){var result=isIos(createMockState({}));expect(result).toBe(false);});it('should return false on Android devices',function(){var result=isIos(createMockState(mockedStateAndroid));expect(result).toBe(false);});it('should return true on iOS devices',function(){var result=isIos(createMockState(mockedStateIPhoneX));expect(result).toBe(true);});});describe('getPageInsets()',function(){beforeEach(function(){mockedHasSGJavaScriptBridge=jest.fn(function(){return true;});});it('should return the Android insets if the client state is not ready yet',function(){var result=getPageInsets(createMockState({}));expect(result).toEqual(PAGE_INSETS_ANDROID);});it('should return the Android insets on Android devices',function(){var result=getPageInsets(createMockState(mockedStateAndroid));expect(result).toEqual(PAGE_INSETS_ANDROID);});it('should return the Android insets when no SGJavaScriptBridge is available',function(){mockedHasSGJavaScriptBridge=jest.fn(function(){return false;});var result=getPageInsets(createMockState(mockedStateAndroid));expect(result).toEqual(PAGE_INSETS_ANDROID);});it('should return the default iOS insets on iOS devices',function(){var state=createMockState(_extends({},mockedStateIPhoneX,{device:_extends({},mockedStateIPhoneX.device,{model:'iPhone8,1'})}));var result=getPageInsets(state);expect(result).toEqual(PAGE_INSETS_IOS);});it('should return the iPhone X insets on an iPhone X',function(){var result=getPageInsets(createMockState(mockedStateIPhoneX));expect(result).toEqual(PAGE_INSETS_IPHONE_X);});});describe('supportedIdentityServices()',function(){it('should return identity services',function(){var selector=makeGetSupportedIdentityServices();var result=selector(createMockState(mockedStateIPhoneX));expect(result).toEqual(mockedStateIPhoneX.supportedIdentityServices);});it('should support identity service apple',function(){var selector=makeSupportsIdentityService('apple');var result=selector(createMockState(mockedStateIPhoneX));expect(result).toEqual(true);});});});describe('Client connectivity',function(){/**
|
|
6
|
-
* Creates a mocked state.
|
|
7
|
-
* @param {Object} state The sub-state of the client state.
|
|
8
|
-
* @returns {Object}
|
|
9
|
-
*/var createMockState=function createMockState(state){return{client:{connectivity:_extends({},state)}};};var mockedNetwork=CONNECTIVITY_TYPE_4G;var mockedType='LTE';var mockedState={connected:true,network:mockedNetwork,type:mockedType};describe('getClientConnectivity()',function(){it('should return an empty object if the client state is not ready yet',function(){var result=getClientConnectivity(createMockState({}));expect(result).toEqual({});});it('should return the expected state',function(){var result=getClientConnectivity(createMockState(mockedState));expect(result).toEqual(mockedState);});});describe('getIsConnected()',function(){it('should return TRUE',function(){var result=getIsConnected(createMockState(mockedState));expect(result).toBe(true);});});describe('getClientConnectivityNetwork()',function(){it('should return 4G',function(){var result=getClientConnectivityNetwork(createMockState(mockedState));expect(result).toBe(mockedNetwork);});});describe('getClientConnectivityType()',function(){it('should return LTE',function(){var result=getClientConnectivityType(createMockState(mockedState));expect(result).toBe(mockedType);});});});});
|
package/selectors/modal.spec.js
DELETED
|
@@ -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{getModalState,getFirstModal,getModalById}from"./modal";var defaultEntry={id:'abc',confirm:null,dismiss:'modal.dismiss',message:'Message',params:{},title:'Title',type:null};var mockedState={modal:[_extends({},defaultEntry),_extends({},defaultEntry,{id:'123'})]};describe('Modal selectors',function(){describe('getModalState()',function(){it('should return an empty object if the modal state is not ready yet',function(){var result=getModalState({});expect(result).toEqual([]);});it('should return an empty object if the modal state is empty',function(){var result=getModalState({modal:[]});expect(result).toEqual([]);});it('should return the expected state',function(){var result=getModalState(_extends({},mockedState));expect(result).toEqual(mockedState.modal);});});describe('getFirstModal()',function(){it('should return undefined when the modal stack is empty',function(){var result=getFirstModal({modal:[]});expect(result).toBeUndefined();});it('should return the first modal from the stack',function(){var result=getFirstModal(_extends({},mockedState));expect(result).toEqual(mockedState.modal[0]);});});describe('getModalById()',function(){it('should return undefined when the modal stack is empty',function(){var result=getModalById({modal:[]});expect(result).toBeUndefined();});it('should return the correct modal from the stack',function(){var result=getModalById(_extends({},mockedState),mockedState.modal[1].id);expect(result).toEqual(mockedState.modal[1]);});});});
|
package/selectors/router.spec.js
DELETED
|
@@ -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{makeIsLastStackEntry,makeGetRoutePattern,makeGetRouteParam,makeGetPrevRoute}from"./router";var mockState={router:{stack:[{id:'abc',pathname:'/',pattern:'/',state:{}},{id:'123',pathname:'/some-route',pattern:'/some-route',state:{},params:{key:'value'}},{id:'234',pathname:'/some-route2',pattern:'/some-route2',state:{}}],currentRoute:{id:'123',pathname:'/some-route',pattern:'/some-route',state:{},params:{key:'value'}}}};describe('Router selectors',function(){describe('makeIsLastStackEntry()',function(){it('should create a fresh instance on every call',function(){var instanceOne=makeIsLastStackEntry();var instanceTwo=makeIsLastStackEntry();expect(instanceOne).not.toBe(instanceTwo);});it('should return TRUE when the routeId belongs to the last stack entry',function(){var isLastStackEntry=makeIsLastStackEntry();var result=isLastStackEntry(mockState,{routeId:'234'});expect(result).toBe(true);});it('should return FALSE when the routeId does not belong to the last stack entry',function(){var isLastStackEntry=makeIsLastStackEntry();var result=isLastStackEntry(mockState,{routeId:'123'});expect(result).toBe(false);});it('should return FALSE when the stack is empty',function(){var isLastStackEntry=makeIsLastStackEntry();var result=isLastStackEntry({router:{stack:[]}},{routeId:'xyz'});expect(result).toBe(false);});});describe('makeGetPrevRoute()',function(){var getPrevRoute;beforeEach(function(){getPrevRoute=makeGetPrevRoute();});it('should return null for index route',function(){var result=getPrevRoute({router:_extends({currentRoute:mockState.router.stack[0]},mockState.router)},{routeId:'abc'});expect(result).toBeNull();});it('should return prev for last route',function(){var result=getPrevRoute({router:_extends({currentRoute:mockState.router.stack[2]},mockState.router)},{routeId:'234'});expect(result).toEqual(mockState.router.stack[1]);});it('should return prev for not last route',function(){var result=getPrevRoute({router:_extends({currentRoute:mockState.router.stack[1]},mockState.router)},{routeId:'123'});expect(result).toEqual(mockState.router.stack[0]);});});describe('makeGetRoutePattern()',function(){it('should create a fresh instance on every call',function(){var instanceOne=makeGetRoutePattern();var instanceTwo=makeGetRoutePattern();expect(instanceOne).not.toBe(instanceTwo);});it('should return the expected route pattern for the current route',function(){var getRoutePattern=makeGetRoutePattern();var result=getRoutePattern(mockState,{});expect(result).toBe('/some-route');});it('should return the expected route pattern for a route referenced by a routeId',function(){var getRoutePattern=makeGetRoutePattern();var result=getRoutePattern(mockState,{routeId:'123'});expect(result).toBe('/some-route');});it('should return NULL when no route can be determined',function(){var getRoutePattern=makeGetRoutePattern();var result=getRoutePattern({router:{stack:[]}},{routeId:'xyz'});expect(result).toBe(null);});});describe('makeGetRouteParam()',function(){it('should create a fresh instance on every call',function(){var instanceOne=makeGetRouteParam();var instanceTwo=makeGetRouteParam();expect(instanceOne).not.toBe(instanceTwo);});it('should return the expected route param for the current route',function(){var getRouteParam=makeGetRouteParam('key');var result=getRouteParam(mockState,{});expect(result).toBe('value');});it('should return the expected route pattern for a route referenced by a routeId',function(){var getRouteParam=makeGetRouteParam('key');var result=getRouteParam(mockState,{routeId:'123'});expect(result).toBe('value');});it('should return NULL when no route params can be determined',function(){var getRouteParam=makeGetRouteParam('key');var result=getRouteParam(mockState,{routeId:'abc'});expect(result).toBe(null);});it('should return NULL when the requested parameter does not exist within the params',function(){var getRouteParam=makeGetRouteParam('does-not-exist');var result=getRouteParam(mockState);expect(result).toBe(null);});});});
|
package/streams/app.spec.js
DELETED
|
@@ -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{createMockStore}from"../store";import{pwaDidAppear,pwaDidDisappear}from"../action-creators";import{pwaDidAppear$,pwaDidDisappear$}from"./app";var mockedPattern;jest.mock("../selectors/router",function(){return{getCurrentRoute:function getCurrentRoute(){return{pattern:mockedPattern};}};});describe('App streams',function(){var pwaDidAppearSubscriber;var pwaDidDisappearSubscriber;var dispatch;beforeEach(function(){mockedPattern='';jest.clearAllMocks();var _createMockStore=createMockStore();dispatch=_createMockStore.dispatch;pwaDidAppearSubscriber=jest.fn();pwaDidDisappearSubscriber=jest.fn();pwaDidAppear$.subscribe(pwaDidAppearSubscriber);pwaDidDisappear$.subscribe(pwaDidDisappearSubscriber);});describe('pwaDidAppear$',function(){it('should emit when the pwaDidAppear action is dispatched',function(){mockedPattern='/somepath';dispatch(pwaDidAppear());expect(pwaDidAppearSubscriber).toHaveBeenCalledTimes(1);var _pwaDidAppearSubscrib=_slicedToArray(pwaDidAppearSubscriber.mock.calls,1),_pwaDidAppearSubscrib2=_slicedToArray(_pwaDidAppearSubscrib[0],1),action=_pwaDidAppearSubscrib2[0].action;expect(action.route.pattern).toEqual(mockedPattern);});it('should not emit when another action is dispatched',function(){dispatch({type:'someaction'});expect(pwaDidAppearSubscriber).not.toHaveBeenCalled();});});describe('pwaDidDisappear$',function(){it('should emit when the pwaDidDisappear action is dispatched',function(){mockedPattern='/somepath';dispatch(pwaDidDisappear());expect(pwaDidDisappearSubscriber).toHaveBeenCalledTimes(1);var _pwaDidDisappearSubsc=_slicedToArray(pwaDidDisappearSubscriber.mock.calls,1),_pwaDidDisappearSubsc2=_slicedToArray(_pwaDidDisappearSubsc[0],1),action=_pwaDidDisappearSubsc2[0].action;expect(action.route.pattern).toEqual(mockedPattern);});it('should not emit when another action is dispatched',function(){dispatch({type:'someaction'});expect(pwaDidDisappearSubscriber).not.toHaveBeenCalled();});});});
|
package/streams/user.spec.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import{successLogin,receiveUser}from"../action-creators/user";import{configureStore}from"../store";import{userDidLogin$,userDidUpdate$}from"./user";jest.mock('redux-logger',function(){return{createLogger:function createLogger(){return function(){return function(next){return function(action){return next(action);};};};}};});/**
|
|
2
|
-
* A mocked dummy reducer to satisfy the store creation.
|
|
3
|
-
* @param {Object} state The current redux state.
|
|
4
|
-
* @return {Object} The unchanged state.
|
|
5
|
-
*/var mockedReducer=function mockedReducer(){var state=arguments.length>0&&arguments[0]!==undefined?arguments[0]:{};return state;};describe.skip('streams/user.js',function(){var _configureStore=configureStore({mocked:mockedReducer}),dispatch=_configureStore.dispatch;var loginMockSubscriber;var updateMockSubscriber;beforeEach(function(){loginMockSubscriber=jest.fn();updateMockSubscriber=jest.fn();userDidLogin$.subscribe(loginMockSubscriber);userDidUpdate$.subscribe(updateMockSubscriber);});describe('Given the successLogin action gets dispatched',function(){beforeEach(function(){dispatch(successLogin());});it('should emit into userDidLogin$',function(){expect(loginMockSubscriber).toBeCalled();expect(loginMockSubscriber.mock.calls).toHaveLength(1);});});describe('Given the receiveUser action gets dispatched',function(){beforeEach(function(){dispatch(receiveUser());});it('should emit into userDidUpdate$',function(){expect(updateMockSubscriber).toBeCalled();expect(updateMockSubscriber.mock.calls).toHaveLength(1);});});});
|
|
@@ -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{appWillStart$}from"../streams/app";import{embeddedMedia}from"../collections";import{Vimeo,YouTube}from"../collections/media-providers";import subscription from"./app";describe.skip('App subscriptions',function(){var subscribe=jest.fn();var dispatch=jest.fn();beforeEach(function(){jest.clearAllMocks();subscription(subscribe);});describe('appWillStart$',function(){var stream;var callback;beforeEach(function(){var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,1);var _subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);stream=_subscribe$mock$calls2[0];callback=_subscribe$mock$calls2[1];embeddedMedia.constructor();});it('should initialize',function(){expect(stream).toEqual(appWillStart$);expect(callback).toBeInstanceOf(Function);});it('should add media providers',function(){var addProviderSpy=jest.spyOn(embeddedMedia,'addProvider');var action={location:'foo'};callback({dispatch:dispatch,action:action});expect(addProviderSpy).toHaveBeenCalledTimes(2);expect(addProviderSpy).toHaveBeenCalledWith(expect.any(YouTube));expect(addProviderSpy).toHaveBeenCalledWith(expect.any(Vimeo));});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import queryString from'query-string';import{LEGACY_URL}from"../../constants/Registration";import{CHECKOUT_PATH,INDEX_PATH}from"../../constants/RoutePaths";import buildRegisterUrl from"./buildRegisterUrl";describe('buildRegisterUrl',function(){it('should create the expected url when no redirect was passed',function(){var result=queryString.parseUrl(buildRegisterUrl(LEGACY_URL));expect(result.url).toBe(LEGACY_URL);expect(result.query).toEqual({sgcloud_callback_data:"{\"redirectTo\":\"".concat(INDEX_PATH,"\"}")});});it('should create the expected url when no redirect was passed and the source url includes GET parameters',function(){var result=queryString.parseUrl(buildRegisterUrl("".concat(LEGACY_URL,"?foo=bar")));expect(result.url).toBe(LEGACY_URL);expect(result.query).toEqual({foo:'bar',sgcloud_callback_data:"{\"redirectTo\":\"".concat(INDEX_PATH,"\"}")});});it('should create the expected url when a common redirect url with GET parameters was passed',function(){var result=queryString.parseUrl(buildRegisterUrl(LEGACY_URL,'/some_url?foo=bar'));expect(result.url).toBe(LEGACY_URL);expect(result.query).toEqual({sgcloud_callback_data:'{"redirectTo":"/some_url?foo=bar"}'});});it('should create the expected url when a checkout redirect url was passed',function(){var result=queryString.parseUrl(buildRegisterUrl("".concat(LEGACY_URL,"?foo=bar"),CHECKOUT_PATH));expect(result.url).toBe(LEGACY_URL);expect(result.query).toEqual({foo:'bar',sgcloud_callback_data:"{\"redirectTo\":\"".concat(INDEX_PATH,"\"}"),sgcloud_checkout:'1'});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import cleanTab from'@shopgate/pwa-core/commands/cleanTab';import clearUpInAppBrowser from"./clearUpInAppBrowser";jest.mock('@shopgate/pwa-core/commands/popTabToRoot',function(){return jest.fn();});jest.mock('@shopgate/pwa-core/commands/cleanTab',function(){return jest.fn();});describe('clearUpInAppBrowser',function(){beforeEach(function(){jest.clearAllMocks();});it('should call the cleanTab command on Android devices',function(){clearUpInAppBrowser(true);expect(cleanTab).toHaveBeenCalled();});it('should call the popTabToRoot command on iOS devices',function(){clearUpInAppBrowser(false);expect(cleanTab).not.toHaveBeenCalled();});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{openPageExtern,openPage}from'@shopgate/pwa-core';import{isShopLink,sanitizeLink,openExternalLink}from"./handleLinks";jest.mock('@shopgate/pwa-core',function(){return{openPageExtern:jest.fn(),openPage:jest.fn()};});jest.mock('@shopgate/pwa-common/helpers/config',function(){return{shopCNAME:'m.example.com'};});describe('handleLinks helpers',function(){describe('isShopLink()',function(){var positives=['http://foo.shopgate.com','https://foo.shopgate.com','http://foo.shopgate.com/page/cms','https://foo.shopgate.com/page/cms','https://m.example.com','http://m.example.com','http://m.example.com/page/cms','https://m.example.com/page/cms','https://M.ExamPle.com/page/CMS'];var negatives=['https://example.com/bar','https://example.com','http://shopgate.com/foo','https://shopgate.com/foo','https://www.shopgate.com','http://www.shopgate.com','http://example.com','https://example.com','https://example.com/page/cms','?foo=bar'];positives.forEach(function(href){it("should return true for ".concat(href," link"),function(){expect(isShopLink(href)).toBe(true);});});negatives.forEach(function(href){it("should return false for ".concat(href," link"),function(){expect(isShopLink(href)).toBe(false);});});});describe('sanitizeLink()',function(){var links=[['http://m.example.com/','http://m.example.com'],['/page/title/','/page/title'],['/page/title','/page/title'],['tel:1234/','tel:1234'],['tel:1234','tel:1234'],['mailto:noreply@shopgate.com','mailto:noreply@shopgate.com'],['/cart/?coupon=test','/cart?coupon=test']];it.each(links)('should sanitize %s to %s',function(input,output){expect(sanitizeLink(input)).toBe(output);});});describe('openExternalLink',function(){it('should call openPageExtern',function(){var location='http://m.me/shopgate';openExternalLink(location,'ACTION',{},{target:'_blank'});expect(openPageExtern).toBeCalledTimes(1);expect(openPageExtern).toBeCalledWith({src:location});expect(openPage).not.toBeCalled();});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import{transformGeneralPipelineError}from"./pipeline";describe('transformGeneralPipelineError',function(){var general=['An internal error occured.','502 Bad Gateway','error from bigApi 504','BigApi request timeout','error in bigApi response'];var others=['Some other pipeline error','Login was unsuccessful'];general.forEach(function(message){it("should return general for ".concat(message),function(){expect(transformGeneralPipelineError({message:message})).toBe('error.general');});});others.forEach(function(message){it("should return original ".concat(message),function(){expect(transformGeneralPipelineError({message:message})).toBe(message);});});});
|
|
@@ -1,21 +0,0 @@
|
|
|
1
|
-
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function _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 _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{router,ACTION_POP,ACTION_PUSH,ACTION_REPLACE,ACTION_RESET}from'@virtuous/conductor';import{LoadingProvider}from'@shopgate/pwa-common/providers';import{redirects}from'@shopgate/pwa-common/collections';import{logger}from'@shopgate/pwa-core/helpers';import{historyRedirect,historyPush,windowOpenOverride}from"../actions/router";import authRoutes from"../collections/AuthRoutes";import*as handler from"./helpers/handleLinks";import{navigate$,appWillStart$,windowOpenOverride$}from"../streams";import{navigate}from"../action-creators";import{getIsConnected}from"../selectors/client";import ToastProvider from"../providers/toast";import subscriptions from"./router";jest.unmock('@shopgate/pwa-core');jest.mock('@shopgate/pwa-core/classes/AppCommand');jest.mock('@virtuous/conductor',function(){return{ACTION_POP:'ACTION_POP',ACTION_PUSH:'ACTION_PUSH',ACTION_REPLACE:'ACTION_REPLACE',ACTION_RESET:'ACTION_RESET',router:{pop:jest.fn(),push:jest.fn(),reset:jest.fn(),replace:jest.fn(),getCurrentRoute:jest.fn(),findPattern:jest.fn(),patterns:{}}};});var mockedShopCNAME=null;var mockedWebCheckoutConfig=null;jest.mock('@shopgate/pwa-common/helpers/config',function(){return{get shopCNAME(){return mockedShopCNAME;},get webCheckoutShopify(){return mockedWebCheckoutConfig;},themeConfig:{}};});jest.mock('@shopgate/pwa-core/helpers/logGroup',function(){return jest.fn();});jest.mock("../actions/router",function(){var _jest$requireActual=jest.requireActual('../actions/router'),windowOpenOriginal=_jest$requireActual.windowOpenOverride;return{windowOpenOverride:jest.fn(function(){return windowOpenOriginal.apply(void 0,arguments);}),historyRedirect:jest.fn(),historyPush:jest.fn()};});jest.mock("../selectors/client",function(){return{getIsConnected:jest.fn().mockReturnValue(true)};});describe('Router subscriptions',function(){var protectedRoute='/protected';var protectorRoute='/login';var mockedRouterState={router:{currentRoute:{pathname:protectorRoute}}};var subscribe=jest.fn();var dispatch=jest.fn();var getState=jest.fn().mockReturnValue(mockedRouterState);var events={emit:jest.fn()};/**
|
|
2
|
-
* @param {Object} action The action object for the callback payload.
|
|
3
|
-
* @return {Object}
|
|
4
|
-
*/var createCallbackPayload=function createCallbackPayload(action){return{dispatch:dispatch,getState:getState,action:action,events:events};};beforeAll(function(){jest.spyOn(logger,'warn').mockImplementation();jest.spyOn(logger,'error').mockImplementation();jest.spyOn(LoadingProvider,'setLoading');jest.spyOn(LoadingProvider,'unsetLoading');// Setup a protected route
|
|
5
|
-
authRoutes.set(protectedRoute,protectorRoute);});beforeEach(function(){jest.clearAllMocks();mockedShopCNAME=null;mockedWebCheckoutConfig=null;subscriptions(subscribe);});it('should subscribe as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:expect(subscribe).toHaveBeenCalledTimes(4);case 1:case"end":return _context.stop();}}},_callee);})));describe('navigate$',function(){var openExternalLinkSpy=jest.spyOn(handler,'openExternalLink');var openNativeLinkSpy=jest.spyOn(handler,'openNativeLink');var openLegacySpy=jest.spyOn(handler,'openLegacy');var openLegacyLinkSpy=jest.spyOn(handler,'openLegacyLink');var stream;var callback;/**
|
|
6
|
-
* Tests if a passed function was called during a test as expected.
|
|
7
|
-
* @param {Function} calledFn The function that was supposed to be called within a test.
|
|
8
|
-
* @param {Object} params Optional params for the function call.
|
|
9
|
-
*/var testExpectedCall=function testExpectedCall(calledFn,params){// All possible functions that might be called within the subscription.
|
|
10
|
-
var haystack=[dispatch,openNativeLinkSpy,openExternalLinkSpy,openLegacySpy,openLegacyLinkSpy,router.pop,router.push,router.reset,router.replace,events.emit];// Split the expected function from the haystack.
|
|
11
|
-
var needle;var needleIndex=haystack.findIndex(function(entry){return entry===calledFn;});if(needleIndex!==-1){var _haystack$splice=haystack.splice(needleIndex,1);var _haystack$splice2=_slicedToArray(_haystack$splice,1);needle=_haystack$splice2[0];}if(needle){expect(needle).toHaveBeenCalledTimes(1);}if(params){expect(calledFn).toHaveBeenCalledWith(params.pathname,params.state,params.silent);}haystack.forEach(function(entry){// Check that none of the others is called.
|
|
12
|
-
expect(entry).not.toBeCalled();});};beforeEach(function(){var _subscribe$mock$calls=_slicedToArray(subscribe.mock.calls,1);var _subscribe$mock$calls2=_slicedToArray(_subscribe$mock$calls[0],2);stream=_subscribe$mock$calls2[0];callback=_subscribe$mock$calls2[1];redirects.constructor();});it('should setup as expected',function(){expect(stream).toEqual(navigate$);expect(callback).toBeInstanceOf(Function);});it('should not do anything when no suitable action is passed',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return callback(createCallbackPayload({params:{action:'W00P'}}));case 2:testExpectedCall();case 3:case"end":return _context2.stop();}}},_callee2);})));it('should handle the ACTION_POP history action as expected',/*#__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 callback(createCallbackPayload({params:{action:ACTION_POP}}));case 2:expect(router.pop).toHaveBeenCalled();case 3:case"end":return _context3.stop();}}},_callee3);})));it('should handle the ACTION_RESET history action as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return callback(createCallbackPayload({params:{action:ACTION_RESET}}));case 2:testExpectedCall(router.reset);case 3:case"end":return _context4.stop();}}},_callee4);})));it('should handle the ACTION_PUSH history action as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var params;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:getState.mockReturnValueOnce(_extends({},mockedRouterState,{user:{login:{isLoggedIn:true}}}));params={action:ACTION_PUSH,pathname:'/some_route',state:{},silent:true};_context5.next=4;return callback(createCallbackPayload({params:params}));case 4:expect(router.push).toHaveBeenCalledWith({emitBefore:true,emitAfter:true,pathname:params.pathname,state:params.state});case 5:case"end":return _context5.stop();}}},_callee5);})));it('should handle the ACTION_REPLACE history action as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var params;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:params={action:ACTION_REPLACE,pathname:'/some_route',silent:false};_context6.next=3;return callback(createCallbackPayload({params:params}));case 3:expect(router.replace).toHaveBeenCalledWith({emitBefore:false,emitAfter:false,pathname:'/some_route',state:undefined});case 4:case"end":return _context6.stop();}}},_callee6);})));it('should remove trailing slashes from pathnames',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var params;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:params={action:ACTION_PUSH,pathname:'/some_route/',state:{},silent:true};_context7.next=3;return callback(createCallbackPayload({params:params}));case 3:expect(router.push).toHaveBeenCalledWith({emitBefore:true,emitAfter:true,pathname:params.pathname.slice(0,-1),state:params.state});case 4:case"end":return _context7.stop();}}},_callee7);})));it('should redirect to a protector route when the user is not logged in',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){var params;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:getState.mockReturnValueOnce(_extends({},mockedRouterState,{user:{login:{isLoggedIn:false}}}));params={action:ACTION_PUSH,pathname:protectedRoute,silent:false};_context8.next=4;return callback(createCallbackPayload({params:params}));case 4:testExpectedCall(dispatch);expect(dispatch).toHaveBeenCalledWith(navigate({action:params.action,pathname:protectorRoute,state:{redirect:{location:params.pathname,state:params.state}}}));case 6:case"end":return _context8.stop();}}},_callee8);})));it('should not redirect to a protector route when the user is logged in',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var params;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:getState.mockReturnValueOnce(_extends({},mockedRouterState,{user:{login:{isLoggedIn:true}}}));params={action:ACTION_PUSH,pathname:protectedRoute,state:{},silent:true};_context9.next=4;return callback(createCallbackPayload({params:params}));case 4:expect(router.push).toHaveBeenCalledWith({emitBefore:true,emitAfter:true,pathname:params.pathname,state:params.state});case 5:case"end":return _context9.stop();}}},_callee9);})));it('should redirect to another location correctly',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var params;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:redirects.set('/some_route','/some_other_route');params={action:ACTION_PUSH,pathname:'/some_route'};_context10.next=4;return callback(createCallbackPayload({params:params}));case 4:expect(router.push).toHaveBeenCalledWith({pathname:'/some_other_route',state:params.state});case 5:case"end":return _context10.stop();}}},_callee10);})));it('should redirect to another location when the redirect handler is a promise',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){var redirectHandler,params;return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:/**
|
|
13
|
-
* @return {Promise}
|
|
14
|
-
*/redirectHandler=function redirectHandler(){return Promise.resolve('/some_other_route');};redirects.set('/some_route',redirectHandler);params={action:ACTION_PUSH,pathname:'/some_route'};_context11.next=5;return callback(createCallbackPayload({params:params}));case 5:expect(router.push).toHaveBeenCalledTimes(1);expect(router.push).toHaveBeenCalledWith({pathname:'/some_other_route',state:params.state});expect(LoadingProvider.setLoading).toHaveBeenCalledWith(protectorRoute);expect(LoadingProvider.unsetLoading).toHaveBeenCalledWith(protectorRoute);case 9:case"end":return _context11.stop();}}},_callee11);})));it('should redirect from an external URL to an internal one',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(){var productCode,matcher,pathname,redirectTarget,redirectHandler,params;return _regeneratorRuntime.wrap(function _callee12$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:productCode='abc123';matcher='http://www.external.com/:seoName/:productCode';pathname="http://www.external.com/nice-product-name/".concat(productCode,"?query=param");redirectTarget="/item/".concat(productCode);redirectHandler=jest.fn(function(params){expect(params).toEqual({dispatch:expect.any(Function),getState:expect.any(Function),events:expect.any(Object),action:{params:{action:ACTION_PUSH,pathname:pathname},route:expect.any(Object),redirectMeta:{location:pathname,matcher:matcher,pathParams:{seoName:'nice-product-name',productCode:productCode},queryParams:{query:'param'}}}});return new Promise(function(resolve){resolve(redirectTarget);});});redirects.set(matcher,redirectHandler);params={action:ACTION_PUSH,pathname:pathname};_context12.next=9;return callback(createCallbackPayload({params:params}));case 9:expect(router.push).toHaveBeenCalledTimes(1);expect(router.push).toHaveBeenCalledWith({pathname:redirectTarget,state:params.state});case 11:case"end":return _context12.stop();}}},_callee12);})));it('should abort navigation when a redirect handler rejects',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(){var error,redirectHandler,params;return _regeneratorRuntime.wrap(function _callee13$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:error=new Error('W00ps');/**
|
|
15
|
-
* @return {Promise}
|
|
16
|
-
*/redirectHandler=function redirectHandler(){return Promise.reject(error);};redirects.set('/some_route',redirectHandler);params={action:ACTION_PUSH,pathname:'/some_route'};_context13.next=6;return expect(callback(createCallbackPayload({params:params}))).resolves.toBe();case 6:expect(router.push).not.toHaveBeenCalled();expect(logger.error).toHaveBeenCalledWith(error);expect(LoadingProvider.setLoading).toHaveBeenCalledWith(protectorRoute);expect(LoadingProvider.unsetLoading).toHaveBeenCalledWith(protectorRoute);case 10:case"end":return _context13.stop();}}},_callee13);})));it('should abort navigation when the url is invalid',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(){var params;return _regeneratorRuntime.wrap(function _callee14$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:params={action:ACTION_PUSH,pathname:'?foo=bar'};_context14.next=3;return expect(callback(createCallbackPayload({params:params}))).resolves.toBe();case 3:testExpectedCall(events.emit);expect(events.emit).toHaveBeenCalledWith(ToastProvider.ADD,{id:'navigate.error',message:'error.general'});case 5:case"end":return _context14.stop();}}},_callee14);})));it('should abort navigation when the redirect url is invalid',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee15(){var redirectHandler,params;return _regeneratorRuntime.wrap(function _callee15$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:/**
|
|
17
|
-
* @return {Promise}
|
|
18
|
-
*/redirectHandler=function redirectHandler(){return Promise.resolve('?foo=bar');};redirects.set('/some_route',redirectHandler);params={action:ACTION_PUSH,pathname:'/some_route'};_context15.next=5;return expect(callback(createCallbackPayload({params:params}))).resolves.toBe();case 5:testExpectedCall(events.emit);expect(events.emit).toHaveBeenCalledWith(ToastProvider.ADD,{id:'navigate.error',message:'error.general'});case 7:case"end":return _context15.stop();}}},_callee15);})));it('should convert shop links as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee16(){var params;return _regeneratorRuntime.wrap(function _callee16$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:mockedShopCNAME='m.awesomeshop.com';params={action:ACTION_PUSH,pathname:"https://".concat(mockedShopCNAME,"/some_route")};_context16.next=4;return callback(createCallbackPayload({params:params}));case 4:expect(router.push).toHaveBeenCalledWith({pathname:'/some_route',state:params.state});case 5:case"end":return _context16.stop();}}},_callee16);})));it('should handle external links like expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee17(){var params;return _regeneratorRuntime.wrap(function _callee17$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:params={action:ACTION_PUSH,pathname:'https://www.awesome-shop.com/some_route'};_context17.next=3;return callback(createCallbackPayload({params:params}));case 3:testExpectedCall(openExternalLinkSpy);expect(openExternalLinkSpy).toHaveBeenCalledWith(params.pathname,params.action,mockedRouterState,undefined);case 5:case"end":return _context17.stop();}}},_callee17);})));it('should handle external urls with target=_blank as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee18(){var params;return _regeneratorRuntime.wrap(function _callee18$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:params={action:ACTION_PUSH,pathname:'https://m.me/facebookID',state:{target:'_blank'}};_context18.next=3;return callback(createCallbackPayload({params:params}));case 3:expect(openExternalLinkSpy).toBeCalledTimes(1);expect(openExternalLinkSpy).toHaveBeenCalledWith(params.pathname,params.action,mockedRouterState,params.state);case 5:case"end":return _context18.stop();}}},_callee18);})));it('should handle native links like expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee19(){var params;return _regeneratorRuntime.wrap(function _callee19$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:/**
|
|
19
|
-
* Replace the implementation of handler.openNative link temporarily. It reassigns
|
|
20
|
-
* window.location.href internally, which would cause a jest error.
|
|
21
|
-
*/openNativeLinkSpy.mockImplementationOnce(function(){});params={action:ACTION_PUSH,pathname:'tel:+49123456789'};_context19.next=4;return callback(createCallbackPayload({params:params}));case 4:testExpectedCall(openNativeLinkSpy);expect(openNativeLinkSpy).toHaveBeenCalledWith(params.pathname);case 6:case"end":return _context19.stop();}}},_callee19);})));it('should open a legacy page as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee20(){var params;return _regeneratorRuntime.wrap(function _callee20$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:params={action:ACTION_PUSH,pathname:'/page/imprint'};_context20.next=3;return callback(createCallbackPayload({params:params}));case 3:testExpectedCall(openLegacySpy);expect(openLegacySpy).toHaveBeenCalledWith(params.pathname,params.action,mockedRouterState);case 5:case"end":return _context20.stop();}}},_callee20);})));it('should open a legacy link as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee21(){var params;return _regeneratorRuntime.wrap(function _callee21$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:params={action:ACTION_PUSH,pathname:handler.LEGACY_LINK_ACCOUNT};_context21.next=3;return callback(createCallbackPayload({params:params}));case 3:testExpectedCall(openLegacyLinkSpy);expect(openLegacyLinkSpy).toHaveBeenCalledWith(params.pathname,params.action,mockedRouterState);case 5:case"end":return _context21.stop();}}},_callee21);})));it('should cancel navigation when not connected to the internet',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee22(){var params;return _regeneratorRuntime.wrap(function _callee22$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:getIsConnected.mockReturnValueOnce(false);params={action:ACTION_PUSH,pathname:'/some_route'};_context22.next=4;return callback(createCallbackPayload({params:params}));case 4:testExpectedCall(events.emit);expect(events.emit).toHaveBeenCalledWith(ToastProvider.ADD,{id:'navigate.error',message:'error.general'});case 6:case"end":return _context22.stop();}}},_callee22);})));});describe('redirectUser$',function(){var callback;beforeEach(function(){var _subscribe$mock$calls3=_slicedToArray(subscribe.mock.calls,2);var _subscribe$mock$calls4=_slicedToArray(_subscribe$mock$calls3[1],2);callback=_subscribe$mock$calls4[1];});it('should redirect when no web checkout config is set',function(){var redirect={pathname:protectedRoute,state:{}};callback(createCallbackPayload({redirect:redirect}));expect(dispatch).toHaveBeenCalledTimes(1);expect(historyRedirect).toHaveBeenCalledWith(redirect);});it('should not redirect when a web checkout config is set',function(){mockedWebCheckoutConfig={config:'key'};var redirect={pathname:protectedRoute,state:{}};callback(createCallbackPayload({redirect:redirect}));expect(dispatch).not.toHaveBeenCalled();});});describe('appWillStart$',function(){var callback;var stream;beforeEach(function(){var _subscribe$mock$calls5=_slicedToArray(subscribe.mock.calls,3);var _subscribe$mock$calls6=_slicedToArray(_subscribe$mock$calls5[2],2);stream=_subscribe$mock$calls6[0];callback=_subscribe$mock$calls6[1];});it('should setup as expected',function(){expect(stream).toEqual(appWillStart$);expect(callback).toBeInstanceOf(Function);});describe('window.open()',function(){beforeAll(function(){callback(createCallbackPayload({}));});it('should return null when called and dispatched the windowOpenOverride action',function(){var pathname='http://some.shop.com/abc123?query=param';expect(window.open(pathname)).toBeNull();expect(dispatch).toBeCalledTimes(1);expect(dispatch).toBeCalledWith(windowOpenOverride({pathname:pathname}));});});});describe('windowOpenOverride$',function(){var callback;var stream;beforeEach(function(){var _subscribe$mock$calls7=_slicedToArray(subscribe.mock.calls,4);var _subscribe$mock$calls8=_slicedToArray(_subscribe$mock$calls7[3],2);stream=_subscribe$mock$calls8[0];callback=_subscribe$mock$calls8[1];});it('should setup as expected',function(){expect(stream).toEqual(windowOpenOverride$);expect(callback).toBeInstanceOf(Function);});it('should dispatch historyPush when invoked with an url',function(){var pathname='http://some.url';callback(createCallbackPayload(windowOpenOverride({pathname:pathname})));expect(dispatch).toHaveBeenCalledTimes(1);expect(dispatch).toHaveBeenCalledWith(historyPush({pathname:pathname}));});it('should NOT dispatch historyPush when invoked with an empty url',function(){callback(createCallbackPayload(windowOpenOverride({pathname:null})));expect(dispatch).not.toBeCalled();});});});
|