How to use configureServer method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

Run Appium Base Driver automation tests on LambdaTest cloud grid

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

server-specs.js

Source: server-specs.js Github

copy
1// transpile:mocha
2
3import { server, routeConfiguringFunction } from '../..';
4import { configureServer, normalizeBasePath } from '../../lib/express/server';
5import chai from 'chai';
6import chaiAsPromised from 'chai-as-promised';
7import sinon from 'sinon';
8
9
10const should = chai.should();
11chai.use(chaiAsPromised);
12
13function fakeApp () {
14  const app = {
15    use: sinon.spy(),
16    all: sinon.spy(),
17    get: sinon.spy(),
18    post: sinon.spy(),
19    delete: sinon.spy(),
20    totalCount: () => (
21      app.use.callCount + app.all.callCount + app.get.callCount + app.post.callCount +
22      app.delete.callCount
23    )
24  };
25  return app;
26}
27
28function fakePlugin () {
29  return {
30    name: 'fake',
31    newMethodMap: {
32      '/session/:sessionId/fake': {
33        GET: {command: 'fakeGet'},
34        POST: {command: 'fakePost', payloadParams: {required: ['fakeParam']}}
35      },
36    },
37    updatesServer: true,
38    updateServer: (app, httpServer) => {
39      app.updated = true;
40      httpServer.updated = true;
41    }
42  };
43}
44
45function fakeDriver () {
46  return {sessionExists: () => {}, executeCommand: () => {}};
47}
48
49describe('server configuration', function () {
50  it('should actually use the middleware', function () {
51    const app = fakeApp();
52    const configureRoutes = () => {};
53    configureServer({app, addRoutes: configureRoutes});
54    app.use.callCount.should.equal(14);
55    app.all.callCount.should.equal(4);
56  });
57
58  it('should apply new methods in plugins to the standard method map', function () {
59    const app1 = fakeApp();
60    const app2 = fakeApp();
61    const driver = fakeDriver();
62    const addRoutes = routeConfiguringFunction(driver);
63    configureServer({app: app1, addRoutes});
64    configureServer({app: app2, addRoutes, plugins: [fakePlugin()]});
65    app2.totalCount().should.eql(app1.totalCount() + 2);
66  });
67
68  it('should silently reject new methods in plugins if not plain objects', function () {
69    const app1 = fakeApp();
70    const app2 = fakeApp();
71    const driver = fakeDriver();
72    const addRoutes = routeConfiguringFunction(driver);
73    const plugin = fakePlugin();
74    plugin.newMethodMap = [];
75    configureServer({app: app1, addRoutes});
76    configureServer({app: app2, addRoutes, plugins: [plugin]});
77    app2.totalCount().should.eql(app1.totalCount());
78  });
79
80  it('should allow plugins to update the server', async function () {
81    const plugins = [fakePlugin()];
82    const driver = fakeDriver();
83    const _server = await server({
84      routeConfiguringFunction: routeConfiguringFunction(driver),
85      port: 8181,
86      plugins,
87    });
88    try {
89      _server.updated.should.be.true;
90    } finally {
91      await _server.close();
92    }
93  });
94
95  it('should reject if error thrown in configureRoutes parameter', async function () {
96    const configureRoutes = () => {
97      throw new Error('I am Mr. MeeSeeks look at me!');
98    };
99    await server({
100      routeConfiguringFunction: configureRoutes,
101      port: 8181,
102    }).should.be.rejectedWith('MeeSeeks');
103  });
104
105  describe('#normalizeBasePath', function () {
106    it('should throw an error for paths of the wrong type', function () {
107      should.throw(() => {
108        normalizeBasePath(null);
109      });
110      should.throw(() => {
111        normalizeBasePath(1);
112      });
113    });
114    it('should remove trailing slashes', function () {
115      normalizeBasePath('/wd/hub/').should.eql('/wd/hub');
116      normalizeBasePath('/foo/').should.eql('/foo');
117      normalizeBasePath('/').should.eql('');
118    });
119    it('should ensure a leading slash is present', function () {
120      normalizeBasePath('foo').should.eql('/foo');
121      normalizeBasePath('wd/hub').should.eql('/wd/hub');
122      normalizeBasePath('wd/hub/').should.eql('/wd/hub');
123    });
124  });
125});
126
Full Screen

auth.js

Source: auth.js Github

