@shopgate/tracking-core 6.21.0 → 6.22.0-beta.10
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/CHANGELOG.md +46 -0
- package/package.json +3 -3
- package/helpers/formatHelpers.spec.js +0 -1
- package/helpers/helpers.spec.js +0 -3
- package/plugins/Base.spec.js +0 -1
- package/tests/AppHandlerTest.js +0 -19
- package/tests/CoreTest.js +0 -66
- package/tests/FbPixelTest.js +0 -13
- package/tests/GaBaseTest.js +0 -47
- package/tests/UnifiedTest.js +0 -5
- package/tests/data/tracking.expectedData.js +0 -1
- package/tests/data/tracking.testData.js +0 -1
- package/tests/helperTest.js +0 -14
- package/tests/helpers/localStorage-mock.js +0 -4
- package/tests/helpers/triggerTrackingCoreEvents.js +0 -25
- package/tests/urlMappingTest.js +0 -5
package/CHANGELOG.md
ADDED
|
@@ -0,0 +1,46 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
---
|
|
3
|
+
### 1.0.9 - January 24, 2018
|
|
4
|
+
- Updated `@shopgate/pwa-core` peer dependency
|
|
5
|
+
|
|
6
|
+
---
|
|
7
|
+
|
|
8
|
+
### 1.0.8 - December 28, 2017
|
|
9
|
+
|
|
10
|
+
#### Changed
|
|
11
|
+
- Updated `@shopgate/pwa-core` peer dependency
|
|
12
|
+
|
|
13
|
+
---
|
|
14
|
+
|
|
15
|
+
### 1.0.7 - December 22, 2017
|
|
16
|
+
|
|
17
|
+
#### Changed
|
|
18
|
+
- Updated `@shopgate/pwa-core` to ^1.1.0
|
|
19
|
+
|
|
20
|
+
---
|
|
21
|
+
|
|
22
|
+
### 1.0.6 - December 22, 2017
|
|
23
|
+
|
|
24
|
+
#### Changed
|
|
25
|
+
- Updated `@shopgate/eslint-config` to ^1.0.3
|
|
26
|
+
|
|
27
|
+
---
|
|
28
|
+
|
|
29
|
+
### 1.0.5 - December 21, 2017
|
|
30
|
+
|
|
31
|
+
#### Changed
|
|
32
|
+
- Updated `@shopgate/pwa-core` to ^1.0.5
|
|
33
|
+
|
|
34
|
+
---
|
|
35
|
+
|
|
36
|
+
### 1.0.3 - December 11, 2017
|
|
37
|
+
|
|
38
|
+
#### Changed
|
|
39
|
+
- Updated `@shopgate/pwa-core` to ^1.0.4
|
|
40
|
+
|
|
41
|
+
---
|
|
42
|
+
|
|
43
|
+
### 1.0.2 - December 11, 2017
|
|
44
|
+
|
|
45
|
+
#### Changed
|
|
46
|
+
- Updated `@shopgate/pwa-core` to ^1.0.3
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shopgate/tracking-core",
|
|
3
|
-
"version": "6.
|
|
3
|
+
"version": "6.22.0-beta.10",
|
|
4
4
|
"description": "Tracking core library for the Shopgate Connect PWA.",
|
|
5
5
|
"author": "Shopgate <support@shopgate.com>",
|
|
6
6
|
"license": "Apache-2.0",
|
|
@@ -16,8 +16,8 @@
|
|
|
16
16
|
"connect"
|
|
17
17
|
],
|
|
18
18
|
"devDependencies": {
|
|
19
|
-
"@shopgate/eslint-config": "6.
|
|
20
|
-
"@shopgate/pwa-core": "6.
|
|
19
|
+
"@shopgate/eslint-config": "6.22.0-beta.10",
|
|
20
|
+
"@shopgate/pwa-core": "6.22.0-beta.10",
|
|
21
21
|
"chai": "^3.5.0",
|
|
22
22
|
"jsdom": "11.1.0",
|
|
23
23
|
"mocha": "^3.1.0",
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var _excluded=["quantity","brand"];function _objectWithoutProperties(source,excluded){if(source==null)return{};var target=_objectWithoutPropertiesLoose(source,excluded);var key,i;if(Object.getOwnPropertySymbols){var sourceSymbolKeys=Object.getOwnPropertySymbols(source);for(i=0;i<sourceSymbolKeys.length;i++){key=sourceSymbolKeys[i];if(excluded.indexOf(key)>=0)continue;if(!Object.prototype.propertyIsEnumerable.call(source,key))continue;target[key]=source[key];}}return target;}function _objectWithoutPropertiesLoose(source,excluded){if(source==null)return{};var target={};var sourceKeys=Object.keys(source);var key,i;for(i=0;i<sourceKeys.length;i++){key=sourceKeys[i];if(excluded.indexOf(key)>=0)continue;target[key]=source[key];}return target;}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{sgDataProduct,sgDataSearch,sgDataCategoryAll}from"../tests/data/tracking.testData";import helpers from"./formatHelpers";var smartbanner=helpers.smartbanner,purchase=helpers.purchase,pageview=helpers.pageview,viewContent=helpers.viewContent,addToCart=helpers.addToCart,addToWishlist=helpers.addToWishlist,initiatedCheckout=helpers.initiatedCheckout,completedRegistration=helpers.completedRegistration,search=helpers.search,addedPaymentInfo=helpers.addedPaymentInfo,selectedPaymentInfo=helpers.selectedPaymentInfo,itemView=helpers.itemView;var mockBaseProduct={uid:'base-product',name:'Product name',manufacturer:'Product manufacturer',quantity:3,tags:[],amount:{currency:'EUR',gross:'100.99',net:'90.99',striked:'0.00'}};var mockMockVariantProduct=_extends({},mockBaseProduct,{uid:'variant-product'});var expectedProduct={id:mockBaseProduct.uid,name:mockBaseProduct.name,brand:mockBaseProduct.manufacturer,type:'product',priceNet:parseFloat(mockBaseProduct.amount.net),priceGross:parseFloat(mockBaseProduct.amount.gross),quantity:mockBaseProduct.quantity,currency:mockBaseProduct.amount.currency};describe('Format helpers',function(){describe('custom events',function(){it('should format event data for the smartbanner event',function(){var raw={eventCategory:'',eventAction:'',eventLabel:null,eventValue:null,nonInteraction:false};expect(smartbanner(raw)).toEqual(raw);});});describe('purchase()',function(){it('should format event data',function(){var raw={order:{number:'123',amount:{gross:'10.00',net:'11.05',tax:'6.50',currency:'EUR'},shipping:{amount:{gross:'1.00',net:'0.87'}},products:[mockBaseProduct]},shop:{name:'testshop'}};expect(purchase(raw)).toEqual({id:raw.order.number,type:'product',affiliation:raw.shop.name,revenueGross:parseFloat(raw.order.amount.gross),revenueNet:parseFloat(raw.order.amount.net),tax:parseFloat(raw.order.amount.tax),shippingGross:parseFloat(raw.order.shipping.amount.gross),shippingNet:parseFloat(raw.order.shipping.amount.net),currency:raw.order.amount.currency,items:[expectedProduct]});});});describe('pageview()',function(){it('should format event data',function(){var raw={page:{link:'http://m.atu.de/item/1234'}};expect(pageview(raw)).toEqual({page:{merchantUrl:'item/1234',shopgateUrl:'item'}});});});describe('viewContent()',function(){it('should format event data for an item route',function(){var raw=_extends({},sgDataProduct);var expected={id:sgDataProduct.product.productNumber,name:sgDataProduct.product.name,type:'product'};expect(viewContent(raw)).toEqual(expected);raw.page.link="https://rapid.shopgate.com/sg_app_resources/10006/item/".concat(sgDataProduct.product.productNumber);expect(viewContent(raw)).toEqual(expected);});it('should format event data for an category/all route',function(){expect(viewContent(sgDataCategoryAll)).toEqual({id:"".concat(sgDataCategoryAll.category.uid,"/all"),name:sgDataCategoryAll.category.name,type:'category'});});it('should format event data for a search route',function(){expect(viewContent(sgDataSearch)).toEqual({id:sgDataSearch.search.query,name:sgDataSearch.page.title.substring(0,sgDataSearch.page.title.indexOf(':')).trim(),type:sgDataSearch.page.name});});it('should format event data for a reviews route',function(){var raw={page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/item/5347313134',name:'reviews',link:'http://testshop.schneider.localdev.cc/php/shopgate/reviews/5347313134',title:'Reviews - Product with manufacturer - Shopgate Testshop'}};expect(viewContent(raw)).toEqual({id:'SG114',name:'Reviews - Product with manufacturer - Shopgate Testshop',type:'reviews'});});it('should format event data for a payment_success route',function(){var raw={page:{referrer:'',name:'success',link:'http://testshop.schneider.localdev.cc/php/shopgate/payment_success/5347313134',title:'Checkout success'}};expect(viewContent(raw)).toEqual({id:'5347313134',name:'Checkout success',type:'checkout_success'});});});describe('addToCart',function(){it('should format event data',function(){var raw={products:[mockBaseProduct]};expect(addToCart(raw)).toEqual({type:'product',items:[expectedProduct]});});});describe('addToWishlist()',function(){it('should format event data',function(){var raw={favouriteListProducts:[_extends({},mockBaseProduct,{currency_id:'EUR',unit_amount_net:(mockBaseProduct.amount.net*100).toString(),unit_amount_with_tax:(mockBaseProduct.amount.gross*100).toString()})]};var quantity=expectedProduct.quantity,brand=expectedProduct.brand,expectedItems=_objectWithoutProperties(expectedProduct,_excluded);expect(addToWishlist(raw)).toEqual({type:'product',items:[expectedItems]});});});describe('initiatedCheckout()',function(){it('should format event data',function(){var raw={checkoutType:'express',product:{amount:{net:'100.00',gross:'110.50',currency:'EUR'}},quantity:16};expect(initiatedCheckout(raw)).toEqual({type:raw.checkoutType,valueNet:parseFloat(raw.product.amount.net),valueGross:parseFloat(raw.product.amount.gross),numItems:raw.quantity,currency:raw.product.amount.currency,paymentInfoAvailable:raw.checkoutType!=='default'});});});describe('completedRegistration()',function(){it('should format event data',function(){var raw={registrationType:'guest'};expect(completedRegistration(raw)).toEqual({registrationMethod:raw.registrationType});});});describe('search()',function(){it('should format event data',function(){var raw={search:{resultCount:356,query:'black shoes'}};expect(search(raw)).toEqual({type:'product',query:raw.search.query,hits:raw.search.resultCount,success:!!raw.search.resultCount});});});describe('itemView()',function(){it('should format raw base product data',function(){var raw={product:mockBaseProduct};expect(itemView(raw)).toEqual({id:'base-product',type:'',name:'Product name',priceNet:90.99,priceGross:100.99,currency:'EUR',brand:'Product manufacturer'});});it('should format raw variant product data',function(){var raw={baseProduct:mockBaseProduct,variant:mockMockVariantProduct};expect(itemView(raw)).toEqual({id:'variant-product',type:'',name:'Product name',priceNet:90.99,priceGross:100.99,currency:'EUR',brand:'Product manufacturer'});});});describe('addedPaymentInfo()',function(){it('should format event data',function(){var raw={paymentMethodAdded:{success:true,name:'credit card'}};expect(addedPaymentInfo(raw)).toEqual({success:raw.paymentMethodAdded.success,name:raw.paymentMethodAdded.name});});});describe('selectedPaymentInfo()',function(){it('should format tracking data',function(){var raw={paymentMethodSelected:{success:true,name:'Payment method'}};expect(selectedPaymentInfo(raw)).toEqual({success:raw.paymentMethodSelected.success,name:raw.paymentMethodSelected.name});});});});
|
package/helpers/helpers.spec.js
DELETED
|
@@ -1,3 +0,0 @@
|
|
|
1
|
-
import{SGLink}from"./helper";describe('Helpers',function(){var sgLink;beforeEach(function(){sgLink=new SGLink('/home');});describe('setUtmParams',function(){it('should set source and medium',function(){sgLink.setUtmParams({},{type:'raw'});expect(sgLink.toString()).toEqual('/home?utm_source=shopgate&utm_medium=raw');});it('should set utm campaign push message',function(){// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
2
|
-
sgLink.setUtmParams({},{type:'push_message',notificationId:101});expect(sgLink.toString()).toEqual('/home?utm_source=shopgate&utm_medium=push_message&utm_campaign=push-101');});it('should set utm content push message',function(){sgLink=new SGLink('/home?utm_campaign=cart_reminder');// eslint-disable-next-line extra-rules/no-single-line-objects
|
|
3
|
-
sgLink.setUtmParams({},{type:'push_message',notificationId:101});expect(sgLink.toString()).toEqual('/home?utm_campaign=push-101&utm_source=shopgate&utm_medium=push_message&utm_content=cart_reminder');});});});
|
package/plugins/Base.spec.js
DELETED
|
@@ -1 +0,0 @@
|
|
|
1
|
-
import SgTrackingPlugin from"./Base";describe('Base',function(){var instance;beforeEach(function(){instance=new SgTrackingPlugin();});describe('.disableTracking() / .enableTracking()',function(){it('should disable and enable the tracking',function(){expect(instance.trackingDisabled).toBe(false);instance.disableTracking();expect(instance.trackingDisabled).toBe(true);instance.enableTracking();expect(instance.trackingDisabled).toBe(false);});});describe('.formatData()',function(){it('should return the input data when no formatter is available',function(){var raw={some:'property'};expect(SgTrackingPlugin.formatData('someEvent',raw)).toBe(raw);});it('should return formatted data for a known event',function(){var raw={page:{link:'http://m.atu.de/item/1234'}};expect(SgTrackingPlugin.formatData('pageview',raw)).toEqual({page:{merchantUrl:'item/1234',shopgateUrl:'item'}});});});});
|
package/tests/AppHandlerTest.js
DELETED
|
@@ -1,19 +0,0 @@
|
|
|
1
|
-
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}/* eslint global-require: "off" */import Chai from'chai';import sinon from'sinon';import sinonChai from'sinon-chai';import mochaJsdom from'mocha-jsdom';var chai=Chai.use(sinonChai);var expect=chai.expect;describe('AppHandler',function(){var appHandler;var SGAction;mochaJsdom();before(function(){global.console.groupCollapsed=function(){};global.console.groupEnd=function(){};window.SGEvent={};appHandler=require("../core/AppHandler")["default"];// eslint-disable-next-line prefer-destructuring
|
|
2
|
-
SGAction=require("../helpers/helper").SGAction;});/**
|
|
3
|
-
* Restrictions object for all tests
|
|
4
|
-
* @type {{blacklist: boolean, trackers: string[]}}
|
|
5
|
-
*/var restrictions={blacklist:true,trackers:['fb']};/**
|
|
6
|
-
* We can use dummy data here, because we only test the adding of the restrictions
|
|
7
|
-
* @type {{foo: string, test: string}}
|
|
8
|
-
*/var dummyData={foo:'bar',test:'test'};/**
|
|
9
|
-
* Events that should be tested
|
|
10
|
-
* @type {[{SGAction: String, event: String}]}
|
|
11
|
-
*/var events=[{SGAction:'analyticsSetCampaignWithUrl',event:'setCampaignWithUrl'},{SGAction:'analyticsLogPageview',event:'viewContent'},{SGAction:'analyticsLogPurchase',event:'purchase'},{SGAction:'analyticsLogAddToCart',event:'addToCart'},{SGAction:'analyticsLogAddedPaymentInfo',event:'addedPaymentInfo'},{SGAction:'analyticsLogInitiatedCheckout',event:'initiatedCheckout'},{SGAction:'analyticsLogCompletedRegistration',event:'completedRegistration'},{SGAction:'analyticsLogAddToWishlist',event:'addToWishlist'},{SGAction:'analyticsLogSearch',event:'search'}];/**
|
|
12
|
-
* Helper function to create a spy for a function
|
|
13
|
-
* @param {string} name Name of the function in SGAction
|
|
14
|
-
* @returns {Object} spy for the given function
|
|
15
|
-
*/var getSpy=function getSpy(name){return sinon.spy(SGAction,name);};/**
|
|
16
|
-
* Helper function to check if the spy gets called with the correct data
|
|
17
|
-
* @param {Object} spy Spy object
|
|
18
|
-
* @param {*} args Arguments which the spy should called with
|
|
19
|
-
*/var checkSpy=function checkSpy(spy,args){expect(spy).to.have.been.calledWith(args);spy.restore();};it('should send events and add restrictions',function(){events.forEach(function(event){var spy=getSpy(event.SGAction);appHandler[event.event](dummyData,restrictions);checkSpy(spy,_extends({},dummyData,{restrictions:restrictions}));});});});
|
package/tests/CoreTest.js
DELETED
|
@@ -1,66 +0,0 @@
|
|
|
1
|
-
/* eslint global-require: "off" */ /* eslint no-unused-expressions: "off" */import chai from'chai';import sinon from'sinon';import sinonChai from'sinon-chai';import mochaJsdom from'mocha-jsdom';import storageMock from"./helpers/localStorage-mock";import{sgData}from"./data/tracking.testData";var expect=chai.expect;describe('Core',function(){var SgTrackingCore=null;var trackableEvents=['setCampaignWithUrl','pageview','viewContent','variantSelected','purchase','addToCart','addToWishlist','initiatedCheckout','completedRegistration','search','addedPaymentInfo','smartbanner','qrScanner','adScanner','ccScanner','filterLiveSuggest','scrollTop','openDeepLink','openUniversalLink','openDeferredDeepLink','openSmartAppDownloadLink','openPushNotification','appReviewPrompt','loginSuccess','loginFailed'];// Initializes fake DOM
|
|
2
|
-
mochaJsdom();// Initializes sinon to be used with chai
|
|
3
|
-
chai.use(sinonChai);/**
|
|
4
|
-
* Load legacy dependencies
|
|
5
|
-
* and prepare coming tests
|
|
6
|
-
*/before(function(){// Set globals for legacy code
|
|
7
|
-
global.localStorage=storageMock();});/**
|
|
8
|
-
* Before running a test clean up globals
|
|
9
|
-
*/beforeEach(function(){// Reinitialize to provide a clean core for each test
|
|
10
|
-
SgTrackingCore=require("../core/Core")["default"].reset().registerFinished();// Provide clean local storage
|
|
11
|
-
global.localStorage=storageMock();});/**
|
|
12
|
-
* Makes sure that all events that can be called are also registerable
|
|
13
|
-
*/it('should compare trackable and registerable events',function(){var registerableEventsFromCore=[];var trackableEventsFromCore=[];registerableEventsFromCore.push.apply(registerableEventsFromCore,Object.keys(SgTrackingCore.register));trackableEventsFromCore.push.apply(trackableEventsFromCore,Object.keys(SgTrackingCore.track));var comparable=[].concat(trackableEventsFromCore,['addTracker','removeTracker']);expect(registerableEventsFromCore).to.have.members(comparable);});it('should make the core globally available in the window object',function(){expect(window.SgTrackingCore).to.be.equal(SgTrackingCore);});/**
|
|
14
|
-
* Simple tests against the pub/sub system.
|
|
15
|
-
*
|
|
16
|
-
* Foreach event
|
|
17
|
-
* 1. registers for the event
|
|
18
|
-
* 2. triggers the event
|
|
19
|
-
* 3. checks that registered callback was called with given test data
|
|
20
|
-
*/it('should handle basic pub/sub functionality',function(){var spies=[];var options={trackerName:'mock'};var expectedObject={expected:'data'};SgTrackingCore.track.pageview();trackableEvents.forEach(function(event){var spy=sinon.spy();spies.push(spy);// Subscribe and publish an event
|
|
21
|
-
var sub=SgTrackingCore.register[event](spy,options);var that=SgTrackingCore.track[event](expectedObject);// Unsubscribe and publish an event
|
|
22
|
-
sub.remove();SgTrackingCore.track[event](expectedObject);// Core should be returned to allow chaining
|
|
23
|
-
expect(that).to.equal(SgTrackingCore);// Check parameters
|
|
24
|
-
expect(spy).to.have.been.calledWith(expectedObject);// Make sure core is cloning the data instead of passing the original reference
|
|
25
|
-
expect(spy.getCall(0).args[0]).to.not.equal(expectedObject);});// Make sure there have been no duplicated calls
|
|
26
|
-
spies.forEach(function(spy){expect(spy).to.have.been.calledOnce;});});/**
|
|
27
|
-
* Makes sure that core is adding the blacklist to the unified event handler
|
|
28
|
-
*/it('should test whitelist/blacklist filtering',function(){var unifiedTracker={trackerName:'unified'};var customTracker={trackerName:'mock',options:{useNativeSdk:true}};var customTracker2={trackerName:'mock2',options:{useNativeSdk:false}};trackableEvents.forEach(function(event){var customSpy=sinon.spy();var customSpy2=sinon.spy();var unifiedSpy=sinon.spy();SgTrackingCore.register[event](unifiedSpy,unifiedTracker);SgTrackingCore.register[event](customSpy,customTracker);SgTrackingCore.register[event](customSpy2,customTracker2);SgTrackingCore.track[event](sgData);expect(unifiedSpy).to.have.been.calledWith(sgData,{shopgate:true,merchant:true},['mock']);expect(customSpy).to.have.been.calledWith(sgData);expect(customSpy2).to.have.been.calledWith(sgData);});});/**
|
|
29
|
-
* 1. activates optin
|
|
30
|
-
* 2. checks that removeTracker is called
|
|
31
|
-
* 3. deactivates optin
|
|
32
|
-
* 4. check thats addTracker is called
|
|
33
|
-
*/it('should test that opt out triggers add/remove tracker events',function(){var options={trackerName:'mock'};// Create and prepare spies
|
|
34
|
-
var spyAdd=sinon.spy();var spyRemove=sinon.spy();SgTrackingCore.register.addTracker(spyAdd,options);SgTrackingCore.register.removeTracker(spyRemove,options);// Activates opt out
|
|
35
|
-
SgTrackingCore.optOut(true);expect(spyAdd).to.not.have.been.calledOnce.to.not["throw"]();expect(spyRemove).to.have.been.called.to.not["throw"]();// Reset spies
|
|
36
|
-
spyAdd.reset();spyRemove.reset();// Deactivates opt out
|
|
37
|
-
SgTrackingCore.optOut(false);expect(spyAdd).to.have.been.calledOnce.to.not["throw"]();expect(spyRemove).to.not.have.been.called.to.not["throw"]();});/**
|
|
38
|
-
* 1. Registers for an merchant only event
|
|
39
|
-
* 2. Checks that shopgate events are not triggering it
|
|
40
|
-
* 3. Register for an shopgate only event
|
|
41
|
-
* 4. Checks that merchant events are not triggering it
|
|
42
|
-
* 5. Checks that listener for both is called in both cases
|
|
43
|
-
*/it('should test merchant/shopgate account restrictions',function(){trackableEvents.forEach(function(event){// Create spies
|
|
44
|
-
var spyAll=sinon.spy();var spyShopgateEvent=sinon.spy();var spyMerchantEvent=sinon.spy();// Register spies
|
|
45
|
-
SgTrackingCore.register[event](spyAll,{trackerName:'mock'});SgTrackingCore.register[event](spyShopgateEvent,{trackerName:'mock',merchant:false});SgTrackingCore.register[event](spyMerchantEvent,{trackerName:'mock',shopgate:false});// Trigger events
|
|
46
|
-
SgTrackingCore.track[event]({},null,{shopgate:true,merchant:false});SgTrackingCore.track[event]({},null,{shopgate:false,merchant:true});// Take assertions
|
|
47
|
-
expect(spyAll).to.have.been.calledTwice.to.not["throw"]();expect(spyShopgateEvent).to.have.been.calledOnce.to.not["throw"]();expect(spyMerchantEvent).to.have.been.calledOnce.to.not["throw"]();});});it('should test page scope restrictions',function(){trackableEvents.forEach(function(event){// Create spies
|
|
48
|
-
var spyAll=sinon.spy();var spyIndex=sinon.spy();var spyCart=sinon.spy();// Register spies
|
|
49
|
-
SgTrackingCore.register[event](spyAll,{trackerName:'mock'});SgTrackingCore.register[event](spyIndex,{trackerName:'mock',page:'index'});SgTrackingCore.register[event](spyCart,{trackerName:'mock',page:'cart'});// Track for index
|
|
50
|
-
SgTrackingCore.track[event]({},'index');expect(spyIndex).to.have.been.calledOnce;expect(spyCart).to.not.have.been.called;expect(spyAll).to.have.been.calledOnce;spyIndex.reset();// Track for cart
|
|
51
|
-
SgTrackingCore.track[event]({},'cart');expect(spyIndex).to.not.have.been.calledOnce;expect(spyCart).to.have.been.called;expect(spyAll).to.have.been.calledTwice;});});/**
|
|
52
|
-
* Mocks econda, ga universal and ga classic to test cross domain functionality
|
|
53
|
-
*/it('should test cross domain tracking',function(){// Set global test data
|
|
54
|
-
global.window.sgData=sgData;// Add some econda params
|
|
55
|
-
global.window.getEmosCrossUrlParams=function(){return'emos_mock=1122';};// "on ready" callback can be called immediately
|
|
56
|
-
global.window.ga=function(fn){return fn();};// Get tracker by name is not required for this test
|
|
57
|
-
global.window.ga.getByName=function(){};// Add some google universal parameters
|
|
58
|
-
global.window.gaplugins={Linker:function Linker(){return{decorate:function decorate(url){return"".concat(url,"&_ga=1.199239214.1624002396.1440697407");}};}};var expectedUrl='http://testshop.reichhorn.localdev.cc/php/shopgate/index?emos_mock=1122&_ga=1.199239214.1624002396.1440697407';// Create ga classic spy to check called objects
|
|
59
|
-
/* eslint-disable no-underscore-dangle, no-multi-assign */global._gaq=global.window._gaq={};var gaqPush=global._gaq.push=sinon.spy();/* eslint-enable no-underscore-dangle, no-multi-assign */ // Execute cross domain tracking logic
|
|
60
|
-
SgTrackingCore.crossDomainTracking('http://testshop.reichhorn.localdev.cc/php/shopgate/index');// Check _gaq calls
|
|
61
|
-
expect(gaqPush).to.have.been.calledOnce.to.not["throw"]();expect(gaqPush.getCall(0).args[0][0]).to.equal('merchant_._link');expect(gaqPush.getCall(0).args[0][1]).to.equal(expectedUrl);// Execute cross domain tracking logic with form element
|
|
62
|
-
/* eslint-disable no-underscore-dangle, no-multi-assign */gaqPush=global._gaq.push=sinon.spy();/* eslint-enable no-underscore-dangle, no-multi-assign */var element=document.createElement('form');element.action='http://shopgate.com';SgTrackingCore.crossDomainTracking('http://testshop.reichhorn.localdev.cc/php/shopgate/index',element);expect(gaqPush).to.have.been.calledOnce.to.not["throw"]();expect(gaqPush.getCall(0).args[0][0]).to.equal('merchant_._linkByPost');expect(gaqPush.getCall(0).args[0][1]).to.equal(element);// Execute cross domain tracking logic with form and without classic sdk
|
|
63
|
-
/* eslint-disable no-underscore-dangle */global._gaq=undefined;/* eslint-enable no-underscore-dangle */SgTrackingCore.crossDomainTracking('http://testshop.reichhorn.localdev.cc/php/shopgate/index',element);expect(element.action).to.equal(expectedUrl);// Redefine window.location as it is simulated using jsdom
|
|
64
|
-
// Otherwise the location.href can't be changed
|
|
65
|
-
Object.defineProperty(global.window,'location',{writable:true,value:{href:''}});// Execute cross domain tracking without ga sdk and without element
|
|
66
|
-
SgTrackingCore.crossDomainTracking('http://testshop.reichhorn.localdev.cc/php/shopgate/index');expect(global.window.location.href).to.equal(expectedUrl);});it('should test buildAdImageIdentifierName',function(){var withTitle=SgTrackingCore.buildAdImageIdentifierName('Title',123);expect(withTitle).to.equal('Title (id: 123)');var withoutTitle=SgTrackingCore.buildAdImageIdentifierName(undefined,123);expect(withoutTitle).to.equal('(id: 123)');});it('should test isOptOut()',function(){expect(SgTrackingCore.isOptOut()).to.be["false"];SgTrackingCore.optOut(true);expect(SgTrackingCore.isOptOut()).to.be["true"];SgTrackingCore.optOut(false);expect(SgTrackingCore.isOptOut()).to.be["false"];});it('should test getScannerEvents()',function(){var expected={SCAN_ACTIVATED:'scan_activated',SCAN_STARTED:'scan_started',SCAN_CANCELED:'scan_canceled',SCAN_SUCCESS:'scan_success',SCAN_FAIL:'scan_fail',SCAN_USER_LINK_INTERACTION:'scan_user_link_interaction'};expect(SgTrackingCore.getScannerEvents()).to.deep.equal(expected);});});
|
package/tests/FbPixelTest.js
DELETED
|
@@ -1,13 +0,0 @@
|
|
|
1
|
-
/* eslint global-require: "off" */import chai from'chai';import sinon from'sinon';import sinonChai from'sinon-chai';import mochaJsdom from'mocha-jsdom';import storageMock from"./helpers/localStorage-mock";import{sgData}from"./data/tracking.testData";var expect=chai.expect;chai.use(sinonChai);describe('FbPixel',function(){var SgFbPixelTracking;var SgTrackingCore;var trackingCoreEvents;var spyFbq;var SGLink;mochaJsdom();before(function(){window.sgData=sgData;global.sgData=sgData;global.fbq=function(){};global.localStorage=storageMock();window.SGEvent={};document.body.innerHTML='<head><script></script></head><body></body>';// eslint-disable-next-line prefer-destructuring
|
|
2
|
-
SGLink=require("../helpers/helper").SGLink;SgFbPixelTracking=require("../plugins/trackers/FbPixel")["default"];SgTrackingCore=require("../core/Core")["default"].reset();trackingCoreEvents=require("./helpers/triggerTrackingCoreEvents");spyFbq=sinon.spy(global,'fbq');// eslint-disable-next-line no-new
|
|
3
|
-
new SgFbPixelTracking({config:{pixelIds:['7117','2222']}});SgTrackingCore.registerFinished();});it('should throw errors for wrong init',function(){var spyConsole=sinon.spy(console,'warn');// eslint-disable-next-line no-new
|
|
4
|
-
new SgFbPixelTracking();// eslint-disable-next-line no-new
|
|
5
|
-
new SgFbPixelTracking({useNativeSdk:true});expect(spyConsole).to.have.been.calledWith('SgFbPixelTracking: pixels missing');expect(spyConsole).to.have.been.calledWith('SgFbPixelTracking: no native SDK support for this plugin');});it('should load the fb sdk',function(){expect(document.getElementsByTagName('script')[0].src.indexOf('connect.facebook.net/en_US/fbevents.js')).to.not.equal(-1);});it('should send init events',function(){var _spyFbq=spyFbq,callCount=_spyFbq.callCount;expect(spyFbq.getCall(callCount-3).args).to.eql(['init','7117',undefined]);expect(spyFbq.getCall(callCount-2).args).to.eql(['addPixelId','2222',undefined]);expect(spyFbq.getCall(callCount-1).args).to.eql(['track','PageView',undefined]);});it('should send completedRegistration',function(){var input=trackingCoreEvents.completedRegistration();// eslint-disable-next-line no-unused-expressions
|
|
6
|
-
expect(spyFbq.withArgs('track','CompleteRegistration',{content_name:input.registrationType})).to.have.been.calledOnce;});it('should send viewContent',function(){var input=trackingCoreEvents.viewContent();var contentType=new SGLink(input.page.link).action||'index';// eslint-disable-next-line no-unused-expressions
|
|
7
|
-
expect(spyFbq.withArgs('track','ViewContent',{content_name:input.page.name,content_ids:[''],content_type:contentType})).to.have.been.calledOnce;});it('should send addedPaymentInfo',function(){trackingCoreEvents.addedPaymentInfo();// eslint-disable-next-line no-unused-expressions
|
|
8
|
-
expect(spyFbq.withArgs('track','AddPaymentInfo',undefined)).to.have.been.calledOnce;});it('should send purchase',function(){var input=trackingCoreEvents.purchase();var productIds=input.order.products.map(function(product){return product.productNumber||product.uid;});var expected={content_ids:productIds,content_type:'product',value:parseFloat(input.order.amount.gross),currency:input.order.amount.currency};if(productIds.length===1){expected.content_name=input.order.products[0].name;}// eslint-disable-next-line no-unused-expressions
|
|
9
|
-
expect(spyFbq.withArgs('track','Purchase',expected)).to.have.been.calledOnce;});it('should send initiatedCheckout',function(){var input=trackingCoreEvents.initiatedCheckout();var productIds=input.cart.products.map(function(product){return product.productNumber||product.uid;});var expected={content_ids:productIds,content_type:'product',value:parseFloat(input.cart.amount.gross),currency:input.cart.amount.currency,num_items:input.cart.productsCount};if(productIds.length===1){expected.content_name=input.cart.products[0].name;}// eslint-disable-next-line no-unused-expressions
|
|
10
|
-
expect(spyFbq.withArgs('track','InitiateCheckout',expected)).to.have.been.calledOnce;});it('should send addToCart',function(){var input=trackingCoreEvents.addToCart();var value=0;var productIds=input.products.map(function(product){value+=parseFloat(product.amount.gross);return product.productNumber||product.uid;});var expected={content_ids:productIds,content_type:'product',value:value,currency:input.products[0].amount.currency};if(productIds.length===1){expected.content_name=input.products[0].name;}// eslint-disable-next-line no-unused-expressions
|
|
11
|
-
expect(spyFbq.withArgs('track','AddToCart',expected)).to.have.been.calledOnce;});it('should send addToWishlist',function(){var input=trackingCoreEvents.addToWishlist();var value=0;var productIds=input.favouriteListProducts.map(function(product){value+=parseFloat(product.unit_amount_with_tax)/100;return product.product_number_public||product.product_number;});var expected={content_ids:productIds,content_type:'product',value:value,currency:input.favouriteListProducts[0].currency_id};if(productIds.length===1){expected.content_name=input.favouriteListProducts[0].name;}// eslint-disable-next-line no-unused-expressions
|
|
12
|
-
expect(spyFbq.withArgs('track','AddToWishlist',expected)).to.have.been.calledOnce;});it('should send search',function(){var input=trackingCoreEvents.search();var productIds=input.products.map(function(product){return product.productNumber||product.uid;});// eslint-disable-next-line no-unused-expressions
|
|
13
|
-
expect(spyFbq.withArgs('track','Search',{content_ids:productIds,content_type:'product',search_string:input.search.query})).to.have.been.calledOnce;});it('should be added to the window object',function(){expect(global.window.SgFbPixelTracking).to.equal(SgFbPixelTracking);});after(function(){delete global.sgData;delete global.fbq;});});
|
package/tests/GaBaseTest.js
DELETED
|
@@ -1,47 +0,0 @@
|
|
|
1
|
-
import chai from'chai';import sinon from'sinon';import chaiSinon from'sinon-chai';import mochaJsdom from'mocha-jsdom';import storageMock from"./helpers/localStorage-mock";import{sgDataOrder}from"./data/tracking.testData";import{gaOrderData}from"./data/tracking.expectedData";var expect=chai.expect;var rerequire=mochaJsdom.rerequire;describe('GaBase',function(){chai.use(chaiSinon);mochaJsdom();// Events for ga
|
|
2
|
-
var events=['pageview','addToCart','purchase'];// Custom events
|
|
3
|
-
// Maps unified name to ga name and if merchant account is expected to recieve these events
|
|
4
|
-
var customEvents={smartbanner:['Smartbanner',true],scrollTop:['ScrollTop',false],qrScanner:['QRScanner',true],adScanner:['AdScanner',true],ccScanner:['CcScanner',true],appReviewPrompt:['AppReviewPrompt',false],filterLiveSuggest:['FilterLiveSuggest',false],openDeepLink:['DeepLinkOpen',false],openUniversalLink:['UniversalLinkOpen',false],openDeferredDeepLink:['DeferredDeepLinkOpen',false],openSmartAppDownloadLink:['SmartAppDownloadLink',false],openPushNotification:['PushNotification',false]};var eventCallbacks={};var SgTrackingGAPlugin=null;var SgTrackingCore=null;var gaqSpy=null;var gaSpy=null;before(function(){// Set globals for legacy code
|
|
5
|
-
global.window.sgData=sgDataOrder;global.window.sgData.device.access='App';global.window.sgData.device.codebase='1.2.3';global.localStorage=storageMock();window.SGEvent={};// eslint-disable-next-line global-require
|
|
6
|
-
SgTrackingCore=require("../core/Core")["default"].reset();});beforeEach(function(){// Reset the core
|
|
7
|
-
SgTrackingCore.reset();// After globals are set scripts can be imported
|
|
8
|
-
SgTrackingGAPlugin=rerequire('../plugins/trackers/GaBase.js')["default"];// Set dom content
|
|
9
|
-
document.body.innerHTML="\n <head>\n <!-- Parent node for ga-->\n <script></script>\n </head>\n\n <body>\n </body>";// Spy on universal sdk
|
|
10
|
-
gaSpy=sinon.spy();global.window.ga=gaSpy;global.ga=gaSpy;// Save all registered callbacks for events
|
|
11
|
-
[].concat(events,Object.keys(customEvents)).forEach(function(event){SgTrackingCore.register[event]=function(cb){eventCallbacks[event]=cb;};});// Initiate universal
|
|
12
|
-
SgTrackingGAPlugin.createUniversal({config:{merchant:[{id:'merchant1'},{id:'merchant2'}],shopgate:{id:'shopgate'}}});// Spy on ga classic
|
|
13
|
-
gaqSpy=sinon.spy();// eslint-disable-next-line no-underscore-dangle
|
|
14
|
-
global._gaq={push:gaqSpy};// eslint-disable-next-line no-underscore-dangle
|
|
15
|
-
global.window._gaq=global._gaq;// Check classic
|
|
16
|
-
SgTrackingGAPlugin.createClassic({config:{merchant:[{id:'merchant1'},{id:'merchant2'}]}});});it('should test that classic sdk is initialized correctly',function(){// Make sure dom script element has been created
|
|
17
|
-
expect(document.getElementsByTagName('script')[0].src.indexOf('google-analytics.com/ga')).to.not.equal(-1);// Make sure that gaq has been called correctly
|
|
18
|
-
expect(gaqSpy).to.have.callCount(3);expect(gaqSpy.getCall(0).args[0]).to.deep.equal(['merchant_._setAccount','merchant1']);expect(gaqSpy.getCall(0).args[1]).to.deep.equal(['merchant_._setAllowLinker',true]);expect(gaqSpy.getCall(1).args[0]).to.deep.equal(['merchant_merchant2._setAccount','merchant2']);expect(gaqSpy.getCall(1).args[0]).to.deep.equal(['merchant_merchant2._setAccount','merchant2']);expect(gaqSpy.getCall(2).args[0]).to.deep.equal(['_gat._anonymizeIp',true]);expect(gaqSpy.getCall(2).args[1]).to.deep.equal(['_gat._forceSSL',true]);});it('should test that universal sdk is initialized correctly',function(){// Make sure dom script element has been created
|
|
19
|
-
expect(document.getElementsByTagName('script')[1].src.indexOf('google-analytics.com/analytics')).to.not.equal(-1);// Make sure that ga has been called correctly
|
|
20
|
-
expect(gaSpy).to.have.callCount(11);expect(gaSpy.getCall(0).args).to.deep.equal(['create',{trackingId:'merchant1',cookieDomain:'auto',name:'merchant_merchant1',allowLinker:true}]);expect(gaSpy.getCall(1).args).to.deep.equal(['merchant_merchant1.set','anonymizeIp',true]);expect(gaSpy.getCall(2).args).to.deep.equal(['merchant_merchant1.set','forceSSL',true]);expect(gaSpy.getCall(3).args).to.deep.equal(['create',{trackingId:'merchant2',cookieDomain:'auto',name:'merchant_merchant2',allowLinker:true}]);expect(gaSpy.getCall(4).args).to.deep.equal(['merchant_merchant2.set','anonymizeIp',true]);expect(gaSpy.getCall(5).args).to.deep.equal(['merchant_merchant2.set','forceSSL',true]);expect(gaSpy.getCall(6).args).to.deep.equal(['create',{trackingId:'shopgate',cookieDomain:'auto',name:'shopgate',allowLinker:true}]);expect(gaSpy.getCall(7).args).to.deep.equal(['shopgate.set','anonymizeIp',true]);expect(gaSpy.getCall(8).args).to.deep.equal(['shopgate.set','forceSSL',true]);expect(gaSpy.getCall(9).args).to.deep.equal(['shopgate.set','dimension1','10006']);expect(gaSpy.getCall(10).args).to.deep.equal(['shopgate.set','dimension2','1.2.3']);});/**
|
|
21
|
-
* Helper functions that allows to test a specific event and asserts correct sdk calls
|
|
22
|
-
*
|
|
23
|
-
* @param {string} eventName name of the event
|
|
24
|
-
* @param {Object} data data that is passed to the event
|
|
25
|
-
* @param {Object} expectedUniversal expected arguments for universal sdk
|
|
26
|
-
* @param {Object} expectedClassic expected arguments for classic sdk
|
|
27
|
-
* @param {bool} merchant if merchants should receive the event
|
|
28
|
-
* @private
|
|
29
|
-
*/function testEventData(eventName,data,expectedUniversal,expectedClassic){var merchant=arguments.length>4&&arguments[4]!==undefined?arguments[4]:true;var gaCalls=gaSpy.getCalls().length;var gaqCalls=gaqSpy.getCalls().length;eventCallbacks[eventName](data,{merchant:true,shopgate:true,trackerName:'mock'});expect(gaSpy).to.have.callCount(merchant?gaCalls+3:gaCalls+1);if(merchant){// Merchant 1
|
|
30
|
-
expect(gaSpy.getCall(gaCalls).args).to.deep.equal(['merchant_merchant1.send'].concat(expectedUniversal));// Merchant 2
|
|
31
|
-
expect(gaSpy.getCall(gaCalls+1).args).to.deep.equal(['merchant_merchant2.send'].concat(expectedUniversal));}// Shopgate
|
|
32
|
-
expect(gaSpy.getCall(merchant?gaCalls+2:gaCalls).args).to.deep.equal(['shopgate.send'].concat(expectedUniversal));if(merchant){expect(gaqSpy).to.have.callCount(gaqCalls+2);expect(gaqSpy.getCall(gaqCalls).args).to.deep.equal([["merchant_.".concat(expectedClassic[0])].concat(expectedClassic.slice(1))]);expect(gaqSpy.getCall(gaqCalls+1).args).to.deep.equal([["merchant_merchant2.".concat(expectedClassic[0])].concat(expectedClassic.slice(1))]);}}/**
|
|
33
|
-
* Helper function to create data for custom events
|
|
34
|
-
*
|
|
35
|
-
* @param {string} eventCategory event name
|
|
36
|
-
* @param {string} eventAction action name
|
|
37
|
-
* @param {string} eventLabel label
|
|
38
|
-
* @param {Object} eventValue value / data
|
|
39
|
-
* @param {boolean} nonInteraction cause of the event (user: true)
|
|
40
|
-
* @returns {{universal: *[], classic: *[]}}
|
|
41
|
-
*/function createCustomEventData(eventCategory,eventAction,eventLabel,eventValue,nonInteraction){return{universal:['event',{eventCategory:eventCategory,eventAction:eventAction,eventLabel:eventLabel,eventValue:eventValue,nonInteraction:nonInteraction}],classic:['_trackEvent',eventCategory,eventAction,eventLabel,eventValue,nonInteraction]};}it('should test sdk calls for addToCart event',function(){testEventData('addToCart',global.window.sgData,['pageview','add_to_cart'],['_trackPageview','add_to_cart']);});it('should test sdk calls for custom events',function(){Object.keys(customEvents).forEach(function(eventName){var data=createCustomEventData(customEvents[eventName][0],'action','label','value',false);testEventData(eventName,data.universal[1],data.universal,data.classic,customEvents[eventName][1]);});});it('should test universal sdk calls for the purchase event',function(){var gaCalls=gaSpy.getCalls().length;var transactionData=gaOrderData.universal.order;var itemData=gaOrderData.universal.items;eventCallbacks.purchase(global.window.sgData);expect(gaSpy).to.have.callCount(gaCalls+15);// Should require ecommerce plugin for all accounts
|
|
42
|
-
expect(gaSpy.getCall(gaCalls).args).to.deep.equal(['merchant_merchant1.require','ecommerce','ecommerce.js']);expect(gaSpy.getCall(gaCalls+1).args).to.deep.equal(['merchant_merchant2.require','ecommerce','ecommerce.js']);expect(gaSpy.getCall(gaCalls+2).args).to.deep.equal(['shopgate.require','ecommerce','ecommerce.js']);// Should start a transaction on all accounts
|
|
43
|
-
expect(gaSpy.getCall(gaCalls+3).args).to.deep.equal(['merchant_merchant1.ecommerce:addTransaction',transactionData]);expect(gaSpy.getCall(gaCalls+4).args).to.deep.equal(['merchant_merchant2.ecommerce:addTransaction',transactionData]);expect(gaSpy.getCall(gaCalls+5).args).to.deep.equal(['shopgate.ecommerce:addTransaction',transactionData]);// Should add two items on all accounts
|
|
44
|
-
expect(gaSpy.getCall(gaCalls+6).args).to.deep.equal(['merchant_merchant1.ecommerce:addItem',itemData[0]]);expect(gaSpy.getCall(gaCalls+7).args).to.deep.equal(['merchant_merchant2.ecommerce:addItem',itemData[0]]);expect(gaSpy.getCall(gaCalls+8).args).to.deep.equal(['shopgate.ecommerce:addItem',itemData[0]]);expect(gaSpy.getCall(gaCalls+9).args).to.deep.equal(['merchant_merchant1.ecommerce:addItem',itemData[1]]);expect(gaSpy.getCall(gaCalls+10).args).to.deep.equal(['merchant_merchant2.ecommerce:addItem',itemData[1]]);expect(gaSpy.getCall(gaCalls+11).args).to.deep.equal(['shopgate.ecommerce:addItem',itemData[1]]);// Should submit the transaction on all accounts
|
|
45
|
-
expect(gaSpy.getCall(gaCalls+12).args).to.deep.equal(['merchant_merchant1.ecommerce:send']);expect(gaSpy.getCall(gaCalls+13).args).to.deep.equal(['merchant_merchant2.ecommerce:send']);expect(gaSpy.getCall(gaCalls+14).args).to.deep.equal(['shopgate.ecommerce:send']);});it('should test classic sdk calls for the purchase event',function(){var transactionData=gaOrderData.classic.order;var itemData=gaOrderData.classic.items;var gaqCalls=gaqSpy.getCalls().length;eventCallbacks.purchase(global.window.sgData);expect(gaqSpy).to.have.callCount(gaqCalls+10);// Should start transaction on all accounts
|
|
46
|
-
expect(gaqSpy.getCall(gaqCalls).args).to.deep.equal([['merchant_._addTrans'].concat(transactionData)]);expect(gaqSpy.getCall(gaqCalls+1).args).to.deep.equal([['merchant_merchant2._addTrans'].concat(transactionData)]);// Should add both producs on all accounts
|
|
47
|
-
expect(gaqSpy.getCall(gaqCalls+2).args).to.deep.equal([['merchant_._addItem'].concat(itemData[0])]);expect(gaqSpy.getCall(gaqCalls+3).args).to.deep.equal([['merchant_merchant2._addItem'].concat(itemData[0])]);expect(gaqSpy.getCall(gaqCalls+4).args).to.deep.equal([['merchant_._addItem'].concat(itemData[1])]);expect(gaqSpy.getCall(gaqCalls+5).args).to.deep.equal([['merchant_merchant2._addItem'].concat(itemData[1])]);expect(gaqSpy.getCall(gaqCalls+6).args).to.deep.equal([['merchant_._set','currencyCode','EUR']]);expect(gaqSpy.getCall(gaqCalls+7).args).to.deep.equal([['merchant_merchant2._set','currencyCode','EUR']]);expect(gaqSpy.getCall(gaqCalls+8).args).to.deep.equal([['merchant_._trackTrans',undefined]]);expect(gaqSpy.getCall(gaqCalls+9).args).to.deep.equal([['merchant_merchant2._trackTrans',undefined]]);});after(function(){SgTrackingCore=undefined;});});
|
package/tests/UnifiedTest.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
/* eslint global-require: "off" */import chai from'chai';import sinon from'sinon';import sinonChai from'sinon-chai';import mochaJsdom from'mocha-jsdom';import storageMock from"./helpers/localStorage-mock";var expect=chai.expect;chai.use(sinonChai);describe('Unified',function(){var SgUnifiedTracking;var SgTrackingCore;var trackingHelper;mochaJsdom();before(function(){global.localStorage=storageMock();global.Headers=function(){};global.fetch=function(){return new Promise(function(){});};global.console.groupCollapsed=function(){};global.console.groupEnd=function(){};window.SGEvent={};trackingHelper=require("../helpers/helper");SgTrackingCore=require("../core/Core")["default"].reset().registerFinished();SgUnifiedTracking=require("../plugins/trackers/Unified")["default"];});var events=['viewContent','purchase','addToCart','initiatedCheckout','completedRegistration','addToWishlist','search','addedPaymentInfo'];var plugin=null;/**
|
|
2
|
-
* Helper to get always the same plugin instance
|
|
3
|
-
*/function createPluginInstance(){plugin=plugin||new SgUnifiedTracking();}it('should register for events',function(){var registerSpy=sinon.spy(SgUnifiedTracking.prototype,'registerHelper');createPluginInstance();events.forEach(function(event){expect(registerSpy).to.have.been.calledWith(event);});registerSpy.restore();});it('should do ajax requests',function(){var spy=sinon.spy(trackingHelper,'sendDataRequest');createPluginInstance();// Trigger opt-out
|
|
4
|
-
SgTrackingCore.optOut();expect(spy).to.have.been.calledWith('remove_unified_trackers');// Revert the opt-out
|
|
5
|
-
SgTrackingCore.optOut(false);expect(spy).to.have.been.calledWith('add_unified_trackers');spy.restore();});it('should call SgTrackingAppHandler',function(){createPluginInstance();var spy=sinon.spy(plugin.appHandler,'viewContent');SgTrackingCore.track.viewContent({page:{link:'startpage',name:'Startpage'}});expect(spy).to.have.been.calledWith({id:'',type:'startpage',name:'Startpage'},{blacklist:true,trackers:undefined});spy.restore();});});
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
var gaOrderData={universal:{order:{affiliation:'Offizieller Shopgate Testshop',currency:'EUR',id:'1700001978',revenue:303.36,shipping:10,tax:-0},items:[{id:'1700001978',name:'Produkt mit einem Grundpreis – langer Text',price:75.63,quantity:1,sku:'item_number_public-10'},{id:'1700001978',name:'Produkt als Highlight 2',price:227.73,quantity:1,sku:'item_number_public-38'}]},classic:{order:['1700001978','Offizieller Shopgate Testshop',303.36,-0,10,'Butzbach','',undefined],items:[['1700001978','item_number_public-10','Produkt mit einem Grundpreis – langer Text','',75.63,1],['1700001978','item_number_public-38','Produkt als Highlight 2','',227.73,1]]}};export{gaOrderData};
|
|
@@ -1 +0,0 @@
|
|
|
1
|
-
function _extends(){_extends=Object.assign||function(target){for(var i=1;i<arguments.length;i++){var source=arguments[i];for(var key in source){if(Object.prototype.hasOwnProperty.call(source,key)){target[key]=source[key];}}}return target;};return _extends.apply(this,arguments);}var sgData={shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'xxx',loggedIn:true,email:'xxx@shopgate.com',phone:'+1223456',birthday:'1904-12-17',gender:'f'},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.xxx.localdev.cc/php/shopgate/checkout_success/87424',name:'startpage',link:'http://testshop.xxx.localdev.cc/php/shopgate/index'},tracking:{get:[]}};var sgDataAddress={firstName:'Bernd',surname:'Mustermann',company:'Shopgate',street:'Teststreet 101',street2:'',zipcode:'35510',stateId:null,city:'Butzbach',countryId:'DE'};var sgDataOrder=_extends({},sgData,{order:{number:'1700001978',amount:{currency:'EUR',gross:'303.36',net:'303.36',tax:'-0.00',coupons:{currency:'EUR',net:'0.00',gross:'0.00'}},invoiceAddress:sgDataAddress,shippingAddress:sgDataAddress,shipping:{name:'DHL',amount:{currency:'EUR',gross:'10.00',net:'9.00',tax:'0.00'}},payment:{name:'Vorkasse (Shopgate (powered by Adyen))',amount:{currency:'EUR',gross:'0.00',net:'0.00',tax:'0.00'}},user:{email:'test@shopgate.com',gender:'m',phone:'12346',birthday:'1970-01-01',customerNumber:'101889',externalCustomerId:'',externalCustomerNumber:''},products:[{uid:'SG10',productNumber:'item_number_public-10',name:'Produkt mit einem Grundpreis – langer Text',quantity:'1',tags:[],amount:{currency:'EUR',gross:'75.63',net:'75.63',tax:'0.00'},stockQuantity:81},{uid:'SG38',productNumber:'item_number_public-38',name:'Produkt als Highlight 2',quantity:'1',tags:[],amount:{currency:'EUR',gross:'227.73',net:'227.73',tax:'0.00'},stockQuantity:69}],coupons:[],field:{fi_fa_fo:{label:'Fi F Fo',value:''}}}});var sgDataSearch={search:{query:'test',resultCount:5},products:[{uid:'LEOTEST10',productNumber:'LEOTEST10',name:'LEO TEST 10 (can be deleted)',amount:{currency:'EUR',net:'2200.00',gross:'2200.00',tax:'0.00',taxRate:'0.00'},tags:[],stockQuantity:0},{uid:'test-size-01',productNumber:'',name:'Product with different sizings',amount:{currency:'EUR',net:'0.00',gross:'0.00',tax:'0.00',taxRate:'0.00'},tags:[],stockQuantity:0},{uid:'1234567',productNumber:'1234567',name:'LEO TEST (can be deleted)',amount:{currency:'EUR',net:'60.00',gross:'60.00',tax:'0.00',taxRate:'0.00'},tags:['tag01',' tag02'],stockQuantity:0}],shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'2034a73978bd4b5af547b82514dea39f',loggedIn:false},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/item/534736',name:'search',link:'http://testshop.schneider.localdev.cc/php/shopgate/search?s=test&sort=relevance_desc',title:'Search: test - Offizieller Shopgate Testshop'},tracking:{get:[]}};var sgDataProduct={product:{uid:'SG6',productNumber:'item_number_public-6',name:'Produkt mit einem Sonderpreis',amount:{currency:'EUR',taxRate:'19.00',net:'21.01',gross:'25.00',tax:'3.99'},tags:[],stockQuantity:66},shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'2034a73978bd4b5af547b82514dea39f',loggedIn:true,email:'carsten.schneider@shopgate.com',phone:'12346',birthday:'1989-09-09',gender:'m'},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/cart',name:'productDetails',link:'http://testshop.schneider.localdev.cc/php/shopgate/item/534736',title:'Produkt mit einem Sonderpreis - Offizieller Shopgate Testshop'},tracking:{get:[]}};var sgDataCheckout={cart:{amount:{currency:'EUR',net:'42.02',gross:'42.02',tax:'0.00',taxes:[],products:{net:'42.02',gross:'42.02'},complete_amount_string:'42.02'},orderable:true,products:[{uid:'SG6',parentUid:null,productNumber:'item_number_public-6',name:'Produkt mit einem Sonderpreis',amount:{currency:'EUR',net:'21.01',gross:'25.00',tax:'3.99',taxRate:'19.00'},tags:[],additionalShippingCosts:{perOrder:'0',perUnit:'0'},quantity:'2',stockQuantity:66}],coupons:[],productsCount:2},checkout:{shipping:{name:'Österreichische Post'},payment:{name:'Vorkasse (Shopgate (powered by Adyen))'},shippingAddress:sgDataAddress,invoiceAddress:sgDataAddress},shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'2034a73978bd4b5af547b82514dea39f',loggedIn:true,email:'carsten.schneider@shopgate.com',phone:'12346',birthday:'1989-09-09',gender:'m'},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/register',name:'checkoutConfirm',link:'http://testshop.schneider.localdev.cc/php/shopgate/checkout/default',title:'Offizieller Shopgate Testshop: Bestellung überprüfen - Offizieller Shopgate Testshop'},tracking:{get:[]}};var product={id:32938370,parent_id:null,has_children:false,currency_id:'EUR',shop_id:'131',product_number:'SG6',product_number_public:'item_number_public-6',manufacturer:'MANUFACTURER',manufacturer_item_number:'manufacturer_item_number-6',name:'Produkt mit einem Sonderpreis',tax_percent:'19.00',tax_class_item_id:'1416',msrp:'0',additional_shipping_costs_per_unit:'0',available_text:"<font color='#007700'>Available_Text</font>",is_free_shipping:false,description:'<p>Dieses Produkt hat einen Sonderpreis. Der aktuelle Preis könnte ein Aktionspreis sein. Diesem gegenüber steht der alte Preis.</p><p></p><p>\nALT: 50,00 EUR – NEU: 25,00 EUR</p><p></p><p>\nEs sollte ein Störer mit entsprechendem prozentualen Hinweis zu sehen sein.</p>',age_rating:'0',weight:'1000.0000',properties:{'Artikel-Nr.':'item_number_public-6'},ean:'',isbn:'',upc:null,pzn:'0',ignore_stock:false,stock_quantity:69,delivery_days:'0',is_available:true,unit_amount_with_tax:'2500',old_unit_amount_with_tax:'5000',unit_amount_display:'2500',unit_amount_display_old:'5000',amount_info_text:'',internal_order_info:'',has_image:true,display_type:'0',is_active:true,image_count:1,attribute_1:'',attribute_2:'',attribute_3:'',attribute_4:'',attribute_5:'',attribute_6:'',attribute_7:'',attribute_8:'',attribute_9:'',attribute_10:'',review_count:'1',review_average_score:'6',review_score_count:'1',has_options:false,has_input_fields:false,has_block_pricing:false,is_not_orderable:false,deeplink_onlineshop:'http://www.shopgate.com?shopgate_redirect=1',tags:null,unit_amount_net:'2100.840336',shipping_costs_per_order:'0',unit_amount_with_tax_formatted:'25,00',additional_shipping_costs_per_unit_formatted:'0,00',msrp_formatted:'0,00',old_unit_amount_with_tax_formatted:'50,00',shipping_costs:0,shipping_info:{shipping_notification:[],shipping_costs_display_formatted:'Kostenloser Versand',additional_shipping_costs_per_unit_formatted:'0,00 €'},image_urls:[{image_url_base:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/10006/1/5ae75db6116871392501166d5651eb67292c9be2f482f7e7134a5b0d69583363',image_url_140:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/1000…651eb67292c9be2f482f7e7134a5b0d69583363?w=140&h=140&zc=resize&fillc=000000',image_url_440:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/1000…651eb67292c9be2f482f7e7134a5b0d69583363?w=440&h=440&zc=resize&fillc=000000',image_url_640:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/1000…651eb67292c9be2f482f7e7134a5b0d69583363?w=640&h=640&zc=resize&fillc=000000',image_url_1024:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/1000…1eb67292c9be2f482f7e7134a5b0d69583363?w=1024&h=1024&zc=resize&fillc=000000',image_url_150:'http://testshop.schneider.localdev.cc/php/shopgate/sites/img/image.php/1000…651eb67292c9be2f482f7e7134a5b0d69583363?w=150&h=150&zc=resize&fillc=000000'}],discount_was_applied:false,unit_amount_display_min:'',unit_amount_display_max:'',price_info:{unit_amount_display_formatted:'21,01 €',unit_amount_display:2100,price_label:'Old Price',discount_label:'Angebot',discount_from_msrp:false,strike_price_display:5000,strike_price_display_formatted:'50,00 €',discount_amount_formatted:'28,99 €',discount_amount:2899.159664,discount_percent:58,discount_percent_formatted:'58%',discount_display_formatted:'28,99 €(58%)',discount_percent_is_final:false},available_text_priority:1,stock_text:'Noch 69 mal auf Lager',stock_text_priority:1,shipping_text:'Noch 69 mal auf Lager',product_labels:[],product_url:'item/534736',product_info_url:'product_info/534736',add_review_url:'add_review/534736',reviews_url:'reviews/534736',extended_fields:true,quantity_in_cart:1,update_image_gallery:true};var sgDataCategoryAll={category:{uid:'16',name:'3 – Darstellung (Text/Bild/etc.)',path:'3 – Darstellung (Text/Bild/etc.)'},products:[{uid:'SG114',productNumber:'item_number_public-114',name:'Produkt mit vielen Bewertungen',amount:{currency:'EUR',net:'21.01',gross:'25.00',tax:'3.99',taxRate:'19.00'},tags:[],stockQuantity:0},{uid:'SG13',productNumber:'item_number_public-13',name:'Produkt mit vielen Bildern',amount:{currency:'EUR',net:'25.21',gross:'30.00',tax:'4.79',taxRate:'19.00'},tags:[],stockQuantity:98}],shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'2034a73978bd4b5af547b82514dea39f',loggedIn:true,email:'carsten.schneider@shopgate.com',phone:'12346',birthday:'1989-09-09',gender:'m'},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/item/534733',name:'productList',link:'http://testshop.schneider.localdev.cc/php/shopgate/category/3136/all?cat_id…egory=3+%E2%80%93+Darstellung+%28Text%2FBild%2Fetc.%29&sort=relevance_desc',title:'3 – Darstellung (Text/Bild/etc.) - Offizieller Shopgate Testshop'},tracking:{get:[]}};var sgDataReviews={shop:{name:'Offizieller Shopgate Testshop',shop_number:'10006',market_id:'DE'},user:{sessionId:'2034a73978bd4b5af547b82514dea39f',loggedIn:true,email:'carsten.schneider@shopgate.com',phone:'12346',birthday:'1989-09-09',gender:'m'},device:{userAgent:'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_12_2) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/55.0.2883.95 Safari/537.36',os:'Other',type:'Phone',access:'Web',codebase:''},page:{referrer:'http://testshop.schneider.localdev.cc/php/shopgate/item/5347313134',name:'reviews',link:'http://testshop.schneider.localdev.cc/php/shopgate/reviews/5347313134',title:'Rezensionen - Produkt mit vielen Bewertungen - Offizieller Shopgate Testshop'},tracking:{get:[]}};var addedToCartProduct={products:[{uid:'SG6',productNumber:'item_number_public-6',name:'Produkt mit einem Sonderpreis',amount:{currency:'EUR',taxRate:'19.00',net:'21.01',gross:'25.00',tax:'3.99'},tags:[],stockQuantity:69,quantity:1}]};export{sgData,sgDataOrder,sgDataSearch,sgDataCategoryAll,sgDataProduct,sgDataCheckout,sgDataReviews,addedToCartProduct,product};
|
package/tests/helperTest.js
DELETED
|
@@ -1,14 +0,0 @@
|
|
|
1
|
-
/* eslint global-require: "off" */import chai from'chai';import mochaJsdom from'mocha-jsdom';var expect=chai.expect;describe('SGLink helper',function(){var SGLink;mochaJsdom();before(function(){window.SGEvent={};// eslint-disable-next-line prefer-destructuring
|
|
2
|
-
SGLink=require("../helpers/helper").SGLink;});it('should handle regular links',function(){var source='http://testshop.shopgate.com/item/abc123?one=123';var link=new SGLink(source);// Check if it ouputs the same url
|
|
3
|
-
expect(link.toString()).to.equal(source);// Update the parameters
|
|
4
|
-
link.setParam('one','321');link.setParam('two','äpfel');expect(link.toString()).to.equal('http://testshop.shopgate.com/item/abc123?one=321&two=%C3%A4pfel');// Remove the params
|
|
5
|
-
link.setParam('one');link.setParam('two');expect(link.toString()).to.equal('http://testshop.shopgate.com/item/abc123');// Add a new param
|
|
6
|
-
link.setParam('three','2342');expect(link.toString()).to.equal('http://testshop.shopgate.com/item/abc123?three=2342');});it('should handle deeplinks',function(){var source='shopgate-1234://item/abc123?one=123';var link=new SGLink(source);// Check if it ouputs the same url
|
|
7
|
-
expect(link.toString()).to.equal(source);// Update the parameters
|
|
8
|
-
link.setParam('one','321');link.setParam('two','äpfel');expect(link.toString()).to.equal('shopgate-1234://item/abc123?one=321&two=%C3%A4pfel');// Remove the params
|
|
9
|
-
link.setParam('one');link.setParam('two');expect(link.toString()).to.equal('shopgate-1234://item/abc123');// Add a new param
|
|
10
|
-
link.setParam('three','2342');expect(link.toString()).to.equal('shopgate-1234://item/abc123?three=2342');});it('should handle push notification links',function(){var source='/item/abc123?one=123';var link=new SGLink(source);// Check if it ouputs the same url
|
|
11
|
-
expect(link.toString()).to.equal(source);// Update the parameters
|
|
12
|
-
link.setParam('one','321');link.setParam('two','äpfel');expect(link.toString()).to.equal('/item/abc123?one=321&two=%C3%A4pfel');// Remove the params
|
|
13
|
-
link.setParam('one');link.setParam('two');expect(link.toString()).to.equal('/item/abc123');// Add a new param
|
|
14
|
-
link.setParam('three','2342');expect(link.toString()).to.equal('/item/abc123?three=2342');});});
|
|
@@ -1,4 +0,0 @@
|
|
|
1
|
-
/**
|
|
2
|
-
* Provide a localstorage mock
|
|
3
|
-
* @returns {*}
|
|
4
|
-
*/var storageMock=function storageMock(){var storage={};return{setItem:function setItem(key,value){storage[key]=value;},getItem:function getItem(key){return key in storage?storage[key]:null;},removeItem:function removeItem(key){delete storage[key];},get length(){return Object.keys(storage).length;},key:function key(i){var keys=Object.keys(storage);return keys[i]||null;}};};export default storageMock;
|
|
@@ -1,25 +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{sgData,sgDataOrder,sgDataSearch,sgDataCheckout,product,addedToCartProduct}from"../data/tracking.testData";var SgTrackingCore=require("../../core/Core")["default"].reset();/**
|
|
2
|
-
* Triggers completedRegistration with data
|
|
3
|
-
* @returns {Object}
|
|
4
|
-
*/export function completedRegistration(){var data=_extends({},sgData,{registrationType:'guest'});SgTrackingCore.track.completedRegistration(data);return data;}/**
|
|
5
|
-
* Triggers viewContent with data
|
|
6
|
-
* @returns {Object}
|
|
7
|
-
*/export function viewContent(){SgTrackingCore.track.viewContent(sgData);return sgData;}/**
|
|
8
|
-
* Triggers addedPaymentInfo with data
|
|
9
|
-
* @returns {Object}
|
|
10
|
-
*/export function addedPaymentInfo(){var data=_extends({},sgData,{paymentMethodAdded:{success:true,name:'Paypal'}});SgTrackingCore.track.addedPaymentInfo(data);return sgData;}/**
|
|
11
|
-
* Triggers purchase with data
|
|
12
|
-
* @returns {Object}
|
|
13
|
-
*/export function purchase(){SgTrackingCore.track.purchase(sgDataOrder);return sgDataOrder;}/**
|
|
14
|
-
* Triggers initiatedCheckout with data
|
|
15
|
-
* @returns {Object}
|
|
16
|
-
*/export function initiatedCheckout(){var data=_extends({},sgDataCheckout,{checkoutType:'paypal_express',quantity:2});SgTrackingCore.track.initiatedCheckout(data);return data;}/**
|
|
17
|
-
* Triggers addToCart with data
|
|
18
|
-
* @returns {Object}
|
|
19
|
-
*/export function addToCart(){SgTrackingCore.track.addToCart(addedToCartProduct);return addedToCartProduct;}/**
|
|
20
|
-
* Triggers addToWishlist with data
|
|
21
|
-
* @returns {Object}
|
|
22
|
-
*/export function addToWishlist(){var data=_extends({},sgData,{favouriteListProducts:[product]});SgTrackingCore.track.addToWishlist(data);return data;}/**
|
|
23
|
-
* Triggers search with data
|
|
24
|
-
* @returns {Object}
|
|
25
|
-
*/export function search(){SgTrackingCore.track.search(sgDataSearch);return sgDataSearch;}
|
package/tests/urlMappingTest.js
DELETED
|
@@ -1,5 +0,0 @@
|
|
|
1
|
-
import chai from'chai';import sgUrlMapper from"../helpers/urlMapping";var expect=chai.expect;var base='http://testshop.shopgate.localdev.cc';var pathLive='/';var pathDevelopment='/php/shopgate/';var pathApp='sg_app_resources/0123456789/';describe('urlMapping',function(){it('should test relative url',function(){expect(sgUrlMapper('/checkout_payment/payment/change_credit_card')["public"]).to.equal('checkout_payment_and_shipping/payment/change_credit_card');});it('should test urls with parameters',function(){var testurl='http://testshop.shopgate.localdev.cc/php/shopgate/register?emos_sid=aaa&emos_vid=aaa&_ga=1.2.3.4__utma=123.123.123&__utmb=123.123.123&__utmc=1.2.3.4&__utmx=-&__utmz=1.2.3.4.5.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&__utmv=-&__utmk=123456#abc';expect(sgUrlMapper(testurl)).to.deep.equal({"public":'register',"private":'register'});var testurlWithAllowedParam='http://testshop.shopgate.localdev.cc/php/shopgate/register?_gaFOO=1&emos_sid=aaa&emos_vid=aaa&allow=me&_ga=1.2.3.4__utma=123.123.123&__utmb=123.123.123&__utmc=1.2.3.4&__utmx=-&__utmz=1.2.3.4.5.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none)&__utmv=-&__utmk=123456#abc';expect(sgUrlMapper(testurlWithAllowedParam)).to.deep.equal({"public":'register?_gaFOO=1&allow=me',"private":'register'});});it('should test cart mapping',function(){// Fake data for empty cart
|
|
2
|
-
var sgDataEmpty={cart:{productsCount:0,products:[]}};expect(sgUrlMapper("".concat(base,"/cart"),sgDataEmpty)["public"]).to.equal('cart_empty');// Fake data for cart with one item
|
|
3
|
-
var sgDataFull={cart:{productsCount:1,products:[{uid:'SG12',parentUid:null,productNumber:'item_number_public-12',name:'Produkt mit 0% MwSt. - §25a',amount:{currency:'EUR',net:'100.00',gross:'100.00',tax:'0.00',taxRate:'0.00'},tags:[],additionalShippingCosts:{perOrder:'0',perUnit:'0'},quantity:'1',stockQuantity:84}]}};expect(sgUrlMapper("".concat(base,"/cart"),sgDataFull)["public"]).to.equal('cart');});it('should test favourite list mappings',function(){// Test empty favourite list
|
|
4
|
-
var sgDataEmpty={favouriteList:[]};expect(sgUrlMapper("".concat(base,"/favourite_list"),sgDataEmpty)["public"]).to.equal('favourite_list_empty');// Test favourite list
|
|
5
|
-
var sgDataFull={favouriteList:{products:[{uid:'SG113',productNumber:'item_number_public-113',name:'Produkt für die Einlösung eines Gutscheins',amount:{currency:'EUR',net:'84.03',gross:'100.00',tax:'15.97',taxRate:'19.00'},tags:[],stockQuantity:51}]}};expect(sgUrlMapper("".concat(base,"/favourite_list"),sgDataFull)["public"]).to.equal('favourite_list');});it('should test one-to-one mappings',function(){var mappingTests=[['payment_success','checkout_success'],['payment_success/1234','checkout_success/1234'],['payment_success/PAYPAL/1234?utm_nooverride=1','checkout_success/1234'],['payment_success/','checkout_success'],['checkout/default','checkout'],['checkout/foo/bar','checkout'],['checkout_payment/foo/bar','checkout_payment_and_shipping/foo/bar'],['checkout_payment','checkout_payment_and_shipping'],['','index']];mappingTests.forEach(function(path){var liveTest=base+pathLive+path[0];var liveAppTest=base+pathLive+pathApp+path[0];var devTest=base+pathDevelopment+path[0];var devAppTest=base+pathDevelopment+pathApp+path[0];expect(sgUrlMapper(liveTest)).to.deep.equal({"public":path[1],"private":path[1]});expect(sgUrlMapper(liveAppTest)).to.deep.equal({"public":path[1],"private":path[1]});expect(sgUrlMapper(devTest)).to.deep.equal({"public":path[1],"private":path[1]});expect(sgUrlMapper(devAppTest)).to.deep.equal({"public":path[1],"private":path[1]});});});it('should test the mapping for simple use cases',function(){var mappingTests=[['index','index'],['checkout_success','checkout_success/12345'],['item','item/5321'],['items','items/5321/1234/134'],['category','category/5321'],['category_show_all_items','category_show_all_items/5321']];mappingTests.forEach(function(path){var liveTest=base+pathLive+path[1];var liveAppTest=base+pathLive+pathApp+path[1];var devTest=base+pathDevelopment+path[1];var devAppTest=base+pathDevelopment+pathApp+path[1];var expectedData={"public":path[1],"private":path[0]};expect(sgUrlMapper(devTest)).to.deep.equal(expectedData);expect(sgUrlMapper(devAppTest)).to.deep.equal(expectedData);expect(sgUrlMapper(liveTest)).to.deep.equal(expectedData);expect(sgUrlMapper(liveAppTest)).to.deep.equal(expectedData);});});});
|