Best JavaScript code snippet using appium-base-driver
SessionManager.js
Source:SessionManager.js
...14 this.intiSessionHeartbeatProcessor();15 //test16 /*17 try{18 this.createSession(56565);19 this.createSession(56565);20 this.createSession(56565);21 this.createSession(56565);22 this.createSession(56565);23 this.createSession(56565);24 this.createSession(56565);25 }catch(er){26 debug(er);27 } */ 28 //debug("createSession =====",this._data);29 }, 30 _data : {}, //ä¿åä¼è¯31 _bind : {}, //ç»å®å¯¹è±¡32 /** ä¼è¯åºæ¬æä½ ***/33 //æ¥æ¾ä¼è¯34 getSession : function(id){35 return this._data[id];36 },37 //å建ä¼è¯38 createSession : function(bid){
...
login-page.js
Source:login-page.js
1function hasTranslationChanged(state, alias, previous) {2 return state.translations[alias] !== undefined && state.translations[alias] !== previous;3}4class LoginPage extends Component {5 static styleSheet = '/static/components/login-page.css';6 constructor() {7 super();8 this._dispatch = () => {};9 this._texts = {10 activateSessionPlaceholder: '',11 createSessionPlaceholder: '',12 };13 this.render = this.render.bind(this);14 this.mapState = this.mapState.bind(this);15 this.mapDispatch = this.mapDispatch.bind(this);16 }17 mapState(state) {18 if (hasTranslationChanged(state, 'login-page.activate-session.input.placeholder', this._texts.activateSessionPlaceholder)) {19 const activateSessionInput = this.activateSession.querySelector('.input');20 activateSessionInput.setAttribute('placeholder', state.translations['login-page.activate-session.input.placeholder']);21 }22 if (hasTranslationChanged(state, 'login-page.create-session.input.placeholder', this._texts.createSessionPlaceholder)) {23 const emailInput = this.createSession.querySelector('.input');24 emailInput.setAttribute('placeholder', state.translations['login-page.create-session.input.placeholder']);25 }26 }27 mapDispatch(dispatch) {28 this._dispatch = dispatch;29 }30 render() {31 }32 connectedCallback() {33 connectRedux(this.mapState, this.mapDispatch);34 this._dispatch(translationsActions.request('login-page.activate-session.input.placeholder'));35 this._dispatch(translationsActions.request('login-page.create-session.input.placeholder'));36 this.innerHTML += `37 <div class="activateSession hidden">38 <h3>39 <translate-text alias="login-page.activate-session.header"></translate-text>40 </h3>41 <div class="note">42 <translate-text alias="login-page.activate-session.note"></translate-text>43 </div>44 <form class="inline">45 <input type="text" maxlength="6" class="input" />46 <button type="submit" class="button">47 <translate-text alias="login-page.activate-session.button"></translate-text>48 </button>49 </form>50 </div>51 <div class="createSession hidden">52 <h3>53 <translate-text alias="login-page.create-session.header"></translate-text>54 </h3>55 <div class="note">56 <translate-text alias="login-page.create-session.header"></translate-text>57 </div>58 <form class="inline">59 <input type="email" class="input" name="email" />60 <button type="submit" class="button">61 <translate-text alias="login-page.create-session.button"></translate-text>62 </button>63 </form>64 </div>65 `;66 this.activateSession = this.querySelector('.activateSession');67 this.createSession = this.querySelector('.createSession');68 const activateSessionForm = this.activateSession.querySelector('form.inline');69 const createSessionForm = this.createSession.querySelector('form.inline');70 const currentUrl = new URL(location.toString());71 const sessionId = currentUrl.searchParams.get('session');72 if (sessionId) {73 this.activateSession.classList.remove('hidden');74 const activateSessionInput = this.activateSession.querySelector('.input');75 activateSessionForm.addEventListener('submit', e => {76 e.preventDefault();77 e.stopPropagation();78 if (activateSessionInput.value && activateSessionInput.value.length === 6 && /^[A-Z0-9]+$/.test(activateSessionInput.value)) {79 currentUrl.searchParams.set('code', activateSessionInput.value);80 currentUrl.pathname = '/login/email';81 location.href = currentUrl.toString();82 }83 });84 } else {85 this.createSession.classList.remove('hidden');86 const emailInput = this.createSession.querySelector('.input');87 createSessionForm.addEventListener('submit', e => {88 e.preventDefault();89 e.stopPropagation();90 const emailValue = emailInput.value;91 if (emailValue.length > 0 && (!emailValue.checkValidity || emailValue.checkValidity())) {92 const request = new XMLHttpRequest();93 request.onreadystatechange = e => {94 if (request.readyState === 4 && request.status === 200) {95 const loginData = JSON.parse(request.responseText);96 location.href = `/login?session=${loginData.sessionId}`;97 }98 };99 request.onerror = () => {100 };101 request.open("POST", "/api/user", true);102 request.setRequestHeader('Content-Type', 'application/json');103 request.send(JSON.stringify({104 type: 'email',105 value: emailValue106 }));107 }108 });109 }110 }111}...
createSession.test.js
Source:createSession.test.js
...29 this.sinon.restore();30 });31 it('should throw an error if account_type is missing in the request', function(done) {32 let event = testHelper.lambdaEvent();33 this.createSession()(event, {}, (err, data) => {34 let body = JSON.parse(data.body);35 testHelper.check(done, () => {36 expect(err).is.null;37 expect(data.statusCode).to.equal(500);38 expect(body.message).to.equal('missing account_type in request');39 });40 });41 });42 it('should get user from database for traditional account types', function(done) {43 let event = testHelper.lambdaEvent({account_type: 'traditional'});44 this.createSession()(event, {}, (err, data) => {45 let body = JSON.parse(data.body);46 testHelper.check(done, () => {47 assert(this.dbMock.getUser.calledOnce);48 });49 });50 });51 it('should save token for traditional account types', function(done) {52 let event = testHelper.lambdaEvent({account_type: 'traditional'});53 this.createSession()(event, {}, (err, data) => {54 let body = JSON.parse(data.body);55 testHelper.check(done, () => {56 assert(this.dbMock.saveTokens.calledOnce, 'db.saveTokens should be called once');57 expect(err).to.be.null;58 expect(data.statusCode).to.equal(200);59 expect(body.access_token).to.not.be.null;60 expect(body.refresh_token).to.not.be.null;61 expect(body.access_token_expires_in).to.equal(3600);62 });63 });64 });65 it('should return error for unsupported account types', function(done) {66 let event = testHelper.lambdaEvent({account_type: 'instagram'});67 this.createSession()(event, {}, (err, data) => {68 let body = JSON.parse(data.body);69 testHelper.check(done, () => {70 expect(err).to.be.null;71 expect(data.statusCode).to.equal(500);72 expect(body.message).to.equal('unsupported account_type');73 });74 });75 });76 it('should return error for non-existing user', function(done) {77 let event = testHelper.lambdaEvent({account_type: 'traditional'});78 this.createSession(true)(event, {}, (err, data) => {79 let body = JSON.parse(data.body);80 testHelper.check(done, () => {81 expect(err).to.be.null;82 expect(data.statusCode).to.equal(500);83 expect(body.message).to.equal('user not found');84 });85 });86 });...
SelectGame.js
Source:SelectGame.js
1import React from "react";2import PropTypes from "prop-types";3import "./SelectGame.css";4import { Sessions } from "../../../api/sessions";5import { withTracker } from "meteor/react-meteor-data";6import { Meteor } from "meteor/meteor";7class SelectGame extends React.Component {8 constructor( props ) {9 super( props );10 this.createSession = this.createSession.bind( this );11 this.joinSession = this.joinSession.bind( this );12 }13 createSession() {14 let curSession = this.props.sessions;15 curSession = isNaN( curSession ) ? 1 : curSession + 1;16 Meteor.call( "session.create", curSession, this.props.user,17 () => {18 this.props.updateSession( 1, curSession );19 } );20 }21 joinSession() {22 let inputValue = "";23 let self = this;24 let inputRef = React.createRef();25 function join() {26 let sessionID = parseInt( inputValue );27 Meteor.call( "session.join", sessionID, self.props.user,28 ( error ) => {29 if ( !error ) {30 self.props.updateSession( 2, sessionID );31 self.props.closeModal();32 }33 else {34 self.props.showErrorModal( error.error );35 }36 } );37 }38 function handleChange( ev ) {39 inputValue = ev.target.value;40 }41 function onKeyPress( ev ) {42 if ( ev.key === "Enter" ) {43 join();44 }45 }46 this.props.openModal( {47 title: "Join Session",48 body: (49 <div id="session-join-content">50 <input type="number"51 min="1"52 placeholder="Session ID"53 onChange={handleChange}54 ref={inputRef} onKeyPress={onKeyPress}/>55 </div>56 ),57 foot: (58 <div id="session-join-ok-content">59 <button onClick={join}>60 <i className="fas fa-check"/>61 </button>62 </div>63 )64 }, () => {65 inputRef.current.focus();66 } );67 }68 render() {69 return (70 <div id="session-choice-container">71 <div onClick={this.createSession}>72 <h1>Create</h1>73 </div>74 <div onClick={this.joinSession}>75 <h1>Join</h1>76 </div>77 </div>78 );79 }80}81SelectGame.propTypes = {82 user: PropTypes.object,83 sessions: PropTypes.number,84 openModal: PropTypes.func.isRequired,85 closeModal: PropTypes.func.isRequired,86 showErrorModal: PropTypes.func.isRequired,87 updateSession: PropTypes.func.isRequired88};89export default withTracker( () => {90 Meteor.subscribe( "sessions" );91 Meteor.subscribe( "user.info" );92 return {93 sessions: Sessions.find( {} ).count(),94 user: Meteor.user()95 };...
TracksPage.js
Source:TracksPage.js
1import React, { Component } from "react";2import { connect } from "react-redux";3import {4 createPlaylistSession,5 setCollaborative,6} from "../redux/actions/thunk";7import Tracks from "./Tracks";8import SearchPage from "./SearchPage";9import "./TrackPage.css";10import InfoBar from "./InfoBar";11class TracksPage extends Component {12 constructor() {13 super();14 this.state = {15 searchShowing: false,16 refreshList: false,17 removedSong: false,18 };19 this.toggleSearch = this.toggleSearch.bind(this);20 this.createSession = this.createSession.bind(this);21 }22 createSession = () => {23 this.props.createPlaylistSession(24 this.props.activePlaylist.id,25 this.props.userID26 );27 //If the playlist is the owners, make it collaborative then create the session28 if (29 this.props.activePlaylist.owner.id === this.props.userID &&30 !this.props.activePlaylist.collaborative31 ) {32 this.props.setCollaborative(true, this.props.activePlaylist.id);33 }34 };35 //TODO: make a componentdidmount that gets active playlist from the list of playlists based off the id from the URL36 toggleSearch() {37 this.setState({ searchShowing: !this.state.searchShowing });38 }39 render() {40 return (41 <div>42 <InfoBar43 title={this.props.activePlaylist.name}44 isTrackListPage={true}45 backLink="/playlists"46 createSession={this.createSession}47 toggleSearch={this.toggleSearch}48 />49 {this.state.searchShowing ? (50 <SearchPage />51 ) : (52 <Tracks col1Name="Name" col2Name="Artist" />53 )}54 </div>55 );56 }57}58//State is entire state tree59function mapStateToProps(state) {60 return {61 hosted_session: state.session.hosted_session62 ? state.session.hosted_session.data63 : null,64 session_code: state.playlists.active_playlist.session65 ? state.playlists.active_playlist.session.joinCode66 : "",67 activePlaylist: state.playlists.active_playlist,68 can_add:69 state.playlists.active_playlist.collaborative ||70 state.playlists.active_playlist.owner.id === state.user.data.id, //Only let them add songs if playlist is collab or theirs71 playlistId: window.location.pathname.split("/").pop(), //Grab playlist ID from URL72 deviceId: state.webplayer.deviceId,73 userID: state.user.data ? state.user.data.id : null,74 };75}76const mapDispatchToProps = {77 createPlaylistSession,78 setCollaborative,79};...
user-application.js
Source:user-application.js
...12 if (userEmail) {13 throw new BadRequestError('El usuario ya existe');14 }15 await this._context.userRepository.add(user);16 return this.createSession(user)17 }18 async login(userlogin) {19 const { email, password } = userlogin;20 const user = await this._context.userRepository.findByEmail(email)21 if (!user) {22 throw new NotFoundError('El usuario no existe');23 }24 const isCorrectPassword = UserService.isCorrectPassword(password, user.password);25 if (!isCorrectPassword) {26 throw new BadRequestError('Usuario/contraseña incorrecta');27 }28 return this.createSession(user);29 }30 async loginGoogle(userlogin) {31 const { email } = userlogin;32 userlogin.provider = "Google"33 let user = await this._context.userRepository.findByEmail(email)34 if (!user) {35 user = UserService.create(userlogin);36 await this._context.userRepository.add(user);37 return this.createSession(user);38 }39 const { provider } = user40 if (provider !== "Google") {41 throw new BadRequestError('El usuario ya existe');42 }43 return this.createSession(user)44 }45 async createSession(user) {46 const { name, email, surname, role } = user;47 const access_token = await jwt.sign({48 name,49 email,50 surname,51 role52 }, process.env.JWT_SECRET, { algorithm: 'HS256' })53 const session = SessionService.create({54 name,55 email,56 surname,57 role,...
SignInPage.js
Source:SignInPage.js
1// Import with { ... } is a named import which allows2// multiple exports from one file. However, each import3// must be referenced by name.4import React, { Component } from "react";5import { Session } from "../Requests";6// Examples of named exports:7// export class Component { ... }8// export const Component = ...9class SignInPage extends Component {10 constructor(props) {11 super(props);12 this.state = {13 errors: []14 };15 this.createSession = this.createSession.bind(this);16 }17 createSession(event) {18 event.preventDefault();19 const { currentTarget: form } = event;20 // const form = event.currentTarget;21 const formData = new FormData(form);22 Session.create({23 email: formData.get("email"),24 password: formData.get("password")25 }).then(data => {26 if (data.status === 404) {27 this.setState({28 errors: [{ message: "Wrong email or password" }]29 });30 } else {31 this.props.history.push(`/`);32 this.props.onSignIn();33 }34 });35 }36 render() {37 const { errors } = this.state;38 return (39 <main>40 <h1>Sign In</h1>41 {/* form.addEventListener('submit', this.createSession) */}42 <form onSubmit={this.createSession}>43 {errors.length > 0 ? (44 <div className="FormErrors">45 {errors.map(e => e.message).join(", ")}46 </div>47 ) : null}48 <div>49 <label htmlFor="email">Email</label> <br />50 <input type="email" name="email" id="email" />51 </div>52 <div>53 <label htmlFor="password">Password</label> <br />54 <input type="password" name="password" id="password" />55 </div>56 <input type="submit" value="Sign In" />57 </form>58 </main>59 );60 }61}...
index.js
Source:index.js
1import React, { Component } from "react";2import { Session } from "../requests";3class SignInPage extends Component {4 constructor(props) {5 super(props);6 this.state = {7 errors: [],8 };9 this.createSession = this.createSession.bind(this);10 }11 createSession(event) {12 event.preventDefault();13 const form = event.currentTarget;14 const formData = new FormData(form);15 // submit a request to sessions#create16 Session.create({17 email: formData.get("email"),18 password: formData.get("password"),19 }).then((data) => {20 if (data.status === 404) {21 this.setState({22 errors: [{ message: "Wrong credentails" }],23 });24 } else {25 this.props.history.push("/");26 }27 });28 }29 render() {30 console.log(this.props);31 const { errors } = this.state;32 return (33 <main className="ui clearing segment Page">34 <h1 className="ui center aligned header">Sign In</h1>35 {errors.length > 0 ? (36 <div className="ui negative message">37 {errors.map((e) => e.message).join(", ")}38 </div>39 ) : null}40 <form className="ui large form" onSubmit={this.createSession}>41 <div className="field">42 <label htmlFor="email">Email</label>43 <input type="email" name="email" id="email" />44 </div>45 <div className="field">46 <label htmlFor="password">Password</label>47 <input type="password" name="password" id="password" />48 </div>49 <input50 className="ui right floated large orange button"51 type="submit"52 value="Sign In"53 />54 </form>55 </main>56 );57 }58}...
Using AI Code Generation
1var wd = require('wd');2driver.init({3}).then(function() {4 return driver.setImplicitWaitTimeout(5000);5}).then(function() {6}).then(function(el) {7 return el.click();8}).then(function() {9}).then(function(el) {10 return el.click();11}).then(function() {12}).then(function(el) {13 return el.click();14}).fin(function() { return driver.quit(); })15 .done();
Using AI Code Generation
1var webdriver = require('selenium-webdriver');2var assert = require('assert');3var test = require('selenium-webdriver/testing');4var appium = require('appium-base-driver');5var server = require('appium-express');6var logger = require('appium-logger').get('Appium');7var path = require('path');8var fs = require('fs');9var _ = require('lodash');10var uuid = require('node-uuid');11var request = require('request');12var express = require('express');13test.describe('Appium Base Driver', function() {14 this.timeout(60000);15 var driver;16 var port = 4723;17 var app = express();18 var server;19 var sessionId;20 var caps = {21 app: path.resolve(__dirname, "selendroid-test-app-0.17.0.apk")22 };23 before(function(done) {24 server = appium.createAppiumBaseDriver(4723);25 server.start();26 done();27 });28 after(function(done) {29 server.stop();30 done();31 });32 test.it('should create a session', function(done) {33 server.createSession(caps).then(function(sessionId) {34 assert.ok(sessionId);35 done();36 }).catch(function(err) {37 done(err);38 });39 });40});41commands.createSession = async function (caps) {42 this.validateDesiredCaps(caps);43 this.caps = _.cloneDeep(caps);44 this.sessionId = uuid.v4();45 this.opts = _.cloneDeep(this.defaultCaps);46 this.opts = _.defaults(this.caps, this.opts);47 this.curContext = this.defaultContext;48 this.contexts = [this.defaultContext];49 this.proxyReqRes = this.jwpProxyActive ? this.jwpProxyAvoid : this.noProxy;50 this.setDeviceDetails();51 await this.startSession();52 await this.startDeviceLogCapture();53 await this.onSessionStart();54 return this.sessionId;55};56commands.createSession = async function (caps) {
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!