copy
1
2
3'use strict';
4
5var EventEmitter = require( 'events' ).EventEmitter,
6    Promises     = require( 'bluebird' ),
7    mongoose     = Promises.promisifyAll( require( 'mongoose' ) ),
8    auth         = require( '../../lib/auth.js' ),
9    User         = require( '../../lib/models/user' ),
10    AccessToken  = require( '../../lib/models/token' ),
11    tmpId        = mongoose.Types.ObjectId(),
12    usr          = {
13        '_id':       tmpId,
14        'firstName': 'Test',
15        'lastName':  'User',
16        'email':     '[email protected]',
17        'password':  '12345'
18    },
19    user, configureServer;
20
21
22configureServer = function configureServer( options ) {
23    var opts = options || {};
24
25    auth.options( opts )
26        .server();
27};
28
29suite( 'auth()', function () {
30
31    suiteSetup( function ( done ) {
32        return mongoose
33            .connectAsync( 'mongodb://localhost/nlmg_test' )
34            .then( function () {
35                // hash a pw and create a user (assume it works)
36                // really this should be stubbed... but i'm tired :(
37                auth.hashPassword( usr.password )
38                    .then( function ( hash ) {
39                        // create a Test User
40                        return User.createAsync({
41                            'firstName': usr.firstName,
42                            'lastName':  usr.lastName,
43                            'email':     usr.email,
44                            'password':  hash
45                        });
46                    })
47                    .then( function ( userModel ) {
48                        user = userModel;
49                        done();
50                    });
51            });
52    });
53
54    // setup( function ( done ){done();});
55
56    // teardown( function ( done ){done();});
57
58    suiteTeardown( function ( done ) {
59        return mongoose
60            .connection
61            .db
62            .executeDbCommand({
63                dropDatabase: 1
64            },
65            function( err , result ) {
66                return mongoose.connection.close( done );
67            });
68    });
69
70    test( 'inherits from event emitter', function ( done ) {
71        assert.instanceOf( auth, EventEmitter, 'auth module is instance of EventEmitter' );
72        done();
73    });
74
75    test( 'does not configure server more than once', function ( done ) {
76
77        var spy  = sinon.spy( auth , 'configureServer' ),
78            opts = {
79                userModel: User,
80                accessTokenModel: AccessToken
81            };
82
83        // initial call
84        configureServer( opts );
85
86        // testing second call
87        configureServer( opts );
88
89        assert.equal( spy.callCount , 1 , 'Configure method called only once' );
90
91        auth.configureServer.restore();
92        done();
93    });
94
95    test( 'throws error if no AccessToken Model supplied', function ( done ) {
96
97        configureServer();
98        assert.throws( auth.createToken.bind( this ) , Error , 'AccessToken model must be provided to the auth module.' );
99        done();
100    });
101
102    test( 'creates token', function ( done ) {
103        var client = {
104            'id': '9876543210'
105        },
106        opts = {
107            userModel: User,
108            accessTokenModel: AccessToken
109        };
110
111        configureServer( opts );
112
113        auth.createToken( client , usr , null )
114            .then( function ( token ) {
115                return AccessToken.findOneAsync({
116                    'userId': usr._id
117                });
118            })
119            .then( function ( tokenModel ) {
120
121                assert.equal( tokenModel.userId.toString() , usr._id.toString() , 'Token UserId Matches User\'s Id' );
122
123                AccessToken
124                    .count({
125                        'userId': usr._id
126                    },
127                    function ( err , count ) {
128                        assert.notEqual( count , 0 , 'Token count is not 0' );
129                        assert.equal( count , 1 , 'Token count is 1' );
130                        done();
131                    }
132                );
133            })
134            .catch( function ( err ) {
135                console.log( err , '??!?' );
136                assert.ok( false , 'Error creating token' );
137                done();
138            });
139    });
140
141    test( 'exchanges password for token' , function ( done ) {
142        var client = {
143            id: 'Shoptology.wut.wut'
144        },
145        opts = {
146            userModel: User,
147            accessTokenModel: AccessToken
148        };
149
150        configureServer( opts );
151
152        auth.exchangePassword( client , usr.email , usr.password , null )
153            .then( function ( token ) {
154                assert.isDefined( token , 'Token was exchanged' );
155
156                done();
157            });
158    });
159
160    test( 'does not exchanges password for token when user not found' , function ( done ) {
161        var client = {
162            id: 'Shoptology.wut.wut'
163        },
164        opts = {
165            userModel: User,
166            accessTokenModel: AccessToken
167        };
168
169        configureServer( opts );
170
171        auth.exchangePassword( client , 'foo' , 'foo' , null )
172            .then( function ( token ) {
173                assert.isUndefined( token , 'Token was not exchanged' );
174            })
175            .catch( function ( e ) {
176                assert.equal( e.message , 'A user was not found with the given username/password.' );
177
178                done();
179            });
180    });
181
182    test( 'hashPassword' , function ( done ) {
183        var t = auth.hashPassword( usr.password )
184            .then( function ( hash ) {
185                assert.instanceOf( t , Promises , 'Method is a Promise' );
186                assert.isDefined( hash , 'hashPassword hashes password' );
187
188                done();
189            })
190            .catch( function ( e ) {
191                done( e );
192            });
193    });
194
195    test( 'checkPassword should verify passwords match' , function ( done ) {
196        var success = auth.checkPassword( usr.password , user.password )
197            .then( function ( match ) {
198                assert.instanceOf( success , Promises , 'Method is a Promise' );
199                assert.isDefined( match , 'method returns result of password match' );
200                assert.ok( match , 'passwords match' );
201
202                done();
203            })
204            .catch( function ( e ) {
205                done( e );
206            });
207    });
208
209
210
211    test( 'checkPassword should fail if passwords don\'t match' , function ( done ) {
212        var fail = auth.checkPassword( '3ojb23rj' , user.password )
213            .then( function ( match ) {
214                assert.instanceOf( fail , Promises , 'Method is a Promise' );
215                assert.isDefined( match , 'method returns result of password match' );
216                assert.notOk( match , 'passwords don\'t match' );
217
218                done();
219            })
220            .catch( function ( e ) {
221                done( e );
222            });
223    });
224});
225
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 Base Driver 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)