How to use deleteSession method in Appium

Best JavaScript code snippet using appium

Run Appium automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

testDeleteSession.js

Source: testDeleteSession.js Github

copy
1var test = require('tape')
2var init = require('./helpers/init.js')
3
4test('deleteSession() can be called without a callback', function (t) {
5	t.plan(2)
6	t.doesNotThrow(function () {
7		init().sessionState.deleteSession(null)
8	})
9	t.doesNotThrow(function () {
10		init().sessionState.deleteSession('wheee')
11	})
12})
13
14test('deleteSession() calls back with a decent error message if a bad session id is passed', function (t) {
15	t.plan(2)
16
17	init().sessionState.deleteSession(null, function (err) {
18		t.ok(err)
19		t.ok(/session ?id/i.test(err.message))
20		t.end()
21	})
22})
23
24test('deleteSession() works as expected', function(t) {
25	var sessionId = 'LOLThisIsAFakeSessionId'
26	var now = new Date().getTime().toString()
27
28	var initialState = init()
29	var ss = initialState.sessionState
30	var sdb = initialState.sessionsDb
31
32	t.plan(9)
33
34	ss.deleteSession(sessionId, function (err) { //not yet authenticated
35		t.ifError(err)
36
37		sdb.put(sessionId, now, function (err) { //authenticate
38			t.ifError(err)
39
40			sdb.get(sessionId, function (err, time) { //make sure 'put' worked
41				t.ifError(err)
42				t.equal(time, now, 'times match')
43
44				ss.deleteSession(sessionId, function (err) { //previously authenticated
45					t.ifError(err)
46					t.notOk(err && err.notFound, 'no \'not found\' error')
47
48					sdb.get(sessionId, function (err, time) { //make sure unauth worked
49						t.ok(err, 'error')
50						t.ok(err && err.notFound, '\'not found\' error')
51						t.notOk(time, 'no time came back')
52						t.end()
53					})
54				})
55			})
56		})
57	})
58})
59
Full Screen

AuthStore.js

Source: AuthStore.js Github

copy
1var _currentUser = null;
2var _facebookLogin = false;
3
4Equipt.stores.AuthStore = Object.assign({}, EventEmitter.prototype, StoreSettings, {
5
6	currentUser() {
7        return _currentUser;
8	},
9
10	authenticated() {
11		return this.getSession() && this.getSession().length;
12	},
13
14	setSession(apiKey) {
15		try {
16			localStorage['equiptSession'] = JSON.stringify(apiKey);
17		} catch(err) {
18			this.deleteSession();
19		}
20	},
21
22	getSession() {
23		return localStorage['equiptSession'];
24	},
25
26	deleteSession() {
27		localStorage['equiptSession'] = '';
28		_currentUser = null;
29	},
30
31	getApiKey() {
32		try {
33			return this.getSession() && JSON.parse(this.getSession()).access_token;
34		} catch(err) {
35			this.deleteSession();
36		}
37	},
38
39	getUserId() {
40		try {
41			return this.getSession() && JSON.parse(this.getSession()).user_id;
42		} catch(err) {
43			this.deleteSession();
44		}
45	},
46
47	isFacebookLogin() {
48		return _facebookLogin;
49	}
50
51});
52
53AppDispatcher.register(function(action) {
54  
55  	var {type, data} = action.payload;
56
57  	let AuthStore = Equipt.stores.AuthStore;
58  	
59 	switch(type) {
60		case Constants.NEW_SESSION:
61			_currentUser = data.user;
62			AuthStore.setSession(data.api_key);
63			AuthStore.emitChange();
64		break;
65		case Constants.END_SESSION:
66			AuthStore.deleteSession();
67			AuthStore.emitChange();
68		break;
69		case Constants.FACEBOOK_STATUS_CHANGED:
70			if (data.isLoggedIn) {
71				_facebookLogin 	= true;
72				_currentUser 	= data.user;
73				AuthStore.setSession(data.api_key);
74			} else {
75				_facebookLogin = false;
76				AuthStore.deleteSession();
77			} 
78			AuthStore.emitChange();
79		break;
80	}
81
82});
Full Screen

SessionAction.test.js

Source: SessionAction.test.js Github

copy
1import { expect } from 'chai';
2import * as SessionActionTypes from '../actionTypes/SessionActionTypes';
3import * as actions from './SessionAction';
4
5describe('Session Actions', () => {
6    let deleteSession;
7    let setSessionTimeOut;
8    // describe block for getActiveMenuOnClickAction
9    describe('deleteSession', () => {
10        beforeEach(() => {
11            deleteSession = actions.deleteSession();
12        });
13        it('returns correct action type', () => {
14            expect(deleteSession.type).to.equal(SessionActionTypes.SESSION_DELETE_REQUEST);
15        });
16    });
17
18    describe('setSessionTimeOut', () => {
19        beforeEach(() => {
20            setSessionTimeOut = actions.setSessionTimeOut(true);
21        });
22        it('returns correct action type', () => {
23            expect(setSessionTimeOut.type).to.equal(SessionActionTypes.IS_SESSION_TIMED_OUT);
24        });
25    });
26});
27
Full Screen

