All files / test AnalyticsTest.ts

99.5% Statements 200/201
100% Branches 0/0
96.3% Functions 26/27
99.49% Lines 196/197

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 3851x 1x 1x 1x   1x 1x 1x   1x 1x 1x   1x     1x 12x 12x     1x 12x     1x 1x     1x   1x 1x 1x   1x   1x 1x       1x     1x 1x   1x 2x   1x 1x   1x 1x 1x   1x 1x 1x 1x       1x     1x   1x 1x   1x     1x 1x 1x 1x 1x 1x 1x       1x     1x   1x 1x 1x   1x   1x       1x     1x 1x 1x 1x 1x   1x 1x       1x     1x 1x 1x                     1x 1x   1x   1x 1x 1x 1x 1x 1x 1x       1x     1x 1x 1x                   1x 1x   1x 1x   1x 1x 1x 1x 1x       1x     1x 1x 1x 1x                             1x 2x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x   1x   1x     1x       1x     1x 1x 1x 1x 1x                           1x                         1x 2x   1x   1x 1x 1x   1x 1x   1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x 1x       1x     1x 1x 1x             1x           1x 3x   1x 1x   1x 1x 1x 1x       1x     1x 1x 1x 1x                       1x 1x 3x     1x 1x   1x   1x   1x 1x 1x       1x     1x 2x   1x 1x   1x   1x       1x  
import { TestClass } from './TestClass';
import * as sinon from 'sinon';
import Analytics from '../src/Analytics';
import Properties from '../src/properties/Properties';
import { IUser, IEvent, IView, IAction } from '../src/analytics/DataModels';
import { PostChannel } from '@ms/1ds-post-js';
import Autocollector from '../src/analytics/Autocollector';
import { AppInsightsCore, IExtendedTelemetryItem } from '@ms/1ds-core-js';
import { IScreenResolution } from '../src/analytics/InternalDataModels';
import { ActionType } from '../src/Index';
import SessionManager from '../src/properties/SessionManager';
import StorageManager from '../src/properties/StorageManager';
 
export class AnalyticsTest extends TestClass {
    private analytics: Analytics | any;
 
    public testInitialize() {
        this.analytics = new Analytics();
        this.analytics.initialize({ingestionKey: 'xyz'});
    }
 
    public testCleanup() {
        window.localStorage.clear();
    }
 
