@shopgate/pwa-core 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 +45 -0
- package/package.json +1 -1
- package/__mocks__/@shopgate/pwa-core/index.js +0 -1
- package/classes/AppCommand/__mocks__/index.js +0 -4
- package/classes/AppCommand/__mocks__/index.spec.js +0 -5
- package/classes/AppPermissionsRequest/AppPermissionsRequest.spec.js +0 -12
- package/classes/AppPermissionsRequest/GetAppPermissionsRequest.spec.js +0 -1
- package/classes/AppPermissionsRequest/RequestAppPermissionsRequest.spec.js +0 -1
- package/classes/AppPermissionsRequest/__mocks__/GetAppPermissionsRequest.js +0 -6
- package/classes/AppPermissionsRequest/__mocks__/RequestAppPermissionsRequest.js +0 -6
- package/classes/Event/__mocks__/index.js +0 -5
- package/classes/PipelineRequest/mock.spec.js +0 -4
- package/classes/Scanner/index.spec.js +0 -22
- package/classes/ScannerEvent/index.spec.js +0 -1
- package/classes/ScannerEventHandler/index.spec.js +0 -6
- package/classes/ScannerEventListener/index.spec.js +0 -3
- package/classes/ScannerManager/ScanProcessingError.spec.js +0 -1
- package/classes/ScannerManager/index.spec.js +0 -17
- package/commands/__tests__/appPermissions.spec.js +0 -1
- package/commands/__tests__/brightness.spec.js +0 -1
- package/commands/__tests__/closeInAppBrowser.spec.js +0 -7
- package/commands/__tests__/openAppSettings.spec.js +0 -2
- package/commands/__tests__/plotProjects.spec.js +0 -3
- package/commands/__tests__/scanner.spec.js +0 -2
- package/helpers/version.spec.js +0 -6
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
|
|
2
|
+
# Changelog
|
|
3
|
+
---
|
|
4
|
+
|
|
5
|
+
### [1.3.0](https://github.com/shopgate/pwa-core/compare/v1.2....v1.3.0) - February 05, 2018
|
|
6
|
+
#### Added
|
|
7
|
+
- Introduced a new constant for invalid pipeline call errors
|
|
8
|
+
|
|
9
|
+
#### Removed
|
|
10
|
+
- Removed the `errorMessageWhitelist` property from the PipelineRequest object, since it wasn't used anymore
|
|
11
|
+
|
|
12
|
+
---
|
|
13
|
+
|
|
14
|
+
### [1.2.0](https://github.com/shopgate/pwa-core/compare/v1.1.1...v1.2.0) - January 25, 2018
|
|
15
|
+
#### Added
|
|
16
|
+
- `EFAVORITE` and `EBIGAPI` error codes
|
|
17
|
+
|
|
18
|
+
---
|
|
19
|
+
|
|
20
|
+
### [1.1.1](https://github.com/shopgate/pwa-core/compare/v1.1.0...v1.1.1) - January 24, 2018
|
|
21
|
+
#### Fixed
|
|
22
|
+
- Enabled console logging for "httpResponse" event errors.
|
|
23
|
+
|
|
24
|
+
---
|
|
25
|
+
|
|
26
|
+
### [1.1.0](https://github.com/shopgate/pwa-core/compare/v1.0.5...v1.1.0) - December 22, 2017
|
|
27
|
+
|
|
28
|
+
#### Changed
|
|
29
|
+
- Updated `@shopgate/eslint-config` to ^1.0.3
|
|
30
|
+
- Updated `jest` to ^22.0.4
|
|
31
|
+
|
|
32
|
+
---
|
|
33
|
+
|
|
34
|
+
### [1.0.5](https://github.com/shopgate/pwa-core/compare/v1.0.0...v1.0.5) - December 21, 2017
|
|
35
|
+
|
|
36
|
+
#### Added
|
|
37
|
+
- cleanTab command
|
|
38
|
+
- closeInAppBrowser command
|
|
39
|
+
- performCommandsAfterDelay command
|
|
40
|
+
- setCommandParams method to AppCommand
|
|
41
|
+
|
|
42
|
+
#### Removed
|
|
43
|
+
- index containing exports of all commands
|
|
44
|
+
- openCart command
|
|
45
|
+
- openSearch command
|
package/package.json
CHANGED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
export var UIEvents={emit:jest.fn(),on:jest.fn(),addListener:jest.fn(),removeListener:jest.fn()};
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}var dispatchError=false;export var mockedSetCommandName=jest.fn(function(name){return name;});export var mockedSetCommandParams=jest.fn(function(params){return params;});export var mockedSetLibVersion=jest.fn(function(version){return version;});export var mockedBuildCommand=jest.fn(function(command){return command;});export var mockedDispatch=jest.fn(function(params){return params;});/**
|
|
2
|
-
* Causes that the dispatch method resolves with FALSE.
|
|
3
|
-
* @param {boolean} value Trigger an error or not.
|
|
4
|
-
*/export var triggerDispatchError=function triggerDispatchError(){var value=arguments.length>0&&arguments[0]!==undefined?arguments[0]:true;dispatchError=value;};var mockedAppCommand=jest.fn().mockImplementation(function MockedAppCommand(){var _this=this;this.name='';this.params=null;this.libVersion='9.0';this.setCommandName=function(name){_this.name=mockedSetCommandName(name);return _this;};this.setCommandParams=function(params){_this.params=mockedSetCommandParams(params);return _this;};this.setLibVersion=function(version){_this.libVersion=mockedSetLibVersion(version);return _this;};this.buildCommand=function(){var command=_this.name?_extends({c:_this.name},_this.params&&{p:_this.params}):null;return mockedBuildCommand(command);};this.dispatch=function(params){mockedDispatch(params);var success=!dispatchError;dispatchError=false;return Promise.resolve(success);};return this;});export default mockedAppCommand;
|
|
@@ -1,5 +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);}// Mock some underlying classes to avoid faulty code exection.
|
|
2
|
-
jest.mock("../../DevServerBridge",function(){});jest.mock("../../../commands/getWebStorageEntry",function(){});// List of known "private" methods within the original class.
|
|
3
|
-
var privateMethods=['constructor','logCommand'];describe('AppCommand mock',function(){describe('check if the mock provides all "public" methods',function(){var OriginalAppCommand=require.requireActual("../index")["default"];var MockedAppCommand=require.requireMock("../index")["default"];// Collect the "public" methods from the original class.
|
|
4
|
-
var publicMethods=Object.getOwnPropertyNames(OriginalAppCommand.prototype).filter(function(method){return!privateMethods.includes(method);});// To access the methods of the mock, an instance is necessary.
|
|
5
|
-
var mockedInstance=new MockedAppCommand();publicMethods.forEach(function(method){it("should contain a method called ".concat(method),function(){expect(_typeof(mockedInstance[method])).toBe('function');});});});});
|
|
@@ -1,12 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}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{hasSGJavaScriptBridge}from"../../helpers";import{PERMISSION_ID_CAMERA,PERMISSION_ID_LOCATION,STATUS_GRANTED}from"../../constants/AppPermissions";import Request from"../Request";import AppPermissionsRequest from"./AppPermissionsRequest";/* eslint-disable import/named */import{triggerDispatchError,mockedSetCommandName,mockedSetCommandParams,mockedSetLibVersion,mockedDispatch}from"../AppCommand";/* eslint-enable import/named */jest.mock("../AppCommand");var lastAddedEventCallback=null;var mockedEventAddCallback=jest.fn();var mockedEventRemoveCallback=jest.fn();jest.mock("../Event",function(){return{addCallback:function addCallback(name,callback){for(var _len=arguments.length,args=new Array(_len>2?_len-2:0),_key=2;_key<_len;_key++){args[_key-2]=arguments[_key];}mockedEventAddCallback.apply(void 0,[name,callback].concat(args));lastAddedEventCallback=callback;},removeCallback:function removeCallback(){mockedEventRemoveCallback.apply(void 0,arguments);}};});var mockedRequestBufferAdd=jest.fn();var mockedRequestBufferRemove=jest.fn();jest.mock("../RequestBuffer",function(){return{add:function add(){mockedRequestBufferAdd.apply(void 0,arguments);},remove:function remove(){mockedRequestBufferRemove.apply(void 0,arguments);}};});var mockedLoggerError=jest.fn();jest.mock("../../helpers",function(){return{logger:{error:function error(){mockedLoggerError.apply(void 0,arguments);}},hasSGJavaScriptBridge:jest.fn().mockReturnValue(true)};});var mockedLogGroup=jest.fn();// eslint-disable-next-line extra-rules/potential-point-free
|
|
2
|
-
jest.mock("../../helpers/logGroup",function(){return function logGroup(){mockedLogGroup.apply(void 0,arguments);};});var parentDispatchSpy=jest.spyOn(Request.prototype,'dispatch');var commandName='appCommand';var eventName='appEvent';describe('AppPermissionsRequest',function(){var instance;var cleanUpRequestSpy;var onDispatchSpy;beforeEach(function(){jest.clearAllMocks();lastAddedEventCallback=null;instance=new AppPermissionsRequest(commandName,eventName);cleanUpRequestSpy=jest.spyOn(instance,'cleanUpRequest');onDispatchSpy=jest.spyOn(instance,'onDispatch');});describe('.constructor()',function(){it('should apply parameters as expected',function(){expect(instance.commandName).toBe(commandName);expect(instance.eventName).toBe(eventName);expect(instance.commandParams).toBe(null);expect(instance.libVersion).toBe('18.0');expect(_typeof(instance.serial)).toBe('string');expect(instance.serial.length).toBeGreaterThan(1);expect(_typeof(instance.callbackName)).toBe('string');expect(instance.callbackName.length).toBeGreaterThan(1);});});describe('.setCommandParams()',function(){it('should set command params as expected',function(){var params={permissionIds:[]};var result=instance.setCommandParams(params);expect(result).toEqual(instance);expect(result.commandParams).toEqual(params);});});describe('.cleanUpRequest()',function(){it('should work like expected',function(){var callbackName=instance.getEventCallbackName();var callback=jest.fn();var _instance=instance,serial=_instance.serial;var result=instance.cleanUpRequest(callback);expect(result).toEqual(instance);expect(mockedEventRemoveCallback).toHaveBeenCalledTimes(1);expect(mockedEventRemoveCallback).toHaveBeenCalledWith(callbackName,callback);expect(mockedRequestBufferRemove).toHaveBeenCalledTimes(1);expect(mockedRequestBufferRemove).toHaveBeenCalledWith(serial);});});describe('.validateCommandParams()',function(){it('should throw an error when not overwritten',function(){expect(instance.validateCommandParams).toThrowError(Error);});});describe('.onDispatch()',function(){var commandParams={permissionIds:[]};var permissionsResponse=[{}];// Promise callbacks.
|
|
3
|
-
var resolveCallback=jest.fn();var rejectCallback=jest.fn();beforeEach(function(){// Overwrite the validate function to always return TRUE.
|
|
4
|
-
instance.validateCommandParams=function(){return true;};instance.setCommandParams(commandParams);});it('should resolve with permissions when the instance is set up properly',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return instance.onDispatch(resolveCallback,rejectCallback);case 2:result=_context.sent;// Simulate callback invocation through the event listener.
|
|
5
|
-
lastAddedEventCallback(instance.serial,permissionsResponse);// Checks for the promise resolve call.
|
|
6
|
-
expect(resolveCallback).toHaveBeenCalledTimes(1);expect(resolveCallback).toHaveBeenCalledWith(permissionsResponse);expect(rejectCallback).toHaveBeenCalledTimes(0);expect(cleanUpRequestSpy).toHaveBeenCalledTimes(1);expect(cleanUpRequestSpy).toHaveBeenCalledWith(lastAddedEventCallback);// Checks for the onDispatch sequence.
|
|
7
|
-
expect(result).toBeUndefined();expect(mockedRequestBufferAdd).toHaveBeenCalledTimes(1);expect(mockedRequestBufferAdd).toHaveBeenCalledWith(instance,instance.serial);expect(mockedEventAddCallback).toHaveBeenCalledTimes(1);// The callback (2nd paramter) is created within the method and access is not possible.
|
|
8
|
-
expect(mockedEventAddCallback).toHaveBeenCalledWith(instance.getEventCallbackName(),expect.any(Function));expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith(commandName);expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenCalledWith(instance.libVersion);expect(mockedSetCommandParams).toHaveBeenCalledTimes(1);expect(mockedSetCommandParams).toHaveBeenCalledWith(_extends({serial:instance.serial},commandParams));expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedLogGroup).toHaveBeenCalledTimes(2);case 22:case"end":return _context.stop();}}},_callee);})));it('should reject when the command params are invalid',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var result;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:// Simulate invalid parameters.
|
|
9
|
-
instance.validateCommandParams=function(){return false;};_context2.next=3;return instance.onDispatch(resolveCallback,rejectCallback);case 3:result=_context2.sent;expect(result).toBeUndefined();expect(rejectCallback).toHaveBeenCalledTimes(1);expect(rejectCallback).toHaveBeenCalledWith(expect.any(Error));expect(resolveCallback).toHaveBeenCalledTimes(0);expect(mockedLoggerError).toHaveBeenCalledTimes(1);expect(mockedLoggerError).toHaveBeenCalledWith(expect.any(String),commandParams);expect(mockedLogGroup).toHaveBeenCalledTimes(0);case 11:case"end":return _context2.stop();}}},_callee2);})));it('should reject when the command was not dispatched',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var result;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:// Resolve with error on command dispatch.
|
|
10
|
-
triggerDispatchError();_context3.next=3;return instance.onDispatch(resolveCallback,rejectCallback);case 3:result=_context3.sent;expect(result).toBeUndefined();expect(rejectCallback).toHaveBeenCalledTimes(1);expect(rejectCallback).toHaveBeenCalledWith(expect.any(Error));expect(resolveCallback).toHaveBeenCalledTimes(0);expect(cleanUpRequestSpy).toHaveBeenCalledTimes(1);expect(cleanUpRequestSpy).toHaveBeenCalledWith(lastAddedEventCallback);expect(mockedLogGroup).toHaveBeenCalledTimes(0);case 11:case"end":return _context3.stop();}}},_callee3);})));it('should be called and resolve during inherited .dispatch()',function(done){instance.dispatch().then(function(result){expect(result).toEqual(permissionsResponse);expect(onDispatchSpy).toHaveBeenCalledTimes(1);expect(onDispatchSpy).toHaveBeenCalledWith(expect.any(Function),expect.any(Function));expect(mockedLogGroup).toHaveBeenCalledTimes(2);done();});// Simulate callback invocation through the event listener.
|
|
11
|
-
lastAddedEventCallback(instance.serial,permissionsResponse);});it('should be called and reject during inherited .dispatch()',function(done){// Resolve with error on command dispatch.
|
|
12
|
-
triggerDispatchError();instance.dispatch()["catch"](function(e){expect(e).toBeInstanceOf(Error);expect(onDispatchSpy).toHaveBeenCalledTimes(1);expect(onDispatchSpy).toHaveBeenCalledWith(expect.any(Function),expect.any(Function));expect(cleanUpRequestSpy).toHaveBeenCalledTimes(1);expect(cleanUpRequestSpy).toHaveBeenCalledWith(lastAddedEventCallback);expect(mockedLogGroup).toHaveBeenCalledTimes(0);done();});});});describe('.dispatch()',function(){/* eslint-disable extra-rules/no-single-line-objects */var expected=[{permissionId:PERMISSION_ID_CAMERA,status:STATUS_GRANTED},{permissionId:PERMISSION_ID_LOCATION,status:STATUS_GRANTED}];/* eslint-enable extra-rules/no-single-line-objects */it('should call the parent dispatch when a SGJavaScriptBridge is present',function(){instance.validateCommandParams=function(){return true;};instance.dispatch();expect(parentDispatchSpy).toHaveBeenCalledTimes(1);});it('should mock the response for a getAppPermissions request when no SGJavaScriptBridge is present',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var params,response;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:hasSGJavaScriptBridge.mockReturnValueOnce(false);params={permissionIds:[PERMISSION_ID_CAMERA,PERMISSION_ID_LOCATION]};instance.setCommandParams(params);_context4.next=5;return instance.dispatch();case 5:response=_context4.sent;expect(response).toEqual(expected);expect(parentDispatchSpy).not.toHaveBeenCalled();case 8:case"end":return _context4.stop();}}},_callee4);})));it('should mock the response for a requestAppPermissions request when no SGJavaScriptBridge is present',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var params,response;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:hasSGJavaScriptBridge.mockReturnValueOnce(false);params={permissions:[{permissionId:PERMISSION_ID_CAMERA},{permissionId:PERMISSION_ID_LOCATION}]};instance.setCommandParams(params);_context5.next=5;return instance.dispatch();case 5:response=_context5.sent;expect(response).toEqual(expected);expect(parentDispatchSpy).not.toHaveBeenCalled();case 8:case"end":return _context5.stop();}}},_callee5);})));});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import GetAppPermissionsRequest from"./GetAppPermissionsRequest";import{PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA}from"../../constants/AppPermissions";var GET_PERMISSIONS_COMMAND_NAME='getAppPermissions';var GET_PERMISSIONS_RESPONSE_EVENT_NAME='getAppPermissionsResponse';jest.mock("../Event",function(){return{};});var permissionIds=[PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA];describe('AppPermissionsRequest',function(){var instance;var setCommandParamsSpy;beforeEach(function(){instance=new GetAppPermissionsRequest();setCommandParamsSpy=jest.spyOn(instance,'setCommandParams');});describe('.constructor()',function(){it('should work as expected',function(){expect(instance.commandName).toEqual(GET_PERMISSIONS_COMMAND_NAME);expect(instance.eventName).toEqual(GET_PERMISSIONS_RESPONSE_EVENT_NAME);});});describe('.setPermissionIds()',function(){it('should set command params as expected when permissions are passed',function(){var expected={permissionIds:permissionIds};var result=instance.setPermissionIds(permissionIds);expect(result).toEqual(instance);expect(instance.commandParams).toEqual(expected);expect(setCommandParamsSpy).toHaveBeenCalledTimes(1);expect(setCommandParamsSpy).toHaveBeenCalledWith(expected);});it('should set command params as expected when nothing is passed',function(){var expected={permissionIds:[]};var result=instance.setPermissionIds();expect(result).toEqual(instance);expect(instance.commandParams).toEqual(expected);expect(setCommandParamsSpy).toHaveBeenCalledTimes(1);});});describe('.validateCommandParams()',function(){it('should return true for valid params',function(){instance.setPermissionIds(permissionIds);var result=instance.validateCommandParams();expect(result).toBe(true);});it('should return true for empty params',function(){instance.setPermissionIds();var result=instance.validateCommandParams();expect(result).toBe(true);});it('should return true when .setPermissionIds() was not called',function(){var result=instance.validateCommandParams();expect(result).toBe(true);});it('should return false when the permission ids contain invalid values',function(){instance.setPermissionIds(['unknown',PERMISSION_ID_LOCATION]);var result=instance.validateCommandParams();expect(result).toBe(false);});it('should return false when the permission ids parameter is not an array',function(){instance.setPermissionIds({});var result=instance.validateCommandParams();expect(result).toBe(false);});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import RequestAppPermissionsRequest from"./RequestAppPermissionsRequest";import{PERMISSION_ID_LOCATION,USAGE_WHEN_IN_USE}from"../../constants/AppPermissions";var REQUEST_PERMISSIONS_COMMAND_NAME='requestAppPermissions';var REQUEST_PERMISSIONS_RESPONSE_EVENT_NAME='requestAppPermissionsResponse';jest.mock("../Event",function(){return{};});var permissions=[{permissionId:PERMISSION_ID_LOCATION,options:{usage:USAGE_WHEN_IN_USE}}];describe('AppPermissionsRequest',function(){var instance;var setCommandParamsSpy;beforeEach(function(){instance=new RequestAppPermissionsRequest();setCommandParamsSpy=jest.spyOn(instance,'setCommandParams');});describe('.constructor()',function(){it('should work as expected',function(){expect(instance.commandName).toEqual(REQUEST_PERMISSIONS_COMMAND_NAME);expect(instance.eventName).toEqual(REQUEST_PERMISSIONS_RESPONSE_EVENT_NAME);});});describe('.setPermissions()',function(){it('should set command params as expected',function(){var expected={permissions:permissions};var result=instance.setPermissions(permissions);expect(result).toEqual(instance);expect(instance.commandParams).toEqual(expected);expect(setCommandParamsSpy).toHaveBeenCalledTimes(1);expect(setCommandParamsSpy).toHaveBeenCalledWith(expected);});});describe('.validateCommandParams()',function(){it('should return true for valid params',function(){instance.setPermissions(permissions);var result=instance.validateCommandParams();expect(result).toBe(true);});it('should return false when .setPermissions() was not called',function(){var result=instance.validateCommandParams();expect(result).toBe(false);});it('should return false when the permission array is empty',function(){instance.setPermissions([]);var result=instance.validateCommandParams();expect(result).toBe(false);});it('should return false when the permission array contains invalid permission entry',function(){instance.setPermissions([null]);var result=instance.validateCommandParams();expect(result).toBe(false);});it('should return false when the permission array contains invalid permissions',function(){instance.setPermissions([{wrongParam:1337}]);var result=instance.validateCommandParams();expect(result).toBe(false);});});});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA,USAGE_ALWAYS}from"../../../constants/AppPermissions";export var mockedSetPermissionIds=jest.fn();export var mockedDispatch=jest.fn();export var mockedPermissionsResponse=[{permissionId:PERMISSION_ID_LOCATION,options:{usage:USAGE_ALWAYS}},{permissionId:PERMISSION_ID_CAMERA}];var dispatchError=false;var errorMessage='';/**
|
|
2
|
-
* Causes that the dispatch method resolves with FALSE.
|
|
3
|
-
* @param {string} message The error message.
|
|
4
|
-
* @param {boolean} value Trigger an error or not.
|
|
5
|
-
*/export var triggerDispatchError=function triggerDispatchError(){var message=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'W00t';var value=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;dispatchError=value;errorMessage=message;};var mockedGetAppPermissionsRequest=jest.fn().mockImplementation(function GetAppPermissionsRequest(){var _this=this;this.setPermissionIds=function(){mockedSetPermissionIds.apply(void 0,arguments);return _this;};this.dispatch=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var message,_args=arguments;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:mockedDispatch.apply(void 0,_args);if(!dispatchError){_context.next=5;break;}// Get the message before it's reset
|
|
6
|
-
message=errorMessage;triggerDispatchError('',false);throw new Error(message);case 5:return _context.abrupt("return",mockedPermissionsResponse);case 6:case"end":return _context.stop();}}},_callee);}));return this;});export default mockedGetAppPermissionsRequest;
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA,USAGE_ALWAYS}from"../../../constants/AppPermissions";export var mockedSetPermissions=jest.fn();export var mockedDispatch=jest.fn();export var mockedPermissionsResponse=[{permissionId:PERMISSION_ID_LOCATION,options:{usage:USAGE_ALWAYS}},{permissionId:PERMISSION_ID_CAMERA}];var dispatchError=false;var errorMessage='';/**
|
|
2
|
-
* Causes that the dispatch method resolves with FALSE.
|
|
3
|
-
* @param {string} message The error message.
|
|
4
|
-
* @param {boolean} value Trigger an error or not.
|
|
5
|
-
*/export var triggerDispatchError=function triggerDispatchError(){var message=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'W00t';var value=arguments.length>1&&arguments[1]!==undefined?arguments[1]:true;dispatchError=value;errorMessage=message;};var mockedRequestAppPermissionsRequest=jest.fn().mockImplementation(function RequestAppPermissionsRequest(){var _this=this;this.setPermissions=function(){mockedSetPermissions.apply(void 0,arguments);return _this;};this.dispatch=/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var message,_args=arguments;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:mockedDispatch.apply(void 0,_args);if(!dispatchError){_context.next=5;break;}// Get the message before it's reset
|
|
6
|
-
message=errorMessage;triggerDispatchError('',false);throw new Error(message);case 5:return _context.abrupt("return",mockedPermissionsResponse);case 6:case"end":return _context.stop();}}},_callee);}));return this;});export default mockedRequestAppPermissionsRequest;
|
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* The Event mock is supposed to be used for tests where the event system needs to be tested.
|
|
3
|
-
* Due to the structure of the original module it's not possible to spy on method calls, since
|
|
4
|
-
* the spies do not call the original methods.
|
|
5
|
-
*/var event=require.requireActual("../index")["default"];var mockedEvent=jest.genMockFromModule("../index");var addCallbackSpy=jest.fn();var removeCallbackSpy=jest.fn();mockedEvent.addCallback=function(){addCallbackSpy.apply(void 0,arguments);event.addCallback.apply(event,arguments);};mockedEvent.removeCallback=function(){removeCallbackSpy.apply(void 0,arguments);event.removeCallback.apply(event,arguments);};mockedEvent.call=function(){event.call.apply(event,arguments);};mockedEvent.removeAllListeners=function(){event.removeAllListeners.apply(event,arguments);};mockedEvent.addCallbackSpy=addCallbackSpy;mockedEvent.removeCallbackSpy=removeCallbackSpy;export default mockedEvent;
|
|
@@ -1,4 +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{mockedPipelineRequestFactory}from"./mock";import*as errorHandleTypes from"../../constants/ErrorHandleTypes";var mockedWarn=jest.fn();jest.mock("../../helpers",function(){return{logger:{warn:function warn(){return mockedWarn.apply(void 0,arguments);}}};});describe('MockPipelineRequest',function(){beforeEach(function(){jest.clearAllMocks();});it('should create class that extends MockedPipelineRequest and resolves on dispatch',function(){return new Promise(function(resolve,reject){var FirstClass=mockedPipelineRequestFactory(function(mockedInstance,res){expect(_typeof(mockedInstance)==='object').toBe(true);res(1);});expect(_typeof(FirstClass.mockedDispatchResolver)).toBe('function');var firstInstance=new FirstClass('first');expect(firstInstance.name).toBe('first');expect(firstInstance.input).toEqual({});expect(firstInstance.errorBlacklist).toEqual([]);expect(firstInstance.handleErrors).toBe(errorHandleTypes.ERROR_HANDLE_DEFAULT);var afterSetInput=firstInstance.setInput({firstOne:1});// Check if returns `this`
|
|
2
|
-
expect(afterSetInput instanceof FirstClass).toBe(true);// Check if input is set
|
|
3
|
-
expect(firstInstance.input).toEqual({firstOne:1});var afterSetErrorBlacklist=firstInstance.setErrorBlacklist([1,2]).setHandleErrors(errorHandleTypes.ERROR_HANDLE_SUPPRESS);expect(afterSetErrorBlacklist instanceof FirstClass).toBe(true);expect(afterSetInput.errorBlacklist).toEqual(afterSetErrorBlacklist.errorBlacklist);expect(afterSetErrorBlacklist.errorBlacklist).toEqual([1,2]);expect(afterSetErrorBlacklist.handleErrors).toBe(errorHandleTypes.ERROR_HANDLE_SUPPRESS);// Check dispatch
|
|
4
|
-
afterSetInput.dispatch().then(function(value){expect(value).toBe(1);resolve();})["catch"](function(){reject();});});});it('should create another, independent class',function(){return new Promise(function(resolve,reject){var SecondClass=mockedPipelineRequestFactory(function(mockedInstance,res,rej){expect(_typeof(mockedInstance)==='object').toBe(true);rej(2);});var secondInstance=new SecondClass('second');expect(secondInstance.name).toBe('second');expect(secondInstance.input).toEqual({});var afterSetInput=secondInstance.setInput({secondOne:2});expect(afterSetInput instanceof SecondClass).toBe(true);expect(afterSetInput.input).toEqual({secondOne:2});afterSetInput.dispatch().then(function(){reject();})["catch"](function(val){expect(val).toBe(2);resolve();});});});it('should set defaults when calling methods',function(){var PipelineClass=mockedPipelineRequestFactory(function(){});var instance=new PipelineClass('third');instance.setInput().setErrorBlacklist();expect(instance.input).toEqual({});expect(instance.errorBlacklist).toEqual([]);});it('should handle deprecated setSuppressErrors',function(){var PipelineClass=mockedPipelineRequestFactory(function(){});var request=new PipelineClass('test');request.setSuppressErrors(true);expect(request.handleErrors).toEqual(errorHandleTypes.ERROR_HANDLE_SUPPRESS);request.setSuppressErrors(false);expect(request.handleErrors).toEqual(errorHandleTypes.ERROR_HANDLE_DEFAULT);expect(mockedWarn).toHaveBeenCalledTimes(2);expect(mockedWarn).toHaveBeenCalledWith('Deprecated: setSuppressErrors() will be removed. Use setHandleErrors() instead!');});it('should handle deprecated setHandledErrors',function(){var PipelineClass=mockedPipelineRequestFactory(function(){});var request=new PipelineClass('test');request.setHandledErrors(['SAMPLE_ERROR']);expect(request.errorBlacklist).toEqual(['SAMPLE_ERROR']);expect(mockedWarn).toHaveBeenCalledTimes(1);expect(mockedWarn).toHaveBeenCalledWith('Deprecated: setHandledErrors() will be removed in favor of setErrorBlacklist()!');});describe('setHandleErrors()',function(){it('should throw if input not one of the possible values',function(done){var PipelineClass=mockedPipelineRequestFactory(function(){});var request=new PipelineClass('test');try{request.setHandleErrors('SOME_WEIRD_THING');done('Did not throw');}catch(e){done();}});it('should throw if if input is not a string',function(done){var PipelineClass=mockedPipelineRequestFactory(function(){});var request=new PipelineClass('test');try{request.setHandleErrors(['test']);done('Did not throw');}catch(e){done();}});});});
|
|
@@ -1,22 +0,0 @@
|
|
|
1
|
-
function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import _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{logger}from"../../helpers";import{Scanner}from"./index";import appEvent from"../Event";import registerEvents from"../../commands/registerEvents";import{openScanner,closeScanner,startScanner,setFlashlightMode,stopScanner}from"../../commands/scanner";import{SCANNER_MODE_ON,SCANNER_TYPE_BARCODE,SCANNER_TYPE_IMAGE,SCANNER_ANIMATION_NONE}from"../../constants/Scanner";import{APP_EVENT_SCANNER_DID_SCAN}from"../../constants/AppEvents";import ScannerEventHandler from"../ScannerEventHandler";import ScannerEventListener from"../ScannerEventListener";import ScannerEvent from"../ScannerEvent";jest.mock("../../helpers",function(){return{logger:{error:jest.fn(),warn:jest.fn()}};});var mockedIsLibVersionAtLeast;jest.mock("../../helpers/version",function(){return{isLibVersionAtLeast:function isLibVersionAtLeast(){return mockedIsLibVersionAtLeast.apply(void 0,arguments);}};});jest.mock("../Event");jest.mock("../../commands/registerEvents",function(){return jest.fn();});jest.mock("../../commands/scanner");var mockedEventHandler=new ScannerEventHandler();mockedEventHandler.attach=jest.fn();mockedEventHandler.detach=jest.fn(function(){return true;});describe('Scanner',function(){var scannerInstance;var scope='scope';var type=SCANNER_TYPE_BARCODE;beforeEach(function(){jest.clearAllMocks();scannerInstance=new Scanner();mockedIsLibVersionAtLeast=jest.fn(function(){return true;});});describe('constructor()',function(){it('should register the app scanners scan event correctly',function(){expect(registerEvents).toBeCalledTimes(1);expect(registerEvents).toBeCalledWith([APP_EVENT_SCANNER_DID_SCAN]);});it('should initialize the internal object state correctly',function(){expect(new Set(scannerInstance.supportedTypes)).toEqual(new Set([SCANNER_TYPE_BARCODE,SCANNER_TYPE_IMAGE]));expect(scannerInstance.scope).toBeNull();expect(scannerInstance.type).toBeNull();expect(scannerInstance.opened).toBeFalsy();expect(scannerInstance.running).toBeFalsy();expect(scannerInstance.closeHandler).toBeNull();expect(scannerInstance.flashlightEnabled).toBeFalsy();expect(scannerInstance.eventHandler instanceof ScannerEventHandler).toBeTruthy();});});describe('addListener()',function(){it('should attach the event listener to the event handler',function(){scannerInstance.eventHandler=mockedEventHandler;var l=new ScannerEventListener();scannerInstance.addListener(l);expect(mockedEventHandler.attach).toBeCalledTimes(1);expect(mockedEventHandler.attach).toBeCalledWith(l);});it('should not return any value',function(){expect(scannerInstance.addListener(new ScannerEventListener())).toBeUndefined();});});describe('removeListener()',function(){it('should detach the event listener from the event handler',function(){scannerInstance.eventHandler=mockedEventHandler;var l=new ScannerEventListener();scannerInstance.removeListener(l);expect(mockedEventHandler.detach).toBeCalledTimes(1);expect(mockedEventHandler.detach).toBeCalledWith(l);});it('should forward the return value from the event handler',function(){scannerInstance.eventHandler=mockedEventHandler;// The used event handler detach function is mocked to return true.
|
|
2
|
-
expect(scannerInstance.removeListener(new ScannerEventListener())).toBeTruthy();});});describe('open()',function(){it('should not open and print an error if the app lib version is too low',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var err;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:err=new Error('Failed to open scanner: App lib version must be at least equal to or higher than 21.0.');mockedIsLibVersionAtLeast=jest.fn(function(){return false;});_context.next=4;return expect(scannerInstance.open(scope)).resolves.toBeUndefined();case 4:expect(mockedIsLibVersionAtLeast).toBeCalledWith('21.0');expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(err);expect(scannerInstance.isOpened()).toBeFalsy();case 8:case"end":return _context.stop();}}},_callee);})));it('should not open and print an error when the requested scope is empty',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var err;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:err=new Error('Failed to open scanner: Scope can not be empty.');_context2.next=3;return expect(scannerInstance.open(null)).resolves.toBeUndefined();case 3:expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(err);expect(scannerInstance.isOpened()).toBeFalsy();case 6:case"end":return _context2.stop();}}},_callee2);})));it('should print an error instead of opening when the requested scanner type is unsupported',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var dummy,err;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:dummy='DUMMY_TYPE';err=new Error("Failed to open scanner: ".concat(dummy," is a not supported scanner type."));_context3.next=4;return expect(scannerInstance.open(scope,dummy)).resolves.toBeUndefined();case 4:expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(err);expect(scannerInstance.isOpened()).toBeFalsy();case 7:case"end":return _context3.stop();}}},_callee3);})));it('should print an error and stay opened when already opened',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var err;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:err=new Error("Failed to open scanner: An instance with scope \"".concat(scope,"\" is already running."));// Simulate opened state.
|
|
3
|
-
scannerInstance.opened=true;scannerInstance.scope=scope;_context4.next=5;return expect(scannerInstance.open(scope)).resolves.toBeUndefined();case 5:expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(err);expect(scannerInstance.isOpened()).toBeTruthy();case 8:case"end":return _context4.stop();}}},_callee4);})));it('should not open when an invalid close handler is set',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var err;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:err=new Error('Failed to open scanner: Close handler must be a function.');// Pass an object instead of a callback to trigger the error
|
|
4
|
-
_context5.next=3;return expect(scannerInstance.open(scope,type,{})).resolves.toBeUndefined();case 3:expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(err);expect(scannerInstance.isOpened()).toBeFalsy();case 6:case"end":return _context5.stop();}}},_callee5);})));it('should register the app event callback',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return scannerInstance.open(scope);case 2:expect(appEvent.addCallbackSpy).toBeCalledTimes(1);expect(appEvent.addCallbackSpy).toBeCalledWith(APP_EVENT_SCANNER_DID_SCAN,scannerInstance.handleScan);case 4:case"end":return _context6.stop();}}},_callee6);})));it('should open the scanner',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:_context7.next=2;return scannerInstance.open(scope);case 2:expect(openScanner).toBeCalledTimes(1);case 3:case"end":return _context7.stop();}}},_callee7);})));it('should provide correct parameters to the open scanner app command',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:_context8.next=2;return scannerInstance.open(scope);case 2:expect(openScanner).toBeCalledWith({src:'',modes:_defineProperty({},type,SCANNER_MODE_ON),animation:SCANNER_ANIMATION_NONE});case 3:case"end":return _context8.stop();}}},_callee8);})));it('should update the internal object state correctly',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var closeHandler;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:closeHandler=jest.fn();_context9.next=3;return scannerInstance.open(scope,SCANNER_TYPE_BARCODE,closeHandler);case 3:expect(scannerInstance.scope).toStrictEqual(scope);expect(scannerInstance.type).toStrictEqual(SCANNER_TYPE_BARCODE);expect(scannerInstance.opened).toBeTruthy();expect(scannerInstance.running).toBeTruthy();expect(scannerInstance.closeHandler).toBe(closeHandler);// Recreate Scanner object to check a different set of open params.
|
|
5
|
-
scannerInstance=new Scanner();_context9.next=11;return scannerInstance.open(scope,SCANNER_TYPE_IMAGE);case 11:expect(scannerInstance.type).toStrictEqual(SCANNER_TYPE_IMAGE);expect(scannerInstance.opened).toBeTruthy();expect(scannerInstance.running).toBeFalsy();expect(scannerInstance.closeHandler).toBe(null);case 15:case"end":return _context9.stop();}}},_callee9);})));});describe('start()',function(){it('should print an error message if start is called without opening first',function(){scannerInstance.start();expect(logger.error).toBeCalledTimes(1);expect(startScanner).not.toBeCalled();});it('should not do anything if the Scanner is not opened',function(){scannerInstance.start();expect(startScanner).not.toBeCalled();});it('should not do anything when the Scanner is already running',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:_context10.next=2;return scannerInstance.open('scope');case 2:scannerInstance.start();expect(startScanner).not.toBeCalled();case 4:case"end":return _context10.stop();}}},_callee10);})));it('should dispatch the startScanner command when the Scanner is not already running',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee11(){return _regeneratorRuntime.wrap(function _callee11$(_context11){while(1){switch(_context11.prev=_context11.next){case 0:_context11.next=2;return scannerInstance.open('scope');case 2:scannerInstance.running=false;scannerInstance.start();expect(startScanner).toBeCalled();case 5:case"end":return _context11.stop();}}},_callee11);})));});describe('stop()',function(){it('should print an error message if start is called without opening first',function(){scannerInstance.stop();expect(logger.error).toBeCalledTimes(1);expect(stopScanner).not.toBeCalled();});it('should not do anything if the Scanner is not opened',function(){scannerInstance.stop();expect(stopScanner).not.toBeCalled();});it('should not do anything when the Scanner is not running',function(){scannerInstance.stop();expect(stopScanner).not.toBeCalled();});it('should dispatch the stopScanner command when the Scanner is running',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee12(){return _regeneratorRuntime.wrap(function _callee12$(_context12){while(1){switch(_context12.prev=_context12.next){case 0:_context12.next=2;return scannerInstance.open('scope');case 2:scannerInstance.stop();expect(stopScanner).toBeCalled();case 4:case"end":return _context12.stop();}}},_callee12);})));});describe('close()',function(){beforeEach(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee13(){return _regeneratorRuntime.wrap(function _callee13$(_context13){while(1){switch(_context13.prev=_context13.next){case 0:_context13.next=2;return scannerInstance.open(scope);case 2:case"end":return _context13.stop();}}},_callee13);})));it('should print a warning if close is called without opening first',function(){// Closing twice should trigger this warning.
|
|
6
|
-
scannerInstance.close();scannerInstance.close();expect(logger.warn).toBeCalledTimes(1);});it('should unregister the handleScan callback',function(){scannerInstance.close();expect(appEvent.removeCallbackSpy).toBeCalledTimes(1);expect(appEvent.removeCallbackSpy).toBeCalledWith(APP_EVENT_SCANNER_DID_SCAN,scannerInstance.handleScan);});it('should force switch off the flashlight',function(){scannerInstance.toggleFlashlight(true);expect(scannerInstance.flashlightEnabled).toBeTruthy();scannerInstance.close();expect(scannerInstance.flashlightEnabled).toBeFalsy();});it('should close the app scanner',function(){scannerInstance.close();expect(closeScanner).toBeCalled();});it('should reset the internal object state correctly',function(){expect(scannerInstance.scope).not.toBeNull();scannerInstance.close();expect(scannerInstance.scope).toBeNull();expect(scannerInstance.type).toBeNull();expect(scannerInstance.opened).toBeFalsy();expect(scannerInstance.running).toBeFalsy();expect(scannerInstance.closeHandler).toBeNull();expect(scannerInstance.flashlightEnabled).toBeFalsy();});});describe('toggleFlashlight()',function(){beforeEach(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee14(){return _regeneratorRuntime.wrap(function _callee14$(_context14){while(1){switch(_context14.prev=_context14.next){case 0:_context14.next=2;return scannerInstance.open(scope);case 2:case"end":return _context14.stop();}}},_callee14);})));it('should allow setting the flashlight mode directly',function(){// Start with "off" state.
|
|
7
|
-
expect(scannerInstance.flashlightEnabled).toBeFalsy();// Make sure setting it to "off" again does not toggle.
|
|
8
|
-
scannerInstance.toggleFlashlight(false);expect(scannerInstance.flashlightEnabled).toBeFalsy();// Now make sure switching "on" works.
|
|
9
|
-
scannerInstance.toggleFlashlight(true);expect(scannerInstance.flashlightEnabled).toBeTruthy();// Now make sure switching "on" again does not toggle.
|
|
10
|
-
scannerInstance.toggleFlashlight(true);expect(scannerInstance.flashlightEnabled).toBeTruthy();// Check if switching "off" works as well, when it was enabled.
|
|
11
|
-
scannerInstance.toggleFlashlight(false);expect(scannerInstance.flashlightEnabled).toBeFalsy();});it('should allow to toggle between on and off modes',function(){// Start with "off" state.
|
|
12
|
-
expect(scannerInstance.flashlightEnabled).toBeFalsy();// Test if simple "toggle" enables it now
|
|
13
|
-
scannerInstance.toggleFlashlight();expect(scannerInstance.flashlightEnabled).toBeTruthy();// Test if a second "toggle" disables it afterwards
|
|
14
|
-
scannerInstance.toggleFlashlight();expect(scannerInstance.flashlightEnabled).toBeFalsy();});it('should call the app command even if the internal state did not change',function(){// Start at "off".
|
|
15
|
-
expect(scannerInstance.flashlightEnabled).toBeFalsy();// Call the app command no matter what state it is (to allow resolving state inconsistencies)
|
|
16
|
-
scannerInstance.toggleFlashlight(false);expect(setFlashlightMode).toBeCalledTimes(1);scannerInstance.toggleFlashlight(true);expect(setFlashlightMode).toBeCalledTimes(2);scannerInstance.toggleFlashlight(true);expect(setFlashlightMode).toBeCalledTimes(3);scannerInstance.toggleFlashlight(false);expect(setFlashlightMode).toBeCalledTimes(4);scannerInstance.toggleFlashlight(false);expect(setFlashlightMode).toBeCalledTimes(5);scannerInstance.toggleFlashlight();expect(setFlashlightMode).toBeCalledTimes(6);scannerInstance.toggleFlashlight();expect(setFlashlightMode).toBeCalledTimes(7);scannerInstance.toggleFlashlight();expect(setFlashlightMode).toBeCalledTimes(8);});it('should call the app command correctly',function(){// Start with "off" state.
|
|
17
|
-
expect(scannerInstance.flashlightEnabled).toBeFalsy();// Toggle "on".
|
|
18
|
-
scannerInstance.toggleFlashlight();expect(setFlashlightMode).toBeCalledWith(true);// Toggle "off".
|
|
19
|
-
scannerInstance.toggleFlashlight();expect(setFlashlightMode).toBeCalledWith(false);// Switch "off".
|
|
20
|
-
scannerInstance.toggleFlashlight(false);expect(setFlashlightMode).toBeCalledWith(false);// Switch "on".
|
|
21
|
-
scannerInstance.toggleFlashlight(true);expect(setFlashlightMode).toBeCalledWith(true);});});describe('handleScan()',function(){var payload={format:'format',code:'code'};var closeHandlerMock=jest.fn();var hasListenersForEventMock;beforeEach(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee15(){return _regeneratorRuntime.wrap(function _callee15$(_context15){while(1){switch(_context15.prev=_context15.next){case 0:_context15.next=2;return scannerInstance.open(scope,type,closeHandlerMock);case 2:hasListenersForEventMock=jest.spyOn(scannerInstance.eventHandler,'hasListenersForEvent').mockReturnValue(true);case 3:case"end":return _context15.stop();}}},_callee15);})));it('should forward a ScannerEvent to the event handler',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee16(){var result,mockedNotifyAllListeners;return _regeneratorRuntime.wrap(function _callee16$(_context16){while(1){switch(_context16.prev=_context16.next){case 0:result=null;mockedNotifyAllListeners=jest.fn(function(e){result=e;});scannerInstance.eventHandler.notifyAllListeners=mockedNotifyAllListeners;_context16.next=5;return scannerInstance.handleScan(payload);case 5:expect(mockedNotifyAllListeners).toBeCalledTimes(1);expect(result instanceof ScannerEvent).toBeTruthy();expect(result.payload).toBe(payload);case 8:case"end":return _context16.stop();}}},_callee16);})));it('should notify the close handler if the Scanner is done scanning',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee17(){return _regeneratorRuntime.wrap(function _callee17$(_context17){while(1){switch(_context17.prev=_context17.next){case 0:_context17.next=2;return scannerInstance.handleScan(payload);case 2:expect(closeHandlerMock).toBeCalledTimes(1);expect(closeHandlerMock).toBeCalledWith(scannerInstance);case 4:case"end":return _context17.stop();}}},_callee17);})));it('should restart if any of the listeners throws an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee19(){return _regeneratorRuntime.wrap(function _callee19$(_context19){while(1){switch(_context19.prev=_context19.next){case 0:scannerInstance.start=jest.fn();scannerInstance.addListener(new ScannerEventListener().setHandler(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee18(){return _regeneratorRuntime.wrap(function _callee18$(_context18){while(1){switch(_context18.prev=_context18.next){case 0:throw new Error('Dummy error to enforce Scanner restart!');case 1:case"end":return _context18.stop();}}},_callee18);}))));_context19.next=4;return scannerInstance.handleScan(payload);case 4:expect(scannerInstance.opened).toBeTruthy();expect(scannerInstance.start).toBeCalledTimes(1);case 6:case"end":return _context19.stop();}}},_callee19);})));it('should not run when no suitable event listener was registered',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee20(){var result;return _regeneratorRuntime.wrap(function _callee20$(_context20){while(1){switch(_context20.prev=_context20.next){case 0:hasListenersForEventMock.mockReturnValueOnce(false);_context20.next=3;return scannerInstance.handleScan(payload);case 3:result=_context20.sent;expect(result).toBeUndefined();expect(scannerInstance.handling).toBeFalsy();case 6:case"end":return _context20.stop();}}},_callee20);})));it('should not be running after a successful scan if not restarted',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee21(){var stopSpy;return _regeneratorRuntime.wrap(function _callee21$(_context21){while(1){switch(_context21.prev=_context21.next){case 0:stopSpy=jest.spyOn(scannerInstance,'stop');_context21.next=3;return scannerInstance.handleScan(payload);case 3:expect(scannerInstance.running).toBeFalsy();expect(stopSpy).toBeCalled();case 5:case"end":return _context21.stop();}}},_callee21);})));it("should not close the Scanner on it's own",/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee22(){return _regeneratorRuntime.wrap(function _callee22$(_context22){while(1){switch(_context22.prev=_context22.next){case 0:_context22.next=2;return scannerInstance.handleScan(payload);case 2:expect(scannerInstance.opened).toBeTruthy();case 3:case"end":return _context22.stop();}}},_callee22);})));it('should return a promise',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee23(){return _regeneratorRuntime.wrap(function _callee23$(_context23){while(1){switch(_context23.prev=_context23.next){case 0:expect(scannerInstance.handleScan(payload)instanceof Promise).toBeTruthy();case 1:case"end":return _context23.stop();}}},_callee23);})));it('should catch all errors, from the listeners',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee26(){return _regeneratorRuntime.wrap(function _callee26$(_context26){while(1){switch(_context26.prev=_context26.next){case 0:scannerInstance.addListener(new ScannerEventListener().setHandler(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee24(){return _regeneratorRuntime.wrap(function _callee24$(_context24){while(1){switch(_context24.prev=_context24.next){case 0:throw new Error('First error to catch!');case 1:case"end":return _context24.stop();}}},_callee24);}))));scannerInstance.addListener(new ScannerEventListener().setHandler(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee25(){return _regeneratorRuntime.wrap(function _callee25$(_context25){while(1){switch(_context25.prev=_context25.next){case 0:throw new Error('Second error to catch!');case 1:case"end":return _context25.stop();}}},_callee25);}))));// The Promise should resolve to "undefined" rather than throw an error (mute errors).
|
|
22
|
-
_context26.next=4;return expect(scannerInstance.handleScan(payload)).resolves.toBeUndefined();case 4:case"end":return _context26.stop();}}},_callee26);})));it('should ignore duplicated call in handling stage',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee27(){return _regeneratorRuntime.wrap(function _callee27$(_context27){while(1){switch(_context27.prev=_context27.next){case 0:_context27.next=2;return scannerInstance.handleScan(payload);case 2:_context27.next=4;return scannerInstance.handleScan(payload);case 4:_context27.next=6;return scannerInstance.handleScan(payload);case 6:expect(stopScanner).toHaveBeenCalledTimes(1);case 7:case"end":return _context27.stop();}}},_callee27);})));});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import ScannerEvent from"./index";describe('ScannerEvent',function(){it('should set and return all values correctly',function(){var scope='scope';var type='type';var payload={format:'format',code:'code'};var e=new ScannerEvent(scope,type,payload);expect(e.getScope()).toBe(scope);expect(e.getType()).toBe(type);expect(e.getPayload()).toBe(payload);});});
|
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import ScannerEventHandler from"./index";import ScannerEventListener from"../ScannerEventListener";import ScannerEvent from"../ScannerEvent";jest.mock('@shopgate/pwa-core/classes/AppCommand');// Prevent console output of the logger
|
|
2
|
-
jest.mock("../../helpers",function(){return{logger:{debug:jest.fn(),dir:jest.fn(),dirxml:jest.fn(),error:jest.fn(),info:jest.fn(),log:jest.fn(),warn:jest.fn()}};});describe('ScannerEventHandler',function(){var eventHandler=new ScannerEventHandler();beforeEach(function(){jest.clearAllMocks();eventHandler.eventListeners.clear();});describe('constructor()',function(){it('should not have any listeners after initialization',function(){expect(eventHandler.eventListeners.size).toBe(0);});});describe('attach(eventListener)',function(){it('should attach the event listener',function(){var l=new ScannerEventListener();eventHandler.attach(l);expect(eventHandler.eventListeners.size).toBe(1);expect(eventHandler.eventListeners.has(l)).toBe(true);});it('should attach every event listener only once',function(){var l1=new ScannerEventListener();var l2=new ScannerEventListener();eventHandler.attach(l1);eventHandler.attach(l1);eventHandler.attach(l2);eventHandler.attach(l2);expect(eventHandler.eventListeners.size).toBe(2);expect(eventHandler.eventListeners.has(l1)).toBe(true);expect(eventHandler.eventListeners.has(l2)).toBe(true);});});describe('detach(eventListener)',function(){it('should detach the correct event listener',function(){var l1=new ScannerEventListener();var l2=new ScannerEventListener();var l3=new ScannerEventListener();eventHandler.attach(l1);eventHandler.attach(l2);eventHandler.attach(l3);eventHandler.detach(l2);expect(eventHandler.eventListeners.size).toBe(2);expect(eventHandler.eventListeners.has(l1)).toBe(true);expect(eventHandler.eventListeners.has(l2)).toBe(false);expect(eventHandler.eventListeners.has(l3)).toBe(true);});it('should return true if a listener was detached',function(){var l=new ScannerEventListener();eventHandler.attach(l);expect(eventHandler.detach(l)).toBe(true);});it("should return false if a listener can't be found to detach",function(){var l=new ScannerEventListener();expect(eventHandler.detach(l)).toBe(false);});});describe('hasListenersForEvent(format)',function(){it('should return true when listeners are registered for a passed format',function(){var format='format';var otherFormat='otherFormat';eventHandler.attach(new ScannerEventListener(null,'scope','type',[format]).setHandler(function(){}));eventHandler.attach(new ScannerEventListener(null,null,null,[otherFormat]).setHandler(function(){}));var event=new ScannerEvent('scope','type',{format:format});var result=eventHandler.hasListenersForEvent(event);expect(result).toBe(true);});it('should return false when no listeners are registered for a passed format',function(){var format='format';var otherFormat='otherFormat';eventHandler.attach(new ScannerEventListener(null,'scope','type',[format]).setHandler(function(){}));var event=new ScannerEvent('scope','type',{format:otherFormat});var result=eventHandler.hasListenersForEvent(event);expect(result).toBe(false);});});describe('notifyAllListeners(event)',function(){var mockPayload={format:'format',code:'code'};it('should notify all listeners',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var customHandler;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customHandler=jest.fn();eventHandler.attach(new ScannerEventListener().setHandler(customHandler));eventHandler.attach(new ScannerEventListener().setHandler(customHandler));eventHandler.attach(new ScannerEventListener().setHandler(customHandler));_context.next=6;return eventHandler.notifyAllListeners(new ScannerEvent('scope','type',mockPayload));case 6:expect(customHandler).toBeCalledTimes(3);case 7:case"end":return _context.stop();}}},_callee);})));it('should notify interested listeners only',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var customHandler,scope1,scope2,type1,type2;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:customHandler=jest.fn();scope1='scope1';scope2='scope2';type1='type1';type2='type2';// Listeners to notify
|
|
3
|
-
eventHandler.attach(new ScannerEventListener(null,null,null).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,null,type1).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope1,null).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope1,type1).setHandler(customHandler));// Listeners to skip
|
|
4
|
-
eventHandler.attach(new ScannerEventListener(null,null,type2).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope1,type2).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope2,null).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope2,type1).setHandler(customHandler));eventHandler.attach(new ScannerEventListener(null,scope2,type2).setHandler(customHandler));_context2.next=16;return eventHandler.notifyAllListeners(new ScannerEvent(scope1,type1,mockPayload));case 16:expect(customHandler).toBeCalledTimes(4);case 17:case"end":return _context2.stop();}}},_callee2);})));it('should throw the first error if one or more listeners failed',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var error1,error2,failingHandler1,failingHandler2,succeedingHandler;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:error1=new Error('Handle failed - ERROR 1!');error2=new Error('Handle failed - ERROR 2!');failingHandler1=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:throw error1;case 1:case"end":return _context3.stop();}}},_callee3);})));failingHandler2=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:throw error2;case 1:case"end":return _context4.stop();}}},_callee4);})));succeedingHandler=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:case"end":return _context5.stop();}}},_callee5);})));eventHandler.attach(new ScannerEventListener().setHandler(succeedingHandler));eventHandler.attach(new ScannerEventListener().setHandler(failingHandler2));eventHandler.attach(new ScannerEventListener().setHandler(failingHandler1));// Handler "failingHandler2" will fail first, because it is attached before "failingHandler1".
|
|
5
|
-
_context6.next=10;return expect(eventHandler.notifyAllListeners(new ScannerEvent('scope','type',mockPayload))).rejects.toThrow(error2);case 10:case"end":return _context6.stop();}}},_callee6);})));it('should resolve with "undefined" if all listeners succeeded',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var succeedingHandler;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:succeedingHandler=jest.fn(function(){return'Some ignored return value';});eventHandler.attach(new ScannerEventListener().setHandler(succeedingHandler));eventHandler.attach(new ScannerEventListener().setHandler(succeedingHandler));// Expect true (in an Array) for each listener
|
|
6
|
-
_context7.t0=expect;_context7.next=6;return eventHandler.notifyAllListeners(new ScannerEvent('scope','type',mockPayload));case 6:_context7.t1=_context7.sent;(0,_context7.t0)(_context7.t1).toBe(undefined);case 8:case"end":return _context7.stop();}}},_callee7);})));});});
|
|
@@ -1,3 +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 _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 ScannerEventListener from"./index";import ScannerEvent from"../ScannerEvent";import AppScanner from"../Scanner";import{logger}from"../../helpers";jest.mock('@shopgate/pwa-core/classes/AppCommand');jest.mock("../../helpers",function(){return{logger:{error:jest.fn(),warn:jest.fn()}};});describe('ScannerEventListener',function(){var name='Mocked Event Listener';beforeEach(function(){jest.clearAllMocks();});describe('constructor()',function(){it('should initialize the name correctly if none was set',function(){var l=new ScannerEventListener();expect(l.name).toBe('unnamed');});it('should initialize the type and scope correctly if none were set',function(){var l=new ScannerEventListener();expect(l.scope).toBe(null);expect(l.type).toBe(null);});it('should store the name, scope and type correctly if they were set',function(){var scope='testScope';var type='testType';var l=new ScannerEventListener(name,scope,type);expect(l.name).toBe(name);expect(l.scope).toBe(scope);expect(l.type).toBe(type);});it('should not have a default handler after new instance creation',function(){var l=new ScannerEventListener();expect(l.handler).toBe(null);});});describe('setHandler(handler)',function(){it('should output an error if the given handler is not a function',function(){// Just pass a string instead of a real handler
|
|
2
|
-
var invalidHandler='invalid handler';var invalidHandlerErrorMessage='The ScannerEventListener handler must be a function!';new ScannerEventListener().setHandler(invalidHandler);expect(logger.error).toBeCalledTimes(1);expect(logger.error).toBeCalledWith(new Error(invalidHandlerErrorMessage));});it('should not output an "invalid handler" error for a valid handler',function(){new ScannerEventListener().setHandler(jest.fn());expect(logger.error).not.toBeCalled();});it('should return the current listener instance after setting the handler',function(){var l=new ScannerEventListener();expect(l.setHandler(jest.fn())).toBe(l);});it('should set the handler correctly',function(){var customHandler=jest.fn();var l=new ScannerEventListener().setHandler(customHandler);expect(l.handler).toBe(customHandler);});});describe('attach()',function(){// Make sure to restore scanner object functionality after each test
|
|
3
|
-
var addListener=AppScanner.addListener;afterEach(function(){AppScanner.addListener=addListener;});it('should attach the new listener to the global Scanner object',function(){AppScanner.addListener=jest.fn();var l=new ScannerEventListener();l.attach();expect(AppScanner.addListener).toBeCalledTimes(1);expect(AppScanner.addListener).toBeCalledWith(l);});});describe('canHandleEvent(event)',function(){var mockPayload={format:'format',code:'code'};it('should return false and print a warning if no handlers are attached',function(){var l=new ScannerEventListener();var result=l.canHandleEvent(null);expect(result).toBe(false);expect(logger.warn).toBeCalledTimes(1);});it('should return true on every event for "global" listeners',function(){var listenScope=null;var listenType=null;var differentScope='different-scope';var differentType='different-type';var l=new ScannerEventListener(name,listenScope,listenType).setHandler(function(){});var result=l.canHandleEvent(new ScannerEvent(differentScope,differentType,mockPayload));expect(result).toBe(true);});it('should return the correct values for specific event scopes only',function(){var listenScope='interesting-scope';var differentScope='different-scope';var anyType='any-type';var l=new ScannerEventListener(name,listenScope).setHandler(function(){});var result=[l.canHandleEvent(new ScannerEvent(listenScope,anyType,mockPayload)),l.canHandleEvent(new ScannerEvent(differentScope,anyType,mockPayload))];expect(result).toEqual([true,false]);});it('should return the correct values for specific event types only',function(){var listenType='interesting-type';var differentType='different-type';var anyScope='any-scope';var l=new ScannerEventListener(name,null,listenType).setHandler(function(){});var result=[l.canHandleEvent(new ScannerEvent(anyScope,listenType,mockPayload)),l.canHandleEvent(new ScannerEvent(anyScope,differentType,mockPayload))];expect(result).toEqual([true,false]);});it('should return the correct values for specific event scope/type combinations only',function(){var listenScope='interesting-scope';var listenType='interesting-type';var differentScope='different-scope';var differentType='different-type';var l=new ScannerEventListener(name,listenScope,listenType).setHandler(function(){});var result=[l.canHandleEvent(new ScannerEvent(listenScope,listenType,mockPayload)),l.canHandleEvent(new ScannerEvent(listenScope,differentType,mockPayload)),l.canHandleEvent(new ScannerEvent(differentScope,listenType,mockPayload)),l.canHandleEvent(new ScannerEvent(differentScope,differentType,mockPayload))];expect(result).toEqual([true,false,false,false]);});it('should return the correct values for specific payload format combinations only ',function(){var listenScope='interesting-scope';var listenType='interesting-type';var listenFormats=['format'];var l=new ScannerEventListener(name,listenScope,listenType,listenFormats).setHandler(function(){});var result=[l.canHandleEvent(new ScannerEvent(listenScope,listenType,mockPayload)),l.canHandleEvent(new ScannerEvent(listenScope,listenType,_extends({},mockPayload,{format:'otherFormat'})))];expect(result).toEqual([true,false]);});});describe('notify(event)',function(){var mockPayload={format:'format',code:'code'};it('should print a warning if the custom handler returns a value',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var customHandler,l;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:customHandler=jest.fn(function(){return'Some return-value';});l=new ScannerEventListener(name).setHandler(customHandler);_context.next=4;return l.notify(new ScannerEvent('scope','type',mockPayload));case 4:expect(logger.warn).toBeCalledTimes(1);case 5:case"end":return _context.stop();}}},_callee);})));it('should call the handler for specific event scope/type combinations only',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var customHandler,listenScope,listenType,differentScope,differentType,l,_customHandler$mock$c,_customHandler$mock$c2,event;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:customHandler=jest.fn();listenScope='interesting-scope';listenType='interesting-type';differentScope='different-scope';differentType='different-type';l=new ScannerEventListener(name,listenScope,listenType).setHandler(customHandler);_context2.next=8;return l.notify(new ScannerEvent(listenScope,listenType,mockPayload));case 8:_context2.next=10;return l.notify(new ScannerEvent(listenScope,differentType,mockPayload));case 10:_context2.next=12;return l.notify(new ScannerEvent(differentScope,listenType,mockPayload));case 12:_context2.next=14;return l.notify(new ScannerEvent(differentScope,differentType,mockPayload));case 14:expect(customHandler).toBeCalledTimes(1);_customHandler$mock$c=_slicedToArray(customHandler.mock.calls,1),_customHandler$mock$c2=_slicedToArray(_customHandler$mock$c[0],1),event=_customHandler$mock$c2[0];expect(event).toBeInstanceOf(ScannerEvent);expect(event.getScope()).toBe(listenScope);expect(event.getType()).toBe(listenType);expect(event.getPayload()).toEqual(mockPayload);case 20:case"end":return _context2.stop();}}},_callee2);})));it('should forward the handler error to the caller',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var customHandlerError,customHandler,l;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:customHandlerError=new Error('Custom handler failed!');customHandler=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:throw customHandlerError;case 1:case"end":return _context3.stop();}}},_callee3);})));l=new ScannerEventListener(name).setHandler(customHandler);_context4.next=5;return expect(l.notify(new ScannerEvent('scope','type',mockPayload))).rejects.toThrow(customHandlerError);case 5:case"end":return _context4.stop();}}},_callee4);})));});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import ScanProcessingError from"./ScanProcessingError";describe('ScanProcessingError',function(){it('should create the error as expected everything is set properly',function(){var message='Message';var title='Title';var error=new ScanProcessingError(message,title);expect(error).toBeInstanceOf(Error);expect(error.message).toBe(message);expect(error.title).toBe(title);});it('should create the error as expected when just a message is set',function(){var message='Message';var error=new ScanProcessingError(message);expect(error).toBeInstanceOf(Error);expect(error.message).toBe(message);expect(error.title).toBe(null);});});
|
|
@@ -1,17 +0,0 @@
|
|
|
1
|
-
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}function _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 event from"../Event";import registerEvents from"../../commands/registerEvents";import ScannerManager,{APP_EVENT_SCANNER_DID_SCAN,APP_EVENT_SCANNER_RESULT_PROCESSED,APP_EVENT_CLOSE_SCANNER,APP_EVENT_SCANNER_ERROR_CONFIRMED}from"./index";import ScanProcessingError from"./ScanProcessingError";import{SCANNER_MODE_ON,SCANNER_TYPE_BARCODE,SCANNER_TYPE_CARD,SCANNER_TYPE_IMAGE}from"../../constants/Scanner";jest.mock("../Event");var mockedBroadcastEventCmd=jest.fn();jest.mock("../../commands/broadcastEvent",function(){return function(){return mockedBroadcastEventCmd.apply(void 0,arguments);};});jest.mock("../../commands/registerEvents",function(){return jest.fn();});var mockedOpenScannerCmd=jest.fn();var mockedCloseScannerCmd=jest.fn();var mockedStartScannerCmd=jest.fn();jest.mock("../../commands/scanner",function(){return{openScanner:function openScanner(){return mockedOpenScannerCmd.apply(void 0,arguments);},closeScanner:function closeScanner(){return mockedCloseScannerCmd.apply(void 0,arguments);},startScanner:function startScanner(){return mockedStartScannerCmd.apply(void 0,arguments);}};});var mockErrorLogger=jest.fn();jest.mock("../../helpers",function(){return{logger:{error:function error(){return mockErrorLogger.apply(void 0,arguments);},warn:function warn(){return function(){};}}};});describe('ScannerManager',function(){var instance;var mockedScanHandler=jest.fn().mockResolvedValue();var eventAddCallbackSpy=event.addCallbackSpy;var eventRemoveCallbackSpy=event.removeCallbackSpy;beforeAll(function(){});beforeEach(function(){jest.clearAllMocks();instance=new ScannerManager();instance.registerScanHandler(mockedScanHandler);});afterEach(function(){// Take care the the scanner event callbacks are removed.
|
|
2
|
-
event.removeAllListeners();});describe('.constructor()',function(){it('should register necessary only once',function(){expect(registerEvents).toHaveBeenCalledTimes(1);var newInstance=new ScannerManager();expect(registerEvents).toHaveBeenCalledTimes(1);expect(newInstance).toBeInstanceOf(ScannerManager);});it('should work as expected when no options are passed',function(){expect(instance.autoClose).toBe(true);expect(instance.supportedTypes).toEqual(expect.any(Array));expect(instance.supportedTypes).not.toHaveLength(0);expect(_typeof(instance.scanHandler)).toBe('function');});it('should work as expected when the auto close option is passed',function(){instance=new ScannerManager({autoClose:false});expect(instance.autoClose).toBe(false);});});describe('.registerScanHandler()',function(){it('should work as expected when a valid handler was passed',function(){// eslint-disable-next-line require-jsdoc
|
|
3
|
-
var handler=function handler(){};var result=instance.registerScanHandler(handler);expect(result).toEqual(instance);expect(instance.scanHandler).toBe(handler);});it('should work as expected when an invalid handler was passed',function(){var handler=null;var result=instance.registerScanHandler(handler);expect(result).toEqual(instance);expect(_typeof(instance.scanHandler)).toBe('function');});});describe('.openScanner()',function(){it('should work as expected without params',function(){var expectedOpenScannerParams={modes:_defineProperty({},SCANNER_TYPE_BARCODE,SCANNER_MODE_ON)};var result=instance.openScanner();expect(result).toEqual(instance);expect(eventAddCallbackSpy).toHaveBeenCalledTimes(3);expect(eventAddCallbackSpy).toHaveBeenCalledWith(APP_EVENT_CLOSE_SCANNER,instance.closeScanner);expect(eventAddCallbackSpy).toHaveBeenCalledWith(APP_EVENT_SCANNER_DID_SCAN,instance.scannerDidScanListener);expect(eventAddCallbackSpy).toHaveBeenCalledWith(APP_EVENT_SCANNER_ERROR_CONFIRMED,expect.any(Function));expect(mockedOpenScannerCmd).toHaveBeenCalledTimes(1);expect(mockedOpenScannerCmd).toHaveBeenCalledWith(expectedOpenScannerParams);});it('should work as expected when barcode type is passed as param',function(){var expectedOpenScannerParams={modes:_defineProperty({},SCANNER_TYPE_BARCODE,SCANNER_MODE_ON)};var result=instance.openScanner(SCANNER_TYPE_BARCODE);expect(result).toEqual(instance);expect(eventAddCallbackSpy).toHaveBeenCalledTimes(3);expect(mockedOpenScannerCmd).toHaveBeenCalledTimes(1);expect(mockedOpenScannerCmd).toHaveBeenCalledWith(expectedOpenScannerParams);});it('should work as expected when image type is passed as param',function(){var expectedOpenScannerParams={modes:_defineProperty({},SCANNER_TYPE_IMAGE,SCANNER_MODE_ON)};var result=instance.openScanner(SCANNER_TYPE_IMAGE);expect(result).toEqual(instance);expect(eventAddCallbackSpy).toHaveBeenCalledTimes(3);expect(mockedOpenScannerCmd).toHaveBeenCalledTimes(1);expect(mockedOpenScannerCmd).toHaveBeenCalledWith(expectedOpenScannerParams);});it('should log an error when an unsupported param is passed',function(){var result=instance.openScanner(SCANNER_TYPE_CARD);expect(result).toEqual(instance);expect(mockErrorLogger).toHaveBeenCalledTimes(1);expect(eventAddCallbackSpy).toHaveBeenCalledTimes(0);expect(mockedOpenScannerCmd).toHaveBeenCalledTimes(0);});});describe('.closeScanner()',function(){it('should work as expected',function(){var result=instance.closeScanner();expect(result).toEqual(instance);expect(eventRemoveCallbackSpy).toHaveBeenCalledTimes(3);expect(eventRemoveCallbackSpy).toHaveBeenCalledWith(APP_EVENT_CLOSE_SCANNER,instance.closeScanner);expect(eventRemoveCallbackSpy).toHaveBeenCalledWith(APP_EVENT_SCANNER_DID_SCAN,instance.scannerDidScanListener);expect(eventRemoveCallbackSpy).toHaveBeenCalledWith(APP_EVENT_SCANNER_ERROR_CONFIRMED,expect.any(Function));expect(mockedCloseScannerCmd).toHaveBeenCalledTimes(1);});});describe('.scannerDidScanListener()',function(){var requestId='abc123';var mockedCloseScanner;beforeEach(function(){// Create a new instance without a default handler for the following tests.
|
|
4
|
-
instance=new ScannerManager();mockedCloseScanner=jest.spyOn(instance,'closeScanner');});it('should close the scanner when the handler does not throw an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var handler;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:// eslint-disable-next-line require-jsdoc
|
|
5
|
-
handler=/*#__PURE__*/function(){var _ref2=_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:case"end":return _context.stop();}}},_callee);}));return function handler(){return _ref2.apply(this,arguments);};}();instance.registerScanHandler(handler);_context2.next=4;return instance.scannerDidScanListener({requestId:requestId});case 4:expect(mockedCloseScanner).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenLastCalledWith({event:APP_EVENT_SCANNER_RESULT_PROCESSED,parameters:[requestId,true,null]});case 7:case"end":return _context2.stop();}}},_callee2);})));it('should not close the scanner when the handler when autoClose is turned off',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:instance.autoClose=false;_context3.next=3;return instance.scannerDidScanListener({requestId:requestId});case 3:expect(mockedCloseScanner).toHaveBeenCalledTimes(0);expect(mockedBroadcastEventCmd).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenLastCalledWith({event:APP_EVENT_SCANNER_RESULT_PROCESSED,parameters:[requestId,true,null]});case 6:case"end":return _context3.stop();}}},_callee3);})));it('should close the scanner when no scan handler was set',/*#__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 instance.scannerDidScanListener({requestId:requestId});case 2:expect(mockedCloseScanner).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenLastCalledWith({event:APP_EVENT_SCANNER_RESULT_PROCESSED,parameters:[requestId,true,null]});case 5:case"end":return _context4.stop();}}},_callee4);})));it('should dispatch a scanner error to the scanner view when the handler throws an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var title,message,handler;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:title='Error Title';message='Message';handler=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:throw new ScanProcessingError(message,title);case 1:case"end":return _context5.stop();}}},_callee5);})));instance.registerScanHandler(handler);_context6.next=6;return instance.scannerDidScanListener({requestId:requestId});case 6:expect(mockedCloseScanner).toHaveBeenCalledTimes(0);expect(mockedBroadcastEventCmd).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenLastCalledWith({event:APP_EVENT_SCANNER_RESULT_PROCESSED,parameters:[requestId,false,{message:message,title:title}]});case 9:case"end":return _context6.stop();}}},_callee6);})));it('should dispatch a scanner error without title to the scanner view when the handler throws an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){var message,handler;return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:message='Message';handler=jest.fn(/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:throw new Error(message);case 1:case"end":return _context7.stop();}}},_callee7);})));instance.registerScanHandler(handler);_context8.next=5;return instance.scannerDidScanListener({requestId:requestId});case 5:expect(mockedCloseScanner).toHaveBeenCalledTimes(0);expect(mockedBroadcastEventCmd).toHaveBeenCalledTimes(1);expect(mockedBroadcastEventCmd).toHaveBeenLastCalledWith({event:APP_EVENT_SCANNER_RESULT_PROCESSED,parameters:[requestId,false,{message:message,title:null}]});case 8:case"end":return _context8.stop();}}},_callee8);})));it('should format the scannerDidScan payload like expected for barcode scans',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var code,format,scanPayload,handler;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:code='4004764315772';format='EAN_13';scanPayload={scannerType:SCANNER_TYPE_BARCODE,requestId:requestId,format:format,code:code};handler=jest.fn();instance.registerScanHandler(handler);_context9.next=7;return instance.scannerDidScanListener(scanPayload);case 7:expect(handler).toHaveBeenCalledTimes(1);expect(handler).toHaveBeenCalledWith({scannerType:SCANNER_TYPE_BARCODE,requestId:requestId,data:{code:code,format:format}});case 9:case"end":return _context9.stop();}}},_callee9);})));it('should format the scannerDidScan payload like expected for image scans',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee10(){var format,imageData,scanPayload,handler;return _regeneratorRuntime.wrap(function _callee10$(_context10){while(1){switch(_context10.prev=_context10.next){case 0:format='jpg';imageData='abc123';scanPayload={scannerType:SCANNER_TYPE_BARCODE,requestId:requestId,imageData:imageData,format:format};handler=jest.fn();instance.registerScanHandler(handler);_context10.next=7;return instance.scannerDidScanListener(scanPayload);case 7:expect(handler).toHaveBeenCalledTimes(1);expect(handler).toHaveBeenCalledWith({scannerType:SCANNER_TYPE_BARCODE,requestId:requestId,data:{imageData:imageData,format:format}});case 9:case"end":return _context10.stop();}}},_callee10);})));});describe('App event handling',function(){describe('closeScanner',function(){it('should work as expected',function(){// Trigger when no listener is present - no close command call.
|
|
6
|
-
event.call(APP_EVENT_CLOSE_SCANNER);instance.openScanner();// Trigger when the listener is present - one close command call.
|
|
7
|
-
event.call(APP_EVENT_CLOSE_SCANNER);// Remove the listener - one close command call.
|
|
8
|
-
instance.closeScanner();// Trigger again without an active listener - no close command call.
|
|
9
|
-
event.call(APP_EVENT_CLOSE_SCANNER);expect(mockedCloseScannerCmd).toHaveBeenCalledTimes(2);});});describe('scannerDidScan',function(){it('should work as expected',function(){var code='4004764315772';var format='EAN_13';var scanPayload={requestId:0,scannerType:SCANNER_TYPE_BARCODE,code:code,format:format};// Trigger when no listener is present - no method call.
|
|
10
|
-
event.call(APP_EVENT_SCANNER_DID_SCAN,[_extends({},scanPayload,{requestId:"".concat(scanPayload.requestId+=1)})]);instance.openScanner();// Trigger when the listener is present - one method call.
|
|
11
|
-
event.call(APP_EVENT_SCANNER_DID_SCAN,[_extends({},scanPayload,{requestId:"".concat(scanPayload.requestId+=1)})]);// Remove the listener.
|
|
12
|
-
instance.closeScanner();// Trigger again without an active listener - no method call.
|
|
13
|
-
event.call(APP_EVENT_SCANNER_DID_SCAN,[_extends({},scanPayload,{requestId:"".concat(scanPayload.requestId+=1)})]);expect(mockedScanHandler).toHaveBeenCalledTimes(1);expect(mockedScanHandler).toHaveBeenCalledWith({scannerType:SCANNER_TYPE_BARCODE,requestId:'2',data:{code:code,format:format}});});});describe('scannerErrorConfirmed',function(){it('should work as expected',function(){// Trigger when no listener is present - no command call.
|
|
14
|
-
event.call(APP_EVENT_SCANNER_ERROR_CONFIRMED);instance.openScanner();// Trigger when the listener is present - one command call.
|
|
15
|
-
event.call(APP_EVENT_SCANNER_ERROR_CONFIRMED);// Remove the listener.
|
|
16
|
-
instance.closeScanner();// Trigger again without an active listener - no command call.
|
|
17
|
-
event.call(APP_EVENT_SCANNER_ERROR_CONFIRMED);expect(mockedStartScannerCmd).toHaveBeenCalledTimes(1);});});});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{getAppPermissions,requestAppPermissions}from"../appPermissions";import{PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA}from"../../constants/AppPermissions";/* eslint-disable import/named */import{mockedSetPermissionIds as mockedGetSetter,mockedDispatch as mockedGetDispatch,mockedPermissionsResponse as mockedGetResponse,triggerDispatchError as triggerGetDispatchError}from"../../classes/AppPermissionsRequest/GetAppPermissionsRequest";import{mockedSetPermissions as mockedRequestSetter,mockedDispatch as mockedRequestDispatch,mockedPermissionsResponse as mockedRequestResponse,triggerDispatchError as triggerRequestDispatchError}from"../../classes/AppPermissionsRequest/RequestAppPermissionsRequest";/* eslint-enable import/named */jest.mock("../../classes/AppPermissionsRequest/GetAppPermissionsRequest");jest.mock("../../classes/AppPermissionsRequest/RequestAppPermissionsRequest");describe('App Permissions commands',function(){beforeEach(function(){jest.clearAllMocks();});describe('getAppPermissions()',function(){var permissionIds=[PERMISSION_ID_LOCATION,PERMISSION_ID_CAMERA];it('should resolve with permissions',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return getAppPermissions(permissionIds);case 2:result=_context.sent;expect(result).toEqual(mockedGetResponse);expect(mockedGetSetter).toHaveBeenCalledTimes(1);expect(mockedGetSetter).toHaveBeenCalledWith(permissionIds);expect(mockedGetDispatch).toHaveBeenCalledTimes(1);case 7:case"end":return _context.stop();}}},_callee);})));it('should resolve with permissions if no ids where passed',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var result;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return getAppPermissions();case 2:result=_context2.sent;expect(result).toEqual(mockedGetResponse);expect(mockedGetSetter).toHaveBeenCalledTimes(1);expect(mockedGetSetter).toHaveBeenCalledWith([]);expect(mockedGetDispatch).toHaveBeenCalledTimes(1);case 7:case"end":return _context2.stop();}}},_callee2);})));it('should reject with an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var message,result;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:message='get W00t';triggerGetDispatchError(message);_context3.prev=2;_context3.next=5;return getAppPermissions(permissionIds);case 5:result=_context3.sent;_context3.next=12;break;case 8:_context3.prev=8;_context3.t0=_context3["catch"](2);expect(_context3.t0).toBeInstanceOf(Error);expect(_context3.t0.message).toEqual(message);case 12:expect(result).toBeUndefined();case 13:case"end":return _context3.stop();}}},_callee3,null,[[2,8]]);})));});describe('requestAppPermissions()',function(){it('should resolve with permissions',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var result;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return requestAppPermissions(mockedRequestResponse);case 2:result=_context4.sent;expect(result).toEqual(mockedRequestResponse);expect(mockedRequestSetter).toHaveBeenCalledTimes(1);expect(mockedRequestSetter).toHaveBeenCalledWith(mockedRequestResponse);expect(mockedRequestDispatch).toHaveBeenCalledTimes(1);case 7:case"end":return _context4.stop();}}},_callee4);})));it('should reject with an error',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var message,result;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:message='request W00t';triggerRequestDispatchError(message);_context5.prev=2;_context5.next=5;return requestAppPermissions(mockedRequestResponse);case 5:result=_context5.sent;_context5.next=12;break;case 8:_context5.prev=8;_context5.t0=_context5["catch"](2);expect(_context5.t0).toBeInstanceOf(Error);expect(_context5.t0.message).toEqual(message);case 12:expect(result).toBeUndefined();case 13:case"end":return _context5.stop();}}},_callee5,null,[[2,8]]);})));});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import{setBrightness,resetBrightness,getCurrentBrightness}from"../brightness";/* eslint-disable import/named */import{mockedSetCommandName,mockedSetCommandParams,mockedSetLibVersion,mockedDispatch}from"../../classes/AppCommand";/* eslint-enable import/named */jest.mock("../../classes/AppCommand");var mockedDispatchRejection=false;var mockedBrightnessRequestDispatch=jest.fn();jest.mock("../../classes/BrightnessRequest",function(){return{dispatch:function dispatch(){mockedBrightnessRequestDispatch();return!mockedDispatchRejection?Promise.resolve(100):Promise.reject(new Error('W00t'));}};});var mockedLoggerError=jest.fn();jest.mock("../../helpers",function(){return{logger:{error:function error(){mockedLoggerError.apply(void 0,arguments);}},hasSGJavaScriptBridge:function hasSGJavaScriptBridge(){return false;}};});describe('Brightness commands',function(){beforeEach(function(){mockedDispatchRejection=false;mockedSetCommandName.mockClear();mockedSetCommandParams.mockClear();mockedSetLibVersion.mockClear();mockedDispatch.mockClear();mockedBrightnessRequestDispatch.mockClear();mockedLoggerError.mockClear();});describe('setBrightness()',function(){it('should set the brightness to 100 if no parameter is passed',function(){setBrightness();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenLastCalledWith('setBrightness');expect(mockedSetCommandParams).toHaveBeenCalledTimes(1);expect(mockedSetCommandParams).toHaveBeenLastCalledWith({brightness:100});expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenLastCalledWith('17.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);});it('should set the brightness to 80',function(){setBrightness(80);expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenLastCalledWith('setBrightness');expect(mockedSetCommandParams).toHaveBeenCalledTimes(1);expect(mockedSetCommandParams).toHaveBeenLastCalledWith({brightness:80});expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenLastCalledWith('17.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);});});describe('resetBrightness()',function(){it('should work as expected',function(){resetBrightness();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenLastCalledWith('resetBrightness');expect(mockedSetCommandParams).toHaveBeenCalledTimes(0);expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenLastCalledWith('17.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);});});describe('getCurrentBrightness()',function(){it('should resolve with a number',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var brightness;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return getCurrentBrightness();case 2:brightness=_context.sent;expect(brightness).toBe(100);expect(mockedBrightnessRequestDispatch).toHaveBeenCalledTimes(1);case 5:case"end":return _context.stop();}}},_callee);})));it('should handle error situations',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var brightness;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:mockedDispatchRejection=true;_context2.prev=1;_context2.next=4;return getCurrentBrightness();case 4:brightness=_context2.sent;_context2.next=13;break;case 7:_context2.prev=7;_context2.t0=_context2["catch"](1);expect(mockedLoggerError).toHaveBeenCalledTimes(1);expect(_context2.t0).toBeInstanceOf(Error);expect(_context2.t0.message).toContain('W00t');expect(mockedBrightnessRequestDispatch).toHaveBeenCalledTimes(1);case 13:expect(brightness).toBeUndefined();case 14:case"end":return _context2.stop();}}},_callee2,null,[[1,7]]);})));});});
|
|
@@ -1,7 +0,0 @@
|
|
|
1
|
-
/* eslint-disable import/named */import{mockedSetCommandName,mockedSetCommandParams,mockedBuildCommand,mockedDispatch}from"../../classes/AppCommand";/* eslint-enable import/named */import closeInAppBrowser from"../closeInAppBrowser";jest.mock("../../classes/AppCommand");jest.mock("../../helpers",function(){return{hasSGJavaScriptBridge:function hasSGJavaScriptBridge(){return true;}};});describe('closeInAppBrowser command',function(){beforeEach(function(){jest.clearAllMocks();});/**
|
|
2
|
-
* The default test for a command parameter which is not set, or set to false.
|
|
3
|
-
* @param {boolean} isAndroid The parameter value for the command.
|
|
4
|
-
* @param {string} delayedCommand The name of the delayed command.
|
|
5
|
-
*/var execTest=function execTest(isAndroid,delayedCommand){var expectedDelayedCommand={c:delayedCommand,p:{targetTab:'in_app_browser'}};var actualDelayedCommand;mockedBuildCommand.mockImplementationOnce(function(command){// Intercept the command assignment.
|
|
6
|
-
actualDelayedCommand=command;return command;});closeInAppBrowser(isAndroid);// Check if the correct commands where dispatched.
|
|
7
|
-
expect(mockedSetCommandName).toHaveBeenCalledTimes(3);expect(mockedSetCommandName).toHaveBeenCalledWith(delayedCommand);expect(mockedSetCommandName).toHaveBeenCalledWith('performCommandsAfterDelay');expect(mockedSetCommandName).toHaveBeenCalledWith('showTab');expect(mockedBuildCommand).toHaveBeenCalledTimes(1);expect(actualDelayedCommand).toEqual(expectedDelayedCommand);expect(mockedSetCommandParams).toHaveBeenCalledWith({cmds:[expectedDelayedCommand],delay:expect.any(Number)});expect(mockedDispatch).toHaveBeenCalledTimes(2);};it('should dispatch the commands as expected without any params',function(){execTest(undefined,'popTabToRoot');});it('should dispatch the commands as expected when params is set to false',function(){execTest(false,'popTabToRoot');});it('should dispatch the commands as expected when params is set to true',function(){execTest(true,'cleanTab');});});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
// eslint-disable-next-line import/named
|
|
2
|
-
import{mockedSetCommandName,mockedSetCommandParams,mockedDispatch}from"../../classes/AppCommand";import openAppSettings from"../openAppSettings";jest.mock("../../classes/AppCommand");describe('openAppSettings command',function(){beforeEach(function(){jest.clearAllMocks();});it('should dispatch',function(){openAppSettings();expect(mockedSetCommandName).toHaveBeenCalledWith('openAppSettings');expect(mockedSetCommandParams).not.toHaveBeenCalled();expect(mockedDispatch).toHaveBeenCalledWith(undefined);});});
|
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{plotProjectsEnable,plotProjectsDisable,plotProjectsSetSegmentationProperties}from"../plotProjects";/* eslint-disable import/named */import{mockedSetCommandName,mockedSetLibVersion,mockedDispatch,mockedSetCommandParams}from"../../classes/AppCommand";import{logger}from"../../helpers";/* eslint-enable import/named */jest.mock("../../classes/AppCommand");jest.mock("../../helpers",function(){return{logger:{error:jest.fn()}};});describe('plotprojects commands',function(){beforeEach(function(){jest.clearAllMocks();});describe('plotProjectsEnable()',function(){it('should dispatch the correct command',function(){var token='foo123';plotProjectsEnable(token);expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('plotProjectsEnable');expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenCalledWith('18.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedDispatch).toHaveBeenCalledWith({publicToken:token});});});describe('plotProjectsDisable()',function(){it('should dispatch the correct command',function(){plotProjectsDisable();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('plotProjectsDisable');expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenCalledWith('18.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);});});describe('plotProjectsSetSegmentationProperties()',function(){it('should dispatch the correct command',function(){var inputProperties=[// valid
|
|
2
|
-
{key:'key1',type:'string',value:'value1'},{key:'key2',type:'integer',value:123},{key:'key3',type:'string',value:null},{key:'key3',type:'string'},// invalid
|
|
3
|
-
{key:'key3',type:null},{key:'key4'},{key:'key5',value:null},{key:1,type:'integer',value:123},{type:'integer',value:123},{key:'111111111111111111111111111111111111111111111111111111111111111111111111',type:'string',value:'foo'},{key:'key6',type:'string',value:'111111111111111111111111111111111111111111111111111111111111111111111111'}];var expected={properties:[{key:'key1',type:'string',value:'value1'},{key:'key2',type:'integer',value:123},{key:'key3',type:'string',value:null},{key:'key3',type:'string'}]};plotProjectsSetSegmentationProperties(inputProperties);expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('plotProjectsSetSegmentationProperties');expect(mockedSetCommandParams).toHaveBeenCalledTimes(1);expect(mockedSetCommandParams).toHaveBeenCalledWith(expected);expect(mockedSetLibVersion).toHaveBeenCalledTimes(1);expect(mockedSetLibVersion).toHaveBeenCalledWith('25.0');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(logger.error).toHaveBeenCalledTimes(7);});});});
|
|
@@ -1,2 +0,0 @@
|
|
|
1
|
-
function _defineProperty(obj,key,value){if(key in obj){Object.defineProperty(obj,key,{value:value,enumerable:true,configurable:true,writable:true});}else{obj[key]=value;}return obj;}import{PWA_DEFAULT_TAB}from"../../constants/Command";import*as constants from"../../constants/Scanner";// eslint-disable-next-line import/named
|
|
2
|
-
import{mockedSetCommandName,mockedDispatch}from"../../classes/AppCommand";import*as commands from"../scanner";jest.mock("../../classes/AppCommand");describe('scanner commands',function(){beforeEach(function(){jest.clearAllMocks();});describe('openScanner()',function(){it('should work as expected',function(){var _modes;var expected={src:'sgapi:scanner',modes:(_modes={},_defineProperty(_modes,constants.SCANNER_TYPE_BARCODE,constants.SCANNER_MODE_OFF),_defineProperty(_modes,constants.SCANNER_TYPE_CARD,constants.SCANNER_MODE_OFF),_defineProperty(_modes,constants.SCANNER_TYPE_IMAGE,constants.SCANNER_MODE_OFF),_modes),animation:constants.SCANNER_ANIMATION_FOREGROUND_BOTTOM,eventParams:{scannerData:{modes:{barcodeRecognition:false,cardRecognition:false,imageCapturing:false}},sourceTab:PWA_DEFAULT_TAB}};commands.openScanner();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('openScanner');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedDispatch).toHaveBeenCalledWith(expected);});it('should merge passed parameters properly',function(){var _modes2,_modes3;var expected={src:'sgapi:scanner',modes:(_modes2={},_defineProperty(_modes2,constants.SCANNER_TYPE_BARCODE,constants.SCANNER_MODE_OFF),_defineProperty(_modes2,constants.SCANNER_TYPE_IMAGE,constants.SCANNER_MODE_ON),_defineProperty(_modes2,constants.SCANNER_TYPE_CARD,constants.SCANNER_MODE_OFF),_modes2),animation:constants.SCANNER_ANIMATION_FOREGROUND_BOTTOM,eventParams:{scannerData:{modes:(_modes3={},_defineProperty(_modes3,constants.SCANNER_TYPE_BARCODE,false),_defineProperty(_modes3,constants.SCANNER_TYPE_IMAGE,true),_defineProperty(_modes3,constants.SCANNER_TYPE_CARD,false),_modes3)},sourceTab:PWA_DEFAULT_TAB}};commands.openScanner({modes:{imageCapturing:constants.SCANNER_MODE_ON}});expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedDispatch).toHaveBeenCalledWith(expected);});});describe('closeScanner()',function(){it('should work as expected',function(){var expected={animation:constants.SCANNER_ANIMATION_FOREGROUND_BOTTOM};commands.closeScanner();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('closeScanner');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedDispatch).toHaveBeenCalledWith(expected);});it('should merge passed parameters properly',function(){var expected={animation:constants.SCANNER_ANIMATION_FOREGROUND_LEFT};commands.closeScanner({animation:constants.SCANNER_ANIMATION_FOREGROUND_LEFT});expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('closeScanner');expect(mockedDispatch).toHaveBeenCalledTimes(1);expect(mockedDispatch).toHaveBeenCalledWith(expected);});});describe('startScanner()',function(){it('should work as expected',function(){commands.startScanner();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('startScanner');expect(mockedDispatch).toHaveBeenCalledTimes(1);});});describe('stopScanner()',function(){it('should work as expected',function(){commands.stopScanner();expect(mockedSetCommandName).toHaveBeenCalledTimes(1);expect(mockedSetCommandName).toHaveBeenCalledWith('stopScanner');expect(mockedDispatch).toHaveBeenCalledTimes(1);});});});
|
package/helpers/version.spec.js
DELETED
|
@@ -1,6 +0,0 @@
|
|
|
1
|
-
import _regeneratorRuntime from"@babel/runtime/regenerator";function asyncGeneratorStep(gen,resolve,reject,_next,_throw,key,arg){try{var info=gen[key](arg);var value=info.value;}catch(error){reject(error);return;}if(info.done){resolve(value);}else{Promise.resolve(value).then(_next,_throw);}}function _asyncToGenerator(fn){return function(){var self=this,args=arguments;return new Promise(function(resolve,reject){var gen=fn.apply(self,args);function _next(value){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"next",value);}function _throw(err){asyncGeneratorStep(gen,resolve,reject,_next,_throw,"throw",err);}_next(undefined);});};}import getWebStorageEntry from"../commands/getWebStorageEntry";import{isValidVersion,isVersionAtLeast,isVersionAtMost,isVersion,isLibVersionAtLeast,isLibVersionAtMost,isLibVersion,clearVersionCache,defaultClientInformation}from"./version";import{hasSGJavaScriptBridge}from"./index";var mockedClientInformation=null;var mockedWebStorageResponse=jest.fn();jest.mock("../commands/getWebStorageEntry",function(){return jest.fn().mockImplementation(function(){return{then:function then(cb){mockedWebStorageResponse();cb({value:mockedClientInformation});}};});});var mockedErrorLogger=jest.fn();jest.mock("./index",function(){return{logger:{error:function error(){mockedErrorLogger.apply(void 0,arguments);}},hasSGJavaScriptBridge:jest.fn().mockReturnValue(true)};});/**
|
|
2
|
-
* Updates the mocked client information.
|
|
3
|
-
* @param {string} platform The platform.
|
|
4
|
-
* @param {string} libVersion The libVersion.
|
|
5
|
-
* @param {string} appVersion The appVersion.
|
|
6
|
-
*/var setClientInformation=function setClientInformation(){var platform=arguments.length>0&&arguments[0]!==undefined?arguments[0]:'ios';var libVersion=arguments.length>1&&arguments[1]!==undefined?arguments[1]:'15.0';var appVersion=arguments.length>2&&arguments[2]!==undefined?arguments[2]:'10.18';mockedClientInformation={libVersion:libVersion,appVersion:appVersion,device:{os:{platform:platform}}};};describe('Version helper',function(){beforeEach(function(){jest.clearAllMocks();mockedWebStorageResponse.mockClear();setClientInformation();clearVersionCache();});describe('isValidVersion()',function(){var positives=['16','16.0','16.0.0','16.1','16.1.1'];var negatives=[16,'16.a.1','16.1.a','foo',null,{},[]];positives.forEach(function(value){it("should return true for ".concat(value),function(){expect(isValidVersion(value)).toBe(true);});});negatives.forEach(function(value){it("should return false for ".concat(value),function(){expect(isValidVersion(value)).toBe(false);});});});describe('isVersionAtLeast()',function(){var positives=[['17','17'],['17','17.0'],['17','17.0.0'],['17','17.0.1'],['17','18'],['17.0','17'],['17.1','17.1'],['17.1','17.2'],['17.1.1','17.1.1'],['17.1.1','17.1.2']];var negatives=[['17','16'],['17.1','17.0'],['17.1','17.0.9'],['17.1.0','17.0.1'],['17.1.1','17.1.0'],[]];positives.forEach(function(value){it("should return true for ".concat(value.join(' <= ')),function(){expect(isVersionAtLeast(value[0],value[1])).toBe(true);});});negatives.forEach(function(value){it("should return false for ".concat(value.join(' <= ')),function(){expect(isVersionAtLeast(value[0],value[1])).toBe(false);});});});describe('isVersionAtMost()',function(){var positives=[['17','17'],['17','16'],['17','17.0'],['17.0','17'],['17.1','17.0'],['17.1','17.1'],['17.1','17.0.9'],['17.1.1','17.1.1'],['17.1.0','17.0.1'],['17.1.1','17.1.0']];var negatives=[['17','18'],['17','17.1'],['17.1','17.2'],['17.1','17.1.1'],['17.1.1','17.1.2']];positives.forEach(function(value){it("should return true for ".concat(value.join(' >= ')),function(){expect(isVersionAtMost(value[0],value[1])).toBe(true);});});negatives.forEach(function(value){it("should return false for ".concat(value.join(' >= ')),function(){expect(isVersionAtMost(value[0],value[1])).toBe(false);});});});describe('isVersion()',function(){var positives=[['17','17'],['17','17.0'],['17','17.0.0'],['17.0','17'],['17.0','17.0'],['17.0','17.0.0'],['17.0.0','17'],['17.0.0','17.0'],['17.0.0','17.0.0']];var negatives=[['17','16'],['17.1','17.0'],['17.1','17.0.1'],['17.0.1','17'],['17.0.1','17.1'],['17.0.1','17.1.2']];positives.forEach(function(value){it("should return true for ".concat(value.join(' == ')),function(){expect(isVersion(value[0],value[1])).toBe(true);});});negatives.forEach(function(value){it("should return false for ".concat(value.join(' >= ')),function(){expect(isVersion(value[0],value[1])).toBe(false);});});});describe('error handling and logging',function(){beforeEach(function(){mockedErrorLogger.mockClear();});var invalids=['a','1.a','a.b.c','0.1.c','foobar',''];invalids.forEach(function(value){it("should log an error and return false for \"".concat(value,"\""),function(){expect(isVersion(value,'17.5.2')).toBe(false);expect(mockedErrorLogger).toHaveBeenCalledTimes(1);});});});describe('isLibVersionAtLeast()',function(){it('should return true for a value lower than the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee(){var result;return _regeneratorRuntime.wrap(function _callee$(_context){while(1){switch(_context.prev=_context.next){case 0:_context.next=2;return isLibVersionAtLeast('14.1.2');case 2:result=_context.sent;expect(result).toBe(true);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context.stop();}}},_callee);})));it('should return false for a value greater than the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee2(){var result;return _regeneratorRuntime.wrap(function _callee2$(_context2){while(1){switch(_context2.prev=_context2.next){case 0:_context2.next=2;return isLibVersionAtLeast('15.1.2');case 2:result=_context2.sent;expect(result).toBe(false);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context2.stop();}}},_callee2);})));});describe('isLibVersionAtMost()',function(){it('should return true for a value lower than the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee3(){var result;return _regeneratorRuntime.wrap(function _callee3$(_context3){while(1){switch(_context3.prev=_context3.next){case 0:_context3.next=2;return isLibVersionAtMost('15.1.2');case 2:result=_context3.sent;expect(result).toBe(true);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context3.stop();}}},_callee3);})));it('should return false for a value greater than the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee4(){var result;return _regeneratorRuntime.wrap(function _callee4$(_context4){while(1){switch(_context4.prev=_context4.next){case 0:_context4.next=2;return isLibVersionAtMost('14.1.2');case 2:result=_context4.sent;expect(result).toBe(false);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context4.stop();}}},_callee4);})));});describe('isLibVersion()',function(){it('should return true for a value which does match the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee5(){var result;return _regeneratorRuntime.wrap(function _callee5$(_context5){while(1){switch(_context5.prev=_context5.next){case 0:_context5.next=2;return isLibVersion('15.0.0');case 2:result=_context5.sent;expect(result).toBe(true);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context5.stop();}}},_callee5);})));it('should return false for a value does not match the lib version',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee6(){var result;return _regeneratorRuntime.wrap(function _callee6$(_context6){while(1){switch(_context6.prev=_context6.next){case 0:_context6.next=2;return isLibVersion('14.1.2');case 2:result=_context6.sent;expect(result).toBe(false);expect(getWebStorageEntry).toHaveBeenCalledTimes(1);case 5:case"end":return _context6.stop();}}},_callee6);})));it('should use the default client information when no SGJavaScriptBridge is available',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee7(){var result;return _regeneratorRuntime.wrap(function _callee7$(_context7){while(1){switch(_context7.prev=_context7.next){case 0:hasSGJavaScriptBridge.mockReturnValueOnce(false);_context7.next=3;return isLibVersion(defaultClientInformation.libVersion);case 3:result=_context7.sent;expect(result).toBe(true);expect(getWebStorageEntry).not.toHaveBeenCalled();case 6:case"end":return _context7.stop();}}},_callee7);})));});describe('clearVersionCache()',function(){it('should work as expected',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee8(){return _regeneratorRuntime.wrap(function _callee8$(_context8){while(1){switch(_context8.prev=_context8.next){case 0:clearVersionCache();_context8.next=3;return isLibVersion('15.0.0');case 3:_context8.next=5;return isLibVersion('15.0.0');case 5:expect(mockedWebStorageResponse).toHaveBeenCalledTimes(1);clearVersionCache();_context8.next=9;return isLibVersion('15.0.0');case 9:expect(mockedWebStorageResponse).toHaveBeenCalledTimes(2);case 10:case"end":return _context8.stop();}}},_callee8);})));});describe('request handling',function(){it('should only request once for multiple parallel calls',/*#__PURE__*/_asyncToGenerator(/*#__PURE__*/_regeneratorRuntime.mark(function _callee9(){var result;return _regeneratorRuntime.wrap(function _callee9$(_context9){while(1){switch(_context9.prev=_context9.next){case 0:isLibVersion('15.0.0');isLibVersion('15.0.0');_context9.next=4;return isLibVersion('15.0.0');case 4:result=_context9.sent;expect(result).toBe(true);case 6:case"end":return _context9.stop();}}},_callee9);})));});});
|