deleteSession.test.js

Source: deleteSession.test.js Github

copy
1const { assert } = require('chai');
2const deleteSession = require('../../../lib/deleteSession');
3
4const req = { session: {} };
5const reqEmpty = { session: {} };
6describe('Data session', () => {
7  describe(' delete all data ', () => {
8    beforeEach(() => {
9      req.session = {
10        'lived-abroad': true,
11        'lived-abroad-countries': true,
12        'lived-abroad-countries-details': true,
13        'worked-abroad': true,
14        'worked-abroad-countries': true,
15        'worked-abroad-countries-details': true,
16        'marital-select': true,
17        'marital-date-married': true,
18        'marital-partner-married': true,
19        'contact-details': true,
20        'account-details': true,
21      };
22    });
23
24    it('should delete all marital dates', () => {
25      deleteSession.afterKey(req, 'all');
26      assert.isUndefined(req.session['lived-abroad']);
27      assert.isUndefined(req.session['lived-abroad-countries']);
28      assert.isUndefined(req.session['lived-abroad-countries-details']);
29      assert.isUndefined(req.session['worked-abroad']);
30      assert.isUndefined(req.session['worked-abroad-countries']);
31      assert.isUndefined(req.session['worked-abroad-countries-details']);
32      assert.isUndefined(req.session['marital-select']);
33      assert.isUndefined(req.session['marital-select']);
34      assert.isUndefined(req.session['marital-date-married']);
35      assert.isUndefined(req.session['marital-partner-married']);
36      assert.isUndefined(req.session['contact-details']);
37      assert.isUndefined(req.session['account-details']);
38    });
39
40    it('calling deleteCustomerFormData should also delete all form data', () => {
41      deleteSession.deleteCustomerFormData(req);
42      assert.isUndefined(req.session['lived-abroad']);
43      assert.isUndefined(req.session['lived-abroad-countries']);
44      assert.isUndefined(req.session['lived-abroad-countries-details']);
45      assert.isUndefined(req.session['worked-abroad']);
46      assert.isUndefined(req.session['worked-abroad-countries']);
47      assert.isUndefined(req.session['worked-abroad-countries-details']);
48      assert.isUndefined(req.session['marital-select']);
49      assert.isUndefined(req.session['marital-select']);
50      assert.isUndefined(req.session['marital-date-married']);
51      assert.isUndefined(req.session['marital-partner-married']);
52      assert.isUndefined(req.session['contact-details']);
53      assert.isUndefined(req.session['account-details']);
54    });
55  });
56
57  describe(' deletePartnerDate ', () => {
58    beforeEach(() => {
59      req.session = {
60        'marital-date-married': true,
61        'marital-date-civil': true,
62        'marital-date-widowed': true,
63        'marital-date-divorced': true,
64        'marital-date-dissolved': true,
65      };
66    });
67
68    it('should delete all marital dates', () => {
69      deleteSession.deletePartnerDate(req);
70      assert.isUndefined(req.session['marital-date-married']);
71      assert.isUndefined(req.session['marital-date-civil']);
72      assert.isUndefined(req.session['marital-date-widowed']);
73      assert.isUndefined(req.session['marital-date-divorced']);
74      assert.isUndefined(req.session['marital-date-dissolved']);
75    });
76
77    it('should return empty session', () => {
78      deleteSession.deletePartnerDate(reqEmpty);
79      assert.equal(Object.keys(reqEmpty.session).length, 0);
80    });
81  });
82
83  describe(' deletePartnerDetails ', () => {
84    beforeEach(() => {
85      req.session = {
86        'marital-partner-married': true,
87        'marital-partner-civil': true,
88        'marital-partner-widowed': true,
89        'marital-partner-divorced': true,
90        'marital-partner-dissolved': true,
91      };
92    });
93
94    it('should delete all marital partner details', () => {
95      deleteSession.deletePartnerDetails(req);
96      assert.isUndefined(req.session['marital-partner-married']);
97      assert.isUndefined(req.session['marital-partner-civil']);
98      assert.isUndefined(req.session['marital-partner-widowed']);
99      assert.isUndefined(req.session['marital-partner-divorced']);
100      assert.isUndefined(req.session['marital-partner-dissolved']);
101    });
102
103    it('should return empty session', () => {
104      deleteSession.deletePartnerDetails(reqEmpty);
105      assert.equal(Object.keys(reqEmpty.session).length, 0);
106    });
107  });
108
109  describe(' deletePartnerStatus ', () => {
110    it('should return empty session', () => {
111      deleteSession.deletePartnerStatus(reqEmpty);
112      assert.equal(Object.keys(reqEmpty.session).length, 0);
113    });
114  });
115
116  describe(' deleteContact ', () => {
117    it('should return empty session', () => {
118      deleteSession.deleteContact(reqEmpty);
119      assert.equal(Object.keys(reqEmpty.session).length, 0);
120    });
121  });
122});
123
Full Screen