    public registerTests() {
        this.testCase({
            name: 'Verify setUser calls properties',
            test: () => {
                const propertiesStub = sinon.createStubInstance<Properties>(Properties);
                let calledUser: IUser;
                this.analytics._properties = propertiesStub;
                propertiesStub.setUser.callsFake((arg) => {
                    calledUser = arg;
                });
                (this.analytics as Analytics).setUser({name: 'abc', localId: 'id'});
 
                QUnit.assert.equal(calledUser.name, 'abc' );
                QUnit.assert.equal(calledUser.localId, 'id' );
            }
        });
 
        this.testCase({
            name: 'Verify setUser updates user mapping correctly',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                let event: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    event = arg;
                });
                (this.analytics as Analytics).setUser({localId: 'localId', authId: 'authId'});
                QUnit.assert.equal(event.name, 'usermapping');
                // setting the same user does not send another usermapping event
                event = null;
                (this.analytics as Analytics).setUser({localId: 'localId', authId: 'authId'});
                QUnit.assert.notOk(event);
                // deleting the usermapping storage, then setting the user will send a new usermapping event
                let storageManager = new StorageManager(false);
                storageManager._setProperty('EIMappings', JSON.stringify({}));
                (this.analytics as Analytics).setUser({localId: 'localId', authId: 'authId'});
                QUnit.assert.equal(event.name, 'usermapping');
            }
        });
 
        this.testCase({
            name: 'Verify calling setUser before initialize does not send an event',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                
                this.analytics = new Analytics();
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                let event: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    event = arg;
                });
                this.analytics._user = null;
                this.analytics._sendUserMapping =false;
                (this.analytics as Analytics).setUser({localId: 'localId', authId: 'authId'});
                QUnit.assert.notOk(event);
                QUnit.assert.equal(this.analytics._sendUserMapping, true);
                QUnit.assert.equal(this.analytics._user.localId, 'localId');
                QUnit.assert.equal(this.analytics._user.authId, 'authId');
            }
        });
 
        this.testCase({
            name: 'Verify setProperty calls properties',
            test: () => {
                const propertiesStub = sinon.createStubInstance<Properties>(Properties);
                let calledKvp;
                this.analytics._properties = propertiesStub;
                propertiesStub.setProperty.callsFake((arg1, arg2) => {
                    calledKvp = arg1 + arg2;
                });
                (this.analytics as Analytics).setProperty('key', 'value');
 
                QUnit.assert.equal(calledKvp, 'keyvalue');
            }
        });
 
        this.testCase({
            name: 'Verify teardown calls postchannel and autocollector',
            test: () => {
                const postChannelStub = sinon.createStubInstance<PostChannel>(PostChannel);
                const autocollectorStub = sinon.createStubInstance<Autocollector>(Autocollector);
                this.analytics._postChannel = postChannelStub;
                this.analytics._autoCollector = autocollectorStub;
                (this.analytics as Analytics).teardown();
 
                QUnit.assert.ok(autocollectorStub._removeAllListeners.calledOnce);
                QUnit.assert.ok(postChannelStub.teardown.calledOnce);
            }
        });
 
        this.testCase({
            name: 'Verify trackEvent',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const event: IEvent = {
                    name: 'custom',
                    properties: {
                        'prop1': 'val',
                        'prop2': 10,
                        'prop3': false
                    },
                    version: '1',
                    ingestionKey: 'abc'
                };
                let item: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    item = arg;
                });
                (this.analytics as Analytics).trackEvent(event);
 
                QUnit.assert.equal(item.name, 'custom');
                QUnit.assert.equal(item.iKey, 'abc');
                QUnit.assert.ok(item.time);
                QUnit.assert.equal(item.data['prop1'], 'val');
                QUnit.assert.equal(item.data['prop2'], 10);
                QUnit.assert.equal(item.data['prop3'], false);
                QUnit.assert.equal(item.data['s']['e']['v'], '1');
            }
        });
 
        this.testCase({
            name: 'Verify that custom properties can not start with event. or s. or be less than 3 chars',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const event: IEvent = {
                    name: 'custom',
                    properties: {
                        'Signal.test': 'val',
                        's.test': 10,
                        'ab': 20,
                        'Signal': 'value'
                    }
                };            
                let item: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    item = arg;
                });
                (this.analytics as Analytics).setProperty('Signal.blah', 'blah');
                (this.analytics as Analytics).trackEvent(event);
 
                QUnit.assert.notOk(item.data['Signal.test']);
                QUnit.assert.notOk(item.data['Signal.blah']);
                QUnit.assert.notOk(item.data['s.test']);
                QUnit.assert.notOk(item.data['ab']);
                QUnit.assert.notOk(item.data['Signal']);
            }
        });
 
        this.testCase({
            name: 'Verify trackView',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const date = new Date();
                const view: IView = {
                    name: 'page1',
                    title: 'title',
                    uri: 'uri',
                    referrer: {
                        pageTitle: 'refPage',
                        uri: 'refUri'
                    },
                    viewClass: 'class',
                    timestamp: date,
                    properties: {
                        'prop': 'val'
                    }
                };
                let event: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    event = arg;
                });
                (this.analytics as Analytics).trackView(view);
                const screenInfo: IScreenResolution = this.analytics._autoCollector._getScreenResolution();
 
                QUnit.assert.equal(event.name, 'view');
                QUnit.assert.equal(event.iKey, 'xyz');
                QUnit.assert.equal(event.time, date.toISOString());
                QUnit.assert.equal(event.data['s']['v']['n'], 'page1');
                QUnit.assert.equal(event.data['s']['v']['v'], 'title');
                QUnit.assert.equal(event.data['s']['v']['u'], 'uri');
                QUnit.assert.equal(event.data['s']['v']['c'], 'class');
                QUnit.assert.equal(event.data['s']['v']['h'], screenInfo.h);
                QUnit.assert.equal(event.data['s']['v']['w'], screenInfo.w);
                QUnit.assert.equal(event.data['s']['v']['g'], screenInfo.vH);
                QUnit.assert.equal(event.data['s']['v']['d'], screenInfo.vW);
                QUnit.assert.equal(event.data['s']['v']['o'], screenInfo.cd);
                QUnit.assert.equal(event.data['s']['v']['s'], screenInfo.sR);
                QUnit.assert.equal(event.data['s']['r']['u'], 'refUri');
                QUnit.assert.equal(event.data['s']['r']['p'], 'refPage');
                QUnit.assert.equal(event.data['prop'], 'val');
                // No previous view if there is no ongoing session. First view starts the session.
                QUnit.assert.notOk(event.data['s']['v']['r']); 
 
                (this.analytics as Analytics).trackView(view);
 
                // Second view should log the earlier view events uri as the PreviousView. 
                QUnit.assert.equal(event.data['s']['v']['r'], 'uri'); 
            }
        });
 
        this.testCase({
            name: 'Verify trackAction',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const date1 = new Date();
                const date2 = new Date(date1.getTime() + 10);
                const view: IView = {
                    name: 'page1',
                    title: 'title',
                    uri: 'uri',
                    referrer: {
                        pageTitle: 'refPage',
                        uri: 'refUri'
                    },
                    viewClass: 'class',
                    timestamp: date1,
                    properties: {
                        'prop': 'val'
                    }
                };
                const action: IAction = {
                    name: 'cart',
                    type: ActionType.leftClick,
                    elementId: 'elId',
                    class: 'class',
                    clickCoordinates: '20X12',
                    viewTarget: 'uri2',
                    timestamp: date2,
                    properties: {
                        'prop': 'val'
                    }
                };
                let event: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    event = arg;
                });
                (this.analytics as Analytics).trackView(view);
 
                const sessionManagerStub = sinon.createStubInstance<SessionManager>(SessionManager);
                this.analytics._sessionManager = sessionManagerStub;
                sessionManagerStub._isSessionActive.returns(true);
 
                (this.analytics as Analytics).trackAction(action);
                const screenInfo: IScreenResolution = this.analytics._autoCollector._getScreenResolution();
 
                QUnit.assert.equal(event.name, 'action');
                QUnit.assert.equal(event.iKey, 'xyz');
                QUnit.assert.equal(event.time, date2.toISOString());
                QUnit.assert.equal(event.data['s']['v']['n'], 'page1');
                QUnit.assert.equal(event.data['s']['v']['v'], 'title');
                QUnit.assert.equal(event.data['s']['v']['u'], 'uri');
                QUnit.assert.equal(event.data['s']['v']['c'], 'class');
                QUnit.assert.equal(event.data['s']['v']['h'], screenInfo.h);
                QUnit.assert.equal(event.data['s']['v']['w'], screenInfo.w);
                QUnit.assert.equal(event.data['s']['v']['g'], screenInfo.vH);
                QUnit.assert.equal(event.data['s']['v']['d'], screenInfo.vW);
                QUnit.assert.equal(event.data['s']['v']['o'], screenInfo.cd);
                QUnit.assert.equal(event.data['s']['v']['s'], screenInfo.sR);
                QUnit.assert.equal(event.data['s']['r']['u'], 'refUri');
                QUnit.assert.equal(event.data['s']['r']['p'], 'refPage');
                QUnit.assert.equal(event.data['prop'], 'val');
                QUnit.assert.equal(event.data['s']['t']['n'], 'cart');
                QUnit.assert.equal(event.data['s']['t']['t'], 'LClick');
                QUnit.assert.equal(event.data['s']['t']['m'], 'elId');
                QUnit.assert.equal(event.data['s']['t']['c'], 'class');
                QUnit.assert.equal(event.data['s']['t']['g'], 'uri2');
                QUnit.assert.equal(event.data['s']['t']['o'], true);
                QUnit.assert.equal(event.data['s']['t']['e'], 10);
                QUnit.assert.equal(event.data['s']['k']['c'], '20X12');
            }
        });
 
        this.testCase({
            name: 'Verify localized texts are decoded',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const view: IView = {
                    name: '名字',
                    uri: '页面',
                    referrer: {
                        uri: '前一个页面'
                    },
                };
                const action: IAction = {
                    name: 'cart',
                    type: ActionType.leftClick,
                    viewTarget: '点击页面',
                };
                let event: IExtendedTelemetryItem;
                appInsightsCoreStub.track.callsFake((arg) => {
                    event = arg;
                });
                (this.analytics as Analytics).trackView(view);
                (this.analytics as Analytics).trackAction(action);
 
                QUnit.assert.equal(event.data['s']['v']['n'], '名字');
                QUnit.assert.equal(event.data['s']['v']['u'], '页面');
                QUnit.assert.equal(event.data['s']['r']['u'], '前一个页面');
                QUnit.assert.equal(event.data['s']['t']['g'], '点击页面');
            }
        });
 
        this.testCase({
            name: 'trackAction always sends view event if session is not started',
            test: () => {
                const appInsightsCoreStub = sinon.createStubInstance<AppInsightsCore>(AppInsightsCore);
                this.analytics._applicationInsightsCore = appInsightsCoreStub;
                const date = new Date();
                const action: IAction = {
                    name: 'cart',
                    type: ActionType.leftClick,
                    elementId: 'elId',
                    class: 'class',
                    clickCoordinates: '20X12',
                    viewTarget: 'uri2',
                    timestamp: date,
                    properties: {
                        'prop': 'val'
                    }
                };
                let events: IExtendedTelemetryItem[] = [];
                appInsightsCoreStub.track.callsFake((arg) => {
                    events.push(arg);
                });
                // Log a view to log a view in this session.
                (this.analytics as Analytics).trackView({uri: 'uri'});
                events = [];
                // Clear session key
                window.localStorage.clear();
                // Simulates that the session is over while the user is still on the page but doing nothing then finally clicks something
                (this.analytics as Analytics).trackAction(action);
 
                QUnit.assert.equal(events.length, 2);
                QUnit.assert.equal(events[0].name, 'view');
                QUnit.assert.equal(events[1].name, 'action');
            }
        });
 
        this.testCase({
            name: 'Verify if local storage not availble storage is disabled',
            test: () => {
                var oldMethod = StorageManager._getLocalStorage;
                StorageManager._getLocalStorage = () => null;
 
                this.analytics = new Analytics();
                this.analytics.initialize({ingestionKey: 'xyz'});
 
                QUnit.assert.ok(this.analytics._storageDisabled);
 
                StorageManager._getLocalStorage = oldMethod;
            }
        });
    }
}