Best JavaScript code snippet using cypress
processUserReply.js
Source:processUserReply.js
...54 case 'car_wash_date':55 switch (req.body.Body){56 case '1':57 case 'Now':58 Requests.updateRequest(req.body.WaId, {when: 'Now'}, 'car_wash_requests')59 return {current_step: 'car_amount', previous_step: 'car_wash_date'};60 case '2':61 Requests.updateRequest(req.body.WaId, {when: 'In 30 minutes'}, 'car_wash_requests')62 return {current_step: 'car_amount', previous_step: 'car_wash_date'};63 case '3':64 Requests.updateRequest(req.body.WaId, {when: 'In 1 hour'}, 'car_wash_requests')65 return {current_step: 'car_amount', previous_step: 'car_wash_date'};66 default:67 return false;68 } 69 case 'car_amount':70 switch (req.body.Body){71 case '1':72 Requests.updateRequest(req.body.WaId, {car_amount: 'One car'}, 'car_wash_requests')73 return {current_step: 'car_wash_type', previous_step: 'car_amount'};74 case '2':75 Requests.updateRequest(req.body.WaId, {car_amount: 'Two cars'}, 'car_wash_requests')76 return {current_step: 'car_wash_type', previous_step: 'car_amount'};77 case '3':78 Requests.updateRequest(req.body.WaId, {car_amount: 'Three cars'}, 'car_wash_requests')79 return {current_step: 'car_wash_type', previous_step: 'car_amount'};80 case '4':81 Requests.updateRequest(req.body.WaId, {car_amount: 'Four cars'}, 'car_wash_requests')82 return {current_step: 'car_wash_type', previous_step: 'car_amount'};83 case '5':84 Requests.updateRequest(req.body.WaId, {car_amount: 'Five cars'}, 'car_wash_requests')85 return {current_step: 'car_wash_type', previous_step: 'car_amount'};86 default:87 return false;88 }89 case 'car_wash_type':90 switch (req.body.Body){91 case '1':92 Requests.updateRequest(req.body.WaId, {wash_type: 'Outside only'}, 'car_wash_requests')93 return {current_step: 'car_location', previous_step: 'car_wash_type'}94 case '2':95 Requests.updateRequest(req.body.WaId, {wash_type: 'Inside and outside'}, 'car_wash_requests')96 return {current_step: 'car_location', previous_step: 'car_wash_type'}97 default:98 return false;99 }100 101 case 'car_location':102 if(req.body.Latitude && req.body.Longitude){103 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'car_wash_requests')104 return {current_step: 'car_payment_type', previous_step: 'car_location'};105 }else{106 return false107 }108 109 case 'car_payment_type':110 111 switch (req.body.Body){112 case '1':113 Requests.updateRequest(req.body.WaId, {payment_type: 'Online'}, 'car_wash_requests')114 return {current_step: 'car_wash_payment_link', previous_step: 'car_payment_type'};115 116 case '2':117 Requests.updateRequest(req.body.WaId, {payment_type: 'Cash'}, 'car_wash_requests')118 return {current_step: 'car_find_runner', previous_step: 'car_payment_type'};119 default:120 return false;121 }122 case 'car_find_runner':123 console.log('FINDING RUNNER')124 125 case 'car_wash_payment_link':126 console.log('GENERATING PAYMENT LINK')127 128 129 /**130 * LAUNDRY========================================131 */132 case 'laundry_date':133 134 switch (req.body.Body){135 case '1':136 Requests.updateRequest(req.body.WaId, {when: 'Now'}, 'laundry_requests')137 return {current_step: 'laundry_amount', previous_step: 'laundry_date'};138 139 case '2':140 Requests.updateRequest(req.body.WaId, {when: 'In 30 minutes'}, 'laundry_requests')141 return {current_step: 'laundry_amount', previous_step: 'laundry_date'};142 case '3':143 Requests.updateRequest(req.body.WaId, {when: 'In 1 hour'}, 'laundry_requests')144 return {current_step: 'laundry_amount', previous_step: 'laundry_date'};145 default:146 return false;147 }148 149 case 'laundry_amount':150 151 switch (req.body.Body){152 case '1':153 Requests.updateRequest(req.body.WaId, {baskets: 1}, 'laundry_requests')154 return {current_step: 'laundry_type', previous_step: 'laundry_amount'};155 156 case '2':157 Requests.updateRequest(req.body.WaId, {baskets: 2}, 'laundry_requests')158 return {current_step: 'laundry_type', previous_step: 'laundry_amount'};159 case '3':160 Requests.updateRequest(req.body.WaId, {baskets: 3}, 'laundry_requests')161 return {current_step: 'laundry_type', previous_step: 'laundry_amount'};162 case '4':163 Requests.updateRequest(req.body.WaId, {baskets: 4}, 'laundry_requests')164 return {current_step: 'laundry_type', previous_step: 'laundry_amount'};165 case '5':166 Requests.updateRequest(req.body.WaId, {baskets: 5}, 'laundry_requests')167 return {current_step: 'laundry_type', previous_step: 'laundry_amount'};168 default:169 return false;170 }171 172 case 'laundry_type':173 174 switch (req.body.Body){175 case '1':176 Requests.updateRequest(req.body.WaId, {type: 'Washing Only'}, 'laundry_requests')177 return {current_step: 'laundry_location', previous_step: 'laundry_type'};178 179 case '2':180 Requests.updateRequest(req.body.WaId, {type: 'Washing And Ironing'}, 'laundry_requests')181 return {current_step: 'laundry_location', previous_step: 'laundry_type'};182 default:183 return false;184 }185 186 case 'laundry_location':187 if(req.body.Latitude && req.body.Longitude){188 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'laundry_requests')189 return {current_step: 'laundry_payment_type', previous_step: 'laundry_location'};190 }else{191 return false192 } 193 case 'laundry_payment_type':194 switch (req.body.Body){195 case '1':196 Requests.updateRequest(req.body.WaId, {payment_type: 'Online'}, 'laundry_requests')197 return {current_step: 'laundry_find_runner', previous_step: 'laundry_payment_type'};198 199 case '2':200 Requests.updateRequest(req.body.WaId, {payment_type: 'Cash'}, 'laundry_requests')201 return {current_step: 'laundry_find_runner', previous_step: 'laundry_payment_type'};202 default:203 return false;204 }205 case 'car_find_runner':206 console.log('FINDING RUNNER')207 case 'landry_payment_link':208 console.log('GENERATING PAYMENT LINK')209 /**210 * CLEANING========================================211 */212 213 case 'cleaning_date':214 switch (req.body.Body){215 case '1':216 217 Requests.updateRequest(req.body.WaId, {when: 'Now'}, 'cleaning_requests')218 return {current_step: 'cleaning_hours', previous_step: 'cleaning_date'};219 220 case '2':221 Requests.updateRequest(req.body.WaId, {hours: 'In 30 minutes'}, 'cleaning_requests')222 return {current_step: 'cleaning_hours', previous_step: 'cleaning_date'};223 case '3':224 Requests.updateRequest(req.body.WaId, {when: 'In 1 hour'}, 'cleaning_requests')225 return {current_step: 'cleaning_hours', previous_step: 'cleaning_date'};226 }227 case 'cleaning_hours':228 switch (req.body.Body){229 case '1':230 Requests.updateRequest(req.body.WaId, {hours: 1}, 'cleaning_requests')231 return {current_step: 'cleaning_location', previous_step: 'cleaning_hours'};232 233 case '2':234 Requests.updateRequest(req.body.WaId, {hours: 2}, 'cleaning_requests')235 return {current_step: 'cleaning_location', previous_step: 'cleaning_hours'};236 case '3':237 Requests.updateRequest(req.body.WaId, {hours: 3}, 'cleaning_requests')238 return {current_step: 'cleaning_location', previous_step: 'cleaning_hours'};239 case '4':240 Requests.updateRequest(req.body.WaId, {hours: 4}, 'cleaning_requests')241 return {current_step: 'cleaning_location', previous_step: 'cleaning_hours'};242 case '5':243 Requests.updateRequest(req.body.WaId, {hours: 5}, 'cleaning_requests')244 return {current_step: 'cleaning_location', previous_step: 'cleaning_hours'};245 }246 case 'cleaning_location':247 if(req.body.Latitude && req.body.Longitude){248 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'cleaning_requests')249 return {current_step: 'cleaning_payment_type', previous_step: 'cleaning_location'};250 }else{251 return false252 }253 254 case 'cleaning_payment_type':255 switch (req.body.Body){256 case '1':257 Requests.updateRequest(req.body.WaId, {payment_type: 'Online'}, 'cleaning_requests')258 return {current_step: 'cleaning_payment_link', previous_step: 'cleaning_payment_type'};259 260 case '2':261 Requests.updateRequest(req.body.WaId, {payment_type: 'Cash'}, 'cleaning_requests')262 return {current_step: 'cleaning_find_runner', previous_step: 'cleaning_payment_type'};263 default:264 return false;265 }266 267 case 'cleaning_find_runner':268 console.log('FINDING RUNNER')269 case 'cleaning_payment_link':270 console.log('GENERATING PAYMENT LINK')271 /**272 * GARDENING========================================273 */ 274 case 'gardening_date':275 switch (req.body.Body){276 case '1':277 Requests.updateRequest(req.body.WaId, {when: 'Now'}, 'gardening_requests')278 return {current_step: 'gardening_yard_type', previous_step: 'gardening_date'};279 280 case '2':281 Requests.updateRequest(req.body.WaId, {when: 'In 30 minutes'}, 'gardening_requests')282 return {current_step: 'gardening_yard_type', previous_step: 'gardening_date'};283 case '3':284 Requests.updateRequest(req.body.WaId, {when: 'In 1 hour'}, 'gardening_requests')285 return {current_step: 'gardening_yard_type', previous_step: 'gardening_date'};286 }287 case 'gardening_yard_type':288 switch (req.body.Body){289 case '1':290 Requests.updateRequest(req.body.WaId, {yard_type: 'Township yard'}, 'gardening_requests')291 return {current_step: 'gardening_grass', previous_step: 'gardening_yard_type'};292 293 case '2':294 Requests.updateRequest(req.body.WaId, {yard_type: 'Surbub yard'}, 'gardening_requests')295 return {current_step: 'gardening_grass', previous_step: 'gardening_yard_type'};296 }297 case 'gardening_grass':298 switch (req.body.Body){299 case '1':300 Requests.updateRequest(req.body.WaId, {grass_cut: true}, 'gardening_requests')301 return {current_step: 'gardening_location', previous_step: 'gardening_grass'};302 303 case '2':304 Requests.updateRequest(req.body.WaId, {grass_cut: false}, 'gardening_requests')305 return {current_step: 'gardening_payment_type', previous_step: 'gardening_grass'};306 }307 case 'gardening_payment_type':308 switch (req.body.Body){309 case '1':310 Requests.updateRequest(req.body.WaId, {payment_type: 'Online'}, 'gardening_requests')311 return {current_step: 'gardening_payment_link', previous_step: 'gardening_payment_type'};312 313 case '2':314 Requests.updateRequest(req.body.WaId, {payment_type: 'Cash'}, 'gardening_requests')315 return {current_step: 'gardening_find_runner', previous_step: 'gardening_payment_type'};316 default:317 return false;318 }319 case 'gardening_location':320 if(req.body.Latitude && req.body.Longitude){321 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'gardening_requests')322 return {current_step: 'gardening_payment_type', previous_step: 'gardening_location'};323 }else{324 return false325 }326 case 'gardening_find_runner':327 console.log('FINDING RUNNER')328 case 'gardening_payment_link':329 console.log('GENERATING PAYMENT LINK')330 /**331 * DELIVERY========================================332 */ 333 case 'delivery_date':334 switch (req.body.Body){335 case '1':336 Requests.updateRequest(req.body.WaId, {when: 'Now'}, 'delivery_requests')337 return {current_step: 'delivery_need', previous_step: 'delivery_date'};338 339 case '2':340 Requests.updateRequest(req.body.WaId, {when: 'In 30 minutes'}, 'delivery_requests')341 return {current_step: 'delivery_need', previous_step: 'delivery_date'};342 case '3':343 Requests.updateRequest(req.body.WaId, {when: 'In 1 hour'}, 'delivery_requests')344 return {current_step: 'delivery_need', previous_step: 'delivery_date'};345 }346 case 'delivery_need':347 switch (req.body.Body){348 case '1':349 Requests.updateRequest(req.body.WaId, {needs: 'person'}, 'delivery_requests')350 return {current_step: 'delivery_pickup_location', previous_step: 'delivery_need'};351 352 case '2':353 Requests.updateRequest(req.body.WaId, {needs: 'private car'}, 'delivery_requests')354 return {current_step: 'delivery_pickup_location', previous_step: 'delivery_need'};355 case '3':356 Requests.updateRequest(req.body.WaId, {needs: 'normal bakkie'}, 'delivery_requests')357 return {current_step: 'delivery_pickup_location', previous_step: 'delivery_need'};358 case '4':359 Requests.updateRequest(req.body.WaId, {needs: 'big bakkie'}, 'delivery_requests')360 return {current_step: 'delivery_pickup_location', previous_step: 'delivery_need'};361 }362 case 'delivery_pickup_location':363 if(req.body.Latitude && req.body.Longitude){364 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'delivery_requests')365 return {current_step: 'delivery_location', previous_step: 'delivery_pickup_location'};366 }else{367 return false368 }369 case 'delivery_location':370 if(req.body.Latitude && req.body.Longitude){371 Requests.updateRequest(req.body.WaId, {location: {long: req.body.Longitude, lat: req.body.Latitude}}, 'delivery_requests')372 return {current_step: 'delivery_payment_type', previous_step: 'delivery_location'};373 }else{374 return false375 }376 case 'delivery_payment_type':377 switch (req.body.Body){378 379 case '1':380 Requests.updateRequest(req.body.WaId, {payment_type: 'Online'}, 'delivery_requests')381 return {current_step: 'delivery_payment_link', previous_step: 'delivery_payment_type'};382 383 case '2':384 Requests.updateRequest(req.body.WaId, {payment_type: 'Cash'}, 'delivery_requests')385 return {current_step: 'delivery_find_runner', previous_step: 'delivery_payment_type'};386 }387 case 'delivery_find_runner':388 console.log('FINDING RUNNER')389 case 'delivery_payment_link':390 console.log('GENERATING PAYMENT LINK')391 default:392 393 return {};394 }395}...
house.js
Source:house.js
1const config = require('../config/api-config.json');2const ShWadeAPI = require('../../../../houseAPI/shwadeAPI');3let houseAPI = new ShWadeAPI(config.houseAPIorigin);4// house modes enumeration5const HouseMode = Object.freeze({ 6 LONGTERM_STANDBY : 0,7 PRESENCE_MODE : 1, 8 SHORTTERM_STANDBY : 29});10// Returns current house status11async function GetHouseStatus() 12{13 return houseAPI.getStatus();14}15// Change house presence mode16async function SetMode(newMode)17{18 let updateRequest = new HouseState().gotoMode(newMode).updateRequest;19 return houseAPI.updateStatus(updateRequest);20}21// Creates update request for typical house statuses or actions22class HouseState 23{24 updateRequest = new Object();25 gotoMode(toMode)26 {27 if (this.updateRequest.config === undefined) 28 this.updateRequest.config = new Object();29 if (this.updateRequest.config.heating === undefined)30 this.updateRequest.config.heating = new Object();31 if (this.updateRequest.oneWireStatus === undefined)32 this.updateRequest.oneWireStatus = new Object();33 if (this.updateRequest.oneWireStatus.switches === undefined)34 this.updateRequest.oneWireStatus.switches = new Object();35 switch(toMode)36 {37 case HouseMode.PRESENCE_MODE:38 // to presence39 this.updateRequest.config.modeDescription = 'Presence mode';40 this.updateRequest.config.modeId = HouseMode.PRESENCE_MODE;41 42 this.updateRequest.oneWireStatus.switches.ultrasonicSwitch = 0;43 this.updateRequest.oneWireStatus.switches.mainsSwitch = 1;44 this.updateRequest.config.heating.saunaFloorTemp = 28.0;45 this.openShutters(1).openShutters(2);46 break;47 48 case HouseMode.LONGTERM_STANDBY:49 // to longterm standby50 this.updateRequest.config.modeDescription = 'Long standby';51 this.updateRequest.config.modeId = HouseMode.LONGTERM_STANDBY;52 53 this.updateRequest.oneWireStatus.switches.streetLight250 = 0;54 this.updateRequest.oneWireStatus.switches.ultrasonicSwitch = 1;55 this.updateRequest.oneWireStatus.switches.mainsSwitch = 0;56 this.updateRequest.oneWireStatus.switches.fenceLight = 0;57 this.updateRequest.config.heating.saunaFloorTemp = 5.0;58 this.allLightsOff().closeShutters(1).closeShutters(2);59 break;60 61 case HouseMode.SHORTTERM_STANDBY:62 // to shorterm standby63 this.updateRequest.config.modeDescription = 'Short standby';64 this.updateRequest.config.modeId = HouseMode.SHORTTERM_STANDBY;65 66 this.updateRequest.oneWireStatus.switches.streetLight250 = 0;67 this.updateRequest.oneWireStatus.switches.ultrasonicSwitch = 1;68 this.updateRequest.oneWireStatus.switches.mainsSwitch = 1;69 this.updateRequest.config.heating.saunaFloorTemp = 20.0;70 this.allLightsOff().closeShutters(1);71 break;72 }73 return this;74 }75 allLightsOff()76 {77 if (this.updateRequest.zigbee === undefined) 78 this.updateRequest.zigbee = new Object();79 if (this.updateRequest.zigbee.switches === undefined)80 this.updateRequest.zigbee.switches = new Object();81 this.updateRequest.zigbee.switches.balconyLight = 0;82 this.updateRequest.zigbee.switches.streetLight150 = 0;83 this.updateRequest.zigbee.switches.kitchenOverheadsLight = 0;84 this.updateRequest.zigbee.switches.stairwayLight = 0;85 this.updateRequest.zigbee.switches.pantryOverheadsLight = 0;86 this.updateRequest.zigbee.switches.hallwayOverheadsLight = 0;87 this.updateRequest.zigbee.switches.hallwayTambourOverheadsLight = 0;88 this.updateRequest.zigbee.switches.porchOverheadsLight = 0;89 this.updateRequest.zigbee.switches.hall1OverheadsMainLight = 0;90 this.updateRequest.zigbee.switches.hall1OverheadsExtraLight = 0;91 this.updateRequest.zigbee.switches.alyaCabinetOverheadsLight = 0;92 this.updateRequest.zigbee.switches.dressingRoomOverheadsLight = 0;93 this.updateRequest.zigbee.switches.ourBedroomOverheadsLight = 0;94 this.updateRequest.zigbee.switches.smallChildrenRoomOverheadsLight = 0;95 this.updateRequest.zigbee.switches.colivingTambourOverheadsLight = 0;96 this.updateRequest.zigbee.switches.colivingOverheadsLight = 0;97 this.updateRequest.zigbee.switches.biggerChildrenRoomOverheadsLight1 = 0;98 this.updateRequest.zigbee.switches.biggerChildrenRoomOverheadsLight2 = 0;99 this.updateRequest.zigbee.switches.hall2OverheadsLight = 0;100 this.updateRequest.zigbee.switches.sashaOverheadsLight = 0;101 this.updateRequest.zigbee.switches.sashaTambourOverheadsLight = 0;102 this.updateRequest.zigbee.switches.bathroom2OverheadsLight = 0;103 this.updateRequest.zigbee.switches.boilerRoomOverheadsLight = 0;104 this.updateRequest.zigbee.switches.saunaOverheadsLight = 0;105 this.updateRequest.zigbee.switches.saunaUnderLight = 0;106 this.updateRequest.zigbee.switches.bathroom1OverheadsLight = 0;107 this.updateRequest.zigbee.switches.denisCabinetOverheadsLight = 0;108 109 return this;110 }111 closeShutters(floor)112 {113 this.changeShutters(floor, 0);114 return this;115 }116 openShutters(floor)117 {118 this.changeShutters(floor, 1);119 return this;120 }121 changeShutters(floor, state)122 {123 if (floor == 1 || floor == 2)124 {125 if (this.updateRequest.shutters === undefined)126 this.updateRequest.shutters = new Object();127 switch(floor)128 {129 case 1:130 if (this.updateRequest.shutters.F1 === undefined)131 this.updateRequest.shutters.F1 = new Object();132 this.updateRequest.shutters.F1.W1 = state;133 this.updateRequest.shutters.F1.W2 = state;134 this.updateRequest.shutters.F1.W3 = state;135 this.updateRequest.shutters.F1.W4 = state;136 this.updateRequest.shutters.F1.W5 = state;137 this.updateRequest.shutters.F1.W6 = state;138 this.updateRequest.shutters.F1.W7 = state;139 break;140 case 2:141 if (this.updateRequest.shutters.F2 === undefined)142 this.updateRequest.shutters.F2 = new Object();143 this.updateRequest.shutters.F2.W1 = state;144 this.updateRequest.shutters.F2.W2 = state;145 this.updateRequest.shutters.F2.W3 = state;146 this.updateRequest.shutters.F2.W4 = state;147 this.updateRequest.shutters.F2.W5 = state;148 this.updateRequest.shutters.F2.W6 = state;149 this.updateRequest.shutters.F2.W7 = state;150 this.updateRequest.shutters.F2.W8 = state;151 this.updateRequest.shutters.F2.W9 = state;152 break;153 }154 }155 return this;156 }157};158if (typeof exports !== 'undefined')159{160 exports.GetHouseStatus = GetHouseStatus;161 exports.SetMode = SetMode;162 exports.HouseMode = HouseMode;163 exports.HouseState = HouseState;...
index.js
Source:index.js
...197 fetchRequestDetail: (id) => {198 dispatch(requestDetail(id));199 },200 fetchUpdateRequest: (requestId, data) => {201 dispatch(updateRequest(requestId, data));202 }203 }204}...
RequestItem.js
Source:RequestItem.js
...32 deleteRequest(id).then(res =>{33 console.log(res)34 })35 }36 updateRequest(data){37 const {updateRequest,request} = this.props;38 updateRequest(request._id,data).then(res =>{39 console.log(res);40 })41 }42 _renderInfo(){43 const {type,request} = this.props;44 let title;45 46 title =(47 <div className="d-flex request-item-title">48 <div clasName="title-text">Reques for : {request.created_for.name}</div>49 <div className="dept-info">{'('} Dept : {request.created_for.department_id.name} { ')'}</div>50 </div>51 )52 53 return title;54 }55 _renderUpdateTime(){56 const {type,request} = this.props;57 let text;58 let date = moment(new Date(request.updated_on)).format('DD MMM YY')59 if(type === 'approved'){60 text = `Approved on : ${date}`61 }else if(type === 'rejected'){62 text = `Rejected On : ${date}`63 }64 return (65 <div className="request-item-footer">66 {text} 67 </div>68 )69 }70 _renderOption(){71 const {type,request,user} = this.props;72 const user_id = user.id;73 let options;74 if(type === 'pending'){75 options = (76 <DropdownItem onClick={this.deleteRequest}>Delete</DropdownItem>77 );78 }else if(type === 'approved'){79 }else if(type === 'incoming-request'){80 console.log(user_id);81 console.log(request.created_for._id)82 if(request.created_for._id == user_id){83 options = (84 <div>85 <DropdownItem onClick={()=> this.updateRequest({status:'approved'})}>Approve</DropdownItem>86 <DropdownItem onClick={() => this.updateRequest({status:'rejected'})}>Reject</DropdownItem>87 </div>88 );89 }else{90 return null;91 }92 93 }94 return type === 'pending' || type === 'incoming-request' ? (95 <Dropdown isOpen={this.state.dropdownOpen} toggle={this.toggle}>96 <DropdownToggle tag="span" className="common-pointer">97 <i class="material-icons">more_vert</i>98 </DropdownToggle>99 <DropdownMenu right>100 {options}...
state.js
Source:state.js
1var page = undefined;2 var pageStack = new Array();3 var tag = undefined;4 var controlState = {5 oil1: { control: 'Stop', state: "On" },6 oil2: { control: 'Stop', state: "On" },7 feed1: { control: 'Stop', state: "Off" },8 feed2: { control: 'Stop', state: "Off" },9 circ1: { control: 'Stop', state: "Off" },10 circ2: { control: 'Stop', state: "Off" }11 };12 function SwitchPage(target) {13 if (page != target) {14 let prev = document.getElementById(page);15 if (prev != undefined)16 prev.style.display = "none";17 let next = document.getElementById(target);18 next.style.display = "block";19 //hide back button on main page20 let backelement = document.getElementById("backbutton");21 backelement.style.display = (target === "main") ? "none" : "block";22 page = target;23 }24 StateRefresh();25 }26 function Navigate(target, newtag) {27 if (page != target) {28 let prevobject =29 {30 p: page,31 t: tag32 };33 tag = newtag;34 pageStack.push(prevobject);35 SwitchPage(target);36 }37 }38 function NavigateBack() {39 if (pageStack.length > 0) {40 let prev = pageStack.pop();41 tag = prev.t;42 SwitchPage(prev.p);43 }44 }45 function ParseAndUpdate(responce) {46 let data = JSON.parse(responce);47 controlState=data;48 StateRefresh();49 }50 var pageUrl="BoilerControl.json";51 function request_update(id, command) {52 var params = JSON.stringify({"id": id, "command": command});53 var xhr = new XMLHttpRequest();54 xhr.open('POST', pageUrl, true);55 xhr.setRequestHeader("Content-Type", "application/json");56 xhr.send(params);57 xhr.onreadystatechange = function () {58 if (xhr.readyState == 4 && xhr.status == 200) {59 cParseAndUpdate(updateRequest.responseText);60 }61 }62 }63 var updateRequest;64 function request_periodical_update() {65 if (!updateRequest) {66 updateRequest = new XMLHttpRequest();67 updateRequest.onreadystatechange = function () {68 if (updateRequest.readyState == 4) {69 if (updateRequest.status == 200) {70 ParseAndUpdate(updateRequest.responseText);71 }72 }73 }74 }75 if (updateRequest.readyState == 4 || updateRequest.readyState == 0) {76 updateRequest.open('GET', pageUrl, true);77 updateRequest.send(null);78 }79 }80 function StateRefresh() {81 let tag = window.tag;82 let pageref = document.getElementById(page);83 switch (page) {84 case "pumpControl": {85 let inputs = pageref.getElementsByTagName('a');86 let control = controlState[tag].control;87 for (item of inputs) {88 let classname = (item.id == control) ? "togglebuttonset" : "togglebutton"89 item.setAttribute("class", classname);90 }91 } break;92 case "oilpumpState":93 case "feedpumpState":94 case "circpumpState": {95 let inputs = pageref.getElementsByTagName('*');96 for (item of inputs) {97 let dataname = item.getAttribute('data-name');98 let datahint = item.getAttribute('data-hint');99 if (datahint != undefined && dataname != undefined) {100 let pumpstate = controlState[dataname];101 let value = pumpstate[datahint];102 item.innerHTML = value;103 }104 }105 }106 break;107 }108 }109 function SwitchPump(to) {110 let tag = window.tag;111 controlState[tag].control = to;112 request_update(tag,to);113 StateRefresh();...
UpdateRequest.test.js
Source:UpdateRequest.test.js
1const isEqual = require('lodash/isEqual');2const UpdateRequest = require('./UpdateRequest');3const Update = require('./Update');4const originalFindOneMethod = UpdateRequest.findOne;5let lastUpdateRequestMock;6const findOneMethodMock = (criteria, fields, options) => {7 const areCriteriaValid = isEqual(criteria, {});8 const areFieldsValid = isEqual(fields, { dateTime: true });9 const areOptionsValid = isEqual(options, { sort: { _id: -1 } });10 if (areCriteriaValid && areFieldsValid && areOptionsValid) {11 return Promise.resolve(lastUpdateRequestMock);12 }13 return Promise.resolve('UpdateRequest.findOne called with invalid params');14};15describe('UpdateRequest.loadNewest', () => {16 beforeEach(() => {17 UpdateRequest.findOne = findOneMethodMock;18 });19 it('should return a promise', () => {20 expect(UpdateRequest.loadNewest()).toBeInstanceOf(Promise);21 });22 it('should resolve a promise with ' +23 'UpdateRequest.findOne (called with proper params) output', async () => {24 expect.assertions(2);25 lastUpdateRequestMock = 'database response';26 expect(await UpdateRequest.loadNewest()).toBe('database response');27 lastUpdateRequestMock = 'another database response';28 expect(await UpdateRequest.loadNewest()).toBe('another database response');29 });30 afterEach(() => {31 UpdateRequest.find = originalFindOneMethod;32 });33});34describe('UpdateRequest.canBeProcessed', () => {35 let lastUpdateMock;36 const originalUpdateFindOneMethod = Update.findOne;37 beforeEach(() => {38 lastUpdateMock = null;39 Update.findOne = (criteria, fields) => {40 if (fields === undefined || isEqual(fields, { dateTime: true })) {41 return Promise.resolve(lastUpdateMock);42 }43 return Promise.resolve('Update.findOne called with invalid params');44 };45 UpdateRequest.findOne = findOneMethodMock;46 });47 it('should return a promise', () => {48 lastUpdateRequestMock = null;49 expect(UpdateRequest.canBeProcessed()).toBeInstanceOf(Promise);50 });51 it('should resolve a promsie with true if timetable has not been updated yet', async () => {52 expect.assertions(1);53 const result = await UpdateRequest.canBeProcessed();54 expect(result).toBe(true);55 });56 it('should resolve a promsie with false ' +57 'if timetable has been updated late enough', async () => {58 expect.assertions(1);59 lastUpdateMock = { dateTime: Date.now() };60 const result = await UpdateRequest.canBeProcessed();61 expect(result).toBe(false);62 });63 it('should resolve a promsie with true if update has not been requested yet', async () => {64 expect.assertions(1);65 lastUpdateMock = { dateTime: 1000 };66 lastUpdateRequestMock = null;67 const result = await UpdateRequest.canBeProcessed();68 expect(result).toBe(true);69 });70 it('should resolve a promsie with true ' +71 'if update has been requested enough time ago', async () => {72 expect.assertions(1);73 lastUpdateMock = { dateTime: 1000 };74 lastUpdateRequestMock = { dateTime: 1000 };75 const result = await UpdateRequest.canBeProcessed();76 expect(result).toBe(true);77 });78 it('should resolve a promsie with false if update has been requested too early', async () => {79 expect.assertions(1);80 lastUpdateMock = { dateTime: 1000 };81 lastUpdateRequestMock = { dateTime: Date.now() };82 const result = await UpdateRequest.canBeProcessed();83 expect(result).toBe(false);84 });85 afterEach(() => {86 Update.findOne = originalUpdateFindOneMethod;87 UpdateRequest.findOne = originalFindOneMethod;88 });...
timetableTimeProtection.test.js
Source:timetableTimeProtection.test.js
1const timeProtectionGuard = require('./timetableTimeProtection');2const ErrorResponse = require('../errors/ErrorResponse');3const UpdateRequest = require('../../models/timetable/UpdateRequest');4jest.mock('../../utils/logger', () => require('../../mocks/utils/logger'));5describe('GraphQL timetableTimeProtection guard', () => {6 const originalCanBeProcessedMethod = UpdateRequest.canBeProcessed;7 const originalCreateMethod = UpdateRequest.create;8 let spy;9 beforeEach(() => {10 UpdateRequest.canBeProcessed = () => Promise.resolve(false);11 UpdateRequest.create = () => Promise.resolve();12 });13 it('should not throw any error if request can be processed', async () => {14 UpdateRequest.canBeProcessed = () => Promise.resolve(true);15 await timeProtectionGuard({}, {});16 });17 it('should throw valid ErrorResponse if request cannot be processed', async () => {18 expect.assertions(1);19 const expectedError = new ErrorResponse(20 'your request cannot be processed, because of time limit', 40321 );22 try {23 await timeProtectionGuard({}, {});24 } catch (err) {25 expect(err).toEqual(expectedError);26 }27 });28 it('should create a record in DB if request cannot be processed', async () => {29 expect.assertions(2);30 const args = { phoneID: 'XYZ' };31 spy = jest.spyOn(UpdateRequest, 'create');32 try {33 await timeProtectionGuard({}, args);34 } catch (err) {35 expect(spy).toHaveBeenCalledTimes(1);36 expect(spy).toHaveBeenCalledWith({37 requestorPhoneID: args.phoneID,38 timetableUpdated: false39 });40 }41 });42 it('should throw valid ErrorResponse if UpdateRequest.canBeProcessed ' +43 'has thrown an exception ', async () => {44 expect.assertions(1);45 UpdateRequest.canBeProcessed = () => Promise.reject(new Error('error message'));46 try {47 await timeProtectionGuard({}, {});48 } catch (err) {49 expect(err).toEqual(new ErrorResponse('something went wrong', 500));50 }51 });52 afterAll(() => {53 UpdateRequest.canBeProcessed = originalCanBeProcessedMethod;54 UpdateRequest.create = originalCreateMethod;55 if (spy) {56 spy.mockReset();57 spy.mockRestore();58 }59 });...
orderBad.js
Source:orderBad.js
1import cloneDeep from 'lodash.clonedeep';2import {API_URL_ORDER} from "../support/util";3const baseRequest = {4 "pilotes": 5,5 "delivery": {6 "street": "Poco Mas Drive",7 "postcode": "24205",8 "city": "Frisco",9 "country": "TX"10 },11 "customer": {12 "email": "EufrasioAlmanzaCepeda@armyspy.com",13 "firstName": "Eufrasio Almanza",14 "lastName": "Cepeda",15 "telephone": "214-474-0425"16 }17};18const randomStr = (length) => {19 let a,b;20 for(a = '', b = 36; a.length < length;) a += (Math.random() * b | 0).toString(b);21 return a;22}23describe('Orders API', () => {24 it('Not create invalid pilotes', () => {25 let updateRequest = cloneDeep(baseRequest);26 updateRequest.pilotes = 2;27 cy.request({ method: 'POST', url : `${API_URL_ORDER}`, failOnStatusCode: false, body: updateRequest }).then((response) => {28 expect(response.status).to.eq(400);29 })30 })31 it('Not create invalid postcode', () => {32 let updateRequest = cloneDeep(baseRequest);33 updateRequest.delivery.postcode = 2;34 cy.request({ method: 'POST', url : `${API_URL_ORDER}`, failOnStatusCode: false, body: updateRequest }).then((response) => {35 expect(response.status).to.eq(400);36 })37 })38 it('Not create invalid email', () => {39 let updateRequest = cloneDeep(baseRequest);40 updateRequest.customer.email = "invalid_mail";41 cy.request({ method: 'POST', url : `${API_URL_ORDER}`, failOnStatusCode: false, body: updateRequest }).then((response) => {42 expect(response.status).to.eq(400);43 })44 })45 it('Not create invalid too long', () => {46 let updateRequest = cloneDeep(baseRequest);47 updateRequest.customer.firstName = randomStr(101);48 cy.request({ method: 'POST', url : `${API_URL_ORDER}`, failOnStatusCode: false, body: updateRequest }).then((response) => {49 expect(response.status).to.eq(400);50 })51 })...
Using AI Code Generation
1Cypress.Commands.add('updateRequest', (url, method, body, headers) => {2 return cy.request({3 })4})5cy.updateRequest(url, method, body, headers).then((res) => {6 expect(res.status).to.eq(200)7 expect(res.body).to.have.property('status', 'success')8})9cy.updateRequest(url, method, body, headers).then((res) => {10 expect(res.status).to.eq(200)11 expect(res.body).to.have.property('status', 'success')12})13cy.updateRequest(url, method, body, headers).then((res) => {14 expect(res.status).to.eq(200)15 expect(res.body).to.have.property('status', 'success')16})17cy.updateRequest(url, method, body, headers).then((res) => {18 expect(res.status).to.eq(200)19 expect(res.body).to.have.property('status', 'success')20})21cy.updateRequest(url, method, body, headers).then((res) => {22 expect(res.status).to.eq(200)23 expect(res.body).to.have.property('status', 'success')24})25cy.updateRequest(url, method, body, headers).then((res) => {26 expect(res.status).to.eq(200)27 expect(res.body).to.have.property('status', 'success')28})29cy.updateRequest(url, method, body, headers).then((res) => {30 expect(res.status).to.eq(200)31 expect(res.body).to.have.property('status', 'success')32})33cy.updateRequest(url, method, body, headers).then((res) => {34 expect(res.status).to.eq(200)35 expect(res.body).to.have.property('status', 'success')36})37cy.updateRequest(url, method, body, headers).then((res) => {38 expect(res.status).to.eq(200
Using AI Code Generation
1cy.updateRequest({2 body: {3 }4}).then((response) => {5 expect(response.status).to.eq(200)6 expect(response.body).to.have.property('id', 1)7 expect(response.body).to.have.property('title', 'foo')8 expect(response.body).to.have.property('body', 'bar')9 expect(response.body).to.have.property('userId', 1)10})11Cypress.Commands.add('updateRequest', (options) => {12 return cy.request({13 })14})15import './commands'16describe('Test', () => {17 it('Test', () => {18 cy.get('#id').type('1')19 cy.get('#title').type('foo')20 cy.get('#body').type('bar')21 cy.get('#userId').type('1')22 cy.get('#updateBtn').click()23 cy.get('#id').should('have.value', '1')24 cy.get('#title').should('have.value', 'foo')25 cy.get('#body').should('have.value', 'bar')26 cy.get('#userId').should('have.value', '1')27 })28})
Using AI Code Generation
1describe('My First Test', function() {2 it('Does not do much!', function() {3 }).then((response) => {4 expect(response.body).to.have.property('title', 'foo')5 })6 })7})8{9}10{11}12{13}14{15}16{17}18{19}20{21}
Using AI Code Generation
1cy.updateRequest({2 body: {3 }4}).then((response) => {5 expect(response.status).to.eq(200)6 expect(response.body).to.have.property('id', 1)7 expect(response.body).to.have.property('title', 'foo')8 expect(response.body).to.have.property('body', 'bar')9 expect(response.body).to.have.property('userId', 1)10})11Cypress.Commands.add('updateRequest', (options) => {12 return cy.request({13 })14})15import './commands'16describe('Test', () => {17 it('Test', () => {18 cy.get('#id').type('1')19 cy.get('#title').type('foo')20 cy.get('#body').type('bar')21 cy.get('#userId').type('1')22 cy.get('#updateBtn').click()23 cy.get('#id').should('have.value', '1')24 cy.get('#title').should('have.value', 'foo')25 cy.get('#body').should('have.value', 'bar')26 cy.get('#userId').should('have.value', '1')27 })28})
Using AI Code Generation
1describe('Test', () => {2 it('Te', () => {3 important: fale4 })5 })6}7cy.updateRequest('/user/1', {name: 'test'}).then((response) => {8 expect(response.status).to.eq(200)9 expect(response.body.name).to.eq('test')10})11cy.updateRequest('/user/1', {name: 'test'}).then((response) => {12 expect(response.status).to.eq(200)13 expect(response.body.name).to.eq('test')14})15cy.updateRequest('/user/1', {name: 'test'}).then((response) => {16 expect(response.status).to.eq(200)17 expect(response.body.name).to.eq('test')18})19Cypress.Commands.add('updateRequest', (url, body) => {20 return cy.request({21 })22})23cy.updateRequest('/user/1', {name: 'test'}).then((response) => {24 expect(response.status).to.eq(200)25 expect(response.body.name).to.eq('test')26})27cy.updateRequest('/user/1', {name: 'test'}).then((response) => {28 expect(response.status).to.eq(200)29 expect(response.body.name).to.eq('test')30})31cy.updateRequest('/user/1', {name: 'test'}).then((response) => {32 expect(response.status).to.eq(200)33 expect(response.body.name).to.eq('test')34})35cy.updateRequest('/user/1', {name: 'test'}).then((response) => {36 expect(response.status).to.eq(200)37 expect(response.body.name).to.eq('test')38})39cy.updateRequest('/user/1', {name: 'test'}).then((response) => {40 expect(response.status).to.eq(200)41 expect(response.body.name).to.eq('test')42})43cy.updateRequest('/user/1', {name: 'test'}).then((response) => {
Using AI Code Generation
1Cypress.Commands.add('updateRequest', () => {2 cy.window().then(win => {3 const token = win.localStorage.getItem('token');4 cy.log(token);5 cy.intercept('POST', '/graphql', req => {6 req.headers['authorization'] = `Bearer ${token}`;7 });8 });9});10Cypress.Commands.add('updateRequest', () => {11 cy.window().then(win => {12 const token = win.localStorage.getItem('token');13 cy.log(token);14 cy.intercept('POST', '/graphql', req => {15 req.headers['authorization'] = `Bearer ${token}`;16 });17 });18});19Cypress.Commands.add('updateRequest', () => {20 cy.window().then(win => {21 const token = win.localStorage.getItem('token');22 cy.log(token);23 cy.intercept('POST', '/graphql', req => {24 req.headers['authorization'] = `Bearer ${token}`;25 });26 });27});28Cypress.Commands.add('updateRequest', () => {29 cy.window().then(win => {30 const token = win.localStorage.getItem('token');31 cy.log(token);32 cy.intercept('POST', '/graphql', req => {33 req.headers['authorization'] = `Bearer ${token}`;34 });35 });36});
Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!