changesEnquiries.js

Source: changesEnquiries.js Github

copy
1const domain = require('../lib/urlExtract');
2const deleteSession = require('../lib/deleteSession');
3const dataStore = require('../lib/dataStore');
4const keyDetailsHelper = require('../lib/keyDetailsHelper');
5
6function checkAwardDetailsNotInSession(req) {
7  return !req.session.searchedNino;
8}
9
10function stopRestrictedServiceOrigin(req) {
11  const referrer = req.get('Referrer') || '';
12  const stopRestrictiveConditions = ['search-result', 'changes-and-enquiries', 'tasks'];
13  return stopRestrictiveConditions.some((el) => referrer.includes(el));
14}
15function redirectWhenNotInSession(req, res, log) {
16  log.info(`Redirect - user not in session - ${req.method} ${req.fullUrl}`);
17  res.redirect('/find-someone');
18}
19
20module.exports = (log) => (req, res, next) => {
21  if (req.fullUrl === '/find-someone') {
22    if (stopRestrictedServiceOrigin(req)) {
23      dataStore.save(req, 'origin', 'full-service');
24    } else if (dataStore.get(req, 'origin') === null) {
25      dataStore.save(req, 'origin', 'restricted-service');
26    }
27    res.locals.restrictedService = true;
28    res.locals.origin = dataStore.get(req, 'origin');
29    res.locals.activeTab = 'change-and-enquiries';
30    next();
31  } else if (req.url.includes('find-someone/search-result')) {
32    if (checkAwardDetailsNotInSession(req)) {
33      redirectWhenNotInSession(req, res, log);
34    } else {
35      next();
36    }
37  } else if (req.url.includes('find-someone')) {
38    res.locals.restrictedService = true;
39    res.locals.origin = dataStore.get(req, 'origin');
40    next();
41  } else if (req.url.includes('changes-and-enquiries')) {
42    res.locals.restrictedService = true;
43    res.locals.origin = dataStore.get(req, 'origin');
44    const awardDetails = dataStore.get(req, 'awardDetails');
45    if (awardDetails !== undefined) {
46      res.locals.keyDetails = keyDetailsHelper.formatter(awardDetails);
47    }
48    if (checkAwardDetailsNotInSession(req)) {
49      redirectWhenNotInSession(req, res, log);
50    } else if (req.url.includes('death') || req.url.includes('marital-details')) {
51      if (domain.extract(req.headers.referer) === req.hostname) {
52        next();
53      } else {
54        log.info(`Security redirect - user agent failed to match - ${req.method} ${req.fullUrl}`);
55        deleteSession.deleteSessionBySection(req, 'marital');
56        deleteSession.deleteDeathDetail(req);
57        res.redirect('/changes-and-enquiries/personal');
58      }
59    } else {
60      next();
61    }
62    if (!req.url.includes('death') && !req.url.includes('deferral')) {
63      deleteSession.deleteSessionBySection(req, 'stop-state-pension');
64    }
65    if (!req.url.includes('death')) {
66      deleteSession.deleteDeathDetail(req);
67      deleteSession.deleteSessionBySection(req, 'death-payee-details-updated');
68      deleteSession.deleteSessionBySection(req, 'death-payment-details');
69    }
70    if (!req.url.includes('deferral')) {
71      deleteSession.deleteSessionBySection(req, 'deferral');
72    }
73    if (!req.url.includes('marital-details/')) {
74      deleteSession.deleteSessionBySection(req, 'marital');
75    }
76    if (!req.url.includes('manual-payment')) {
77      deleteSession.deleteSessionBySection(req, 'manual-payment');
78    }
79  } else {
80    next();
81  }
82};
83
Full Screen

Accelerate Your Automation Test Cycles With LambdaTest

Leverage LambdaTest’s cloud-based platform to execute your automation tests in parallel and trim down your test execution time significantly. Your first 100 automation testing minutes are on us.

Try LambdaTest

Run JavaScript Tests on LambdaTest Cloud Grid

Execute automation tests with Appium on a cloud-based Grid of 3000+ real browsers and operating systems for both web and mobile applications.

Test now for Free
LambdaTestX

We use cookies to give you the best experience. Cookies help to provide a more personalized experience and relevant advertising for you, and web analytics for us. Learn More in our Cookies policy, Privacy & Terms of service

Allow Cookie
Sarah

I hope you find the best code examples for your project.

If you want to accelerate automated browser testing, try LambdaTest. Your first 100 automation testing minutes are FREE.

Sarah Elson (Product & Growth Lead)