How to use CallStart method in Jest

Best JavaScript code snippet using jest

CreateCallRecordSuitelet.js

Source:CreateCallRecordSuitelet.js Github

copy

Full Screen

1// Create a 'journal' (call record) form for an entity.2// 3// It can create both Phone Call and Note records on an entity.4//5// Note form parameters:6//  title=<subject of note>7//  message=<memo contents of note>8//  contactId=<NS id of target record>9//  writeNote=yes10//  optional: recordType=<record type of contact, default is 'entity'>11//12// Phone Call form parameters:13//  title=<subject of call>14//  message=<contents of note>15//  contactId=<NS id of target record>16//  contactType=<type of target record>17//  optional: companyId=<id of company target record is attached to>18//     For contact and employee records, the companyId needs to be specified or the record19//     cannot be attached.20//  startTime=<start time of call, 24 hour format 'HH:mm'>21//  endTime=<end time of call, 24 hour format 'HH:mm'>22//  timeFormat=[0-3] 0=>hh:mm am/pm 1=>HH:mm 2=>hh-mm am/pm 3=>HH-mm23//  optional: phoneNumber=<number involved in call>24//25// This should be installed into NetSuite as a Suitelet with the following26// parameters.27// Script Name: camrivoxCreateCallRecordSuitelet28// Script ID: customscript_camrivox_createcallrecord29// Script Function: camrivoxCreateCallRecordSuitelet30// Deployment Title: camrivoxCreateCallRecordSuitelet (automatic)31// Deployment ID: customdeploy_camrivox_createcallrecord32// Roles: All Roles33// Groups: All Employees34// Execute as admin: No35// Available without login: No3637// Convert a string to a form acceptable as the contents of38// an XML element - any of "'&<> have to be converted to39// entity references40function xmlify(i) {41    if(!i) {42	return '';43    }4445   // Replace ampersands first, as they appear in the46   // other entity references47   var o = i.replace(/&/g,"&amp;");48   o = o.replace(/</g,"&lt;");49   o = o.replace(/>/g,"&gt;");50   o = o.replace(/'/g,"&apos;");51   o = o.replace(/"/g,"&quot;");5253   return o;54}5556function readTime(ts) {57    var time = null;5859    if(ts) {60	var fields = ts.split(':');61	if(fields.length==2) {62	    try {63		time = new Array();64		time[0] = parseInt(fields[0]);65		time[1] = parseInt(fields[1]);66	    } catch(e) {67	    }68	}69    }70    return time;71}7273function formatTime(time,formatIndex) {74    // Ignore the format index for now75    var textTime;7677    var separator = '-';7879    switch(formatIndex) {80    default:81    case 0:82	separator = ':';83    case 2:84	// 12-hour85	if(time[0]>11) {86	    if(time[0]>12) {87		textTime = (time[0]-12)+separator+time[1]+' pm';88	    } else {89		textTime = '12'+separator+time[1]+' pm';90	    }91	} else if(time[0]==0) {92	    textTime = '12'+separator+time[1]+' am';93	} else {94	    textTime = time[0]+separator+time[1]+' am';95	}96	break;97    case 1:98	separator = ':';99    case 3:100	// 24-hour101	textTime = time[0]+separator+time[1];102	break;103    }104    return textTime;105}106107function daysInMonth(month,year) {108    var monthDays = new Array(31,28,31,30,31,30,31,31,30,31,30,31);109110    var d = monthDays[month];111    if(d==28) {112	// February113	if(year%4==0 && (year%100!=0 || year%400==0)) {114	    // Leap year115	    d = 29;116	}117    }118    return d;119}120121function createNoteRecord(title,message,recordId) {122    var result = null;123124    try {125	var newNote = nlapiCreateRecord('note');126127	newNote.setFieldValue('title',title);128129	// For future use: allow the caller to specify the record type.130	// Currently, all the records we deal with are of type 'entity'131	var recordType = request.getParameter('recordType');132	if(!recordType) {133	    recordType = 'entity';134	}135136	newNote.setFieldValue(recordType,recordId);137	138	newNote.setFieldValue('note',message);139140	var noteId = nlapiSubmitRecord(newNote,true);141142	result = "<noteId>"+noteId+"</noteId>";143    } catch(e) {144	result = "<error>Exception: "+xmlify(e)+"</error>";145    }146    return result;147}148149function camrivoxCreateCallRecord(request,response) {150151    response.write("<?xml version='1.0'?><createCallRecord>");152153    var title = request.getParameter('title');154    var message = request.getParameter('message');155156    var writeNote = (request.getParameter('writeNote')!=null);157158    if(title && message) {159160	try {161162	    var contactId = request.getParameter('contactId');163164	    if(writeNote) {165		if(contactId) {166		    response.write(createNoteRecord(title,message,contactId));167		} else {168		    response.write("<error>No contact Id to write note for</error>");169		}170	    } else {171	    172		var callStart = readTime(request.getParameter('callStart'));173		174		if(callStart) {175		    var callEnd = readTime(request.getParameter('callEnd'));176		    // Have to have an end time which is later than the start time177		    if(!callEnd || (callEnd[0]==callStart[0] && callEnd[1]==callStart[1])) {178			callEnd = new Array();179			callEnd[0] = callStart[0];180			callEnd[1] = callStart[1]+1;181			if(callEnd[1]==60) {182			    callEnd[1] = 0;183			    callEnd[0] = callEnd[0]+1;184			    if(callEnd[0]==24) {185				callEnd[0] = 0;186			    }187			}188		    }189190		    var date = new Date();191	    192		    if(callEnd) {193			if(callEnd[0]<callStart[0] ||194			   (callEnd[0]==callStart[0] && callEnd[1]<callStart[1])) {195			    // call ended earlier in the day that it started - so196			    // it must have started the previous day197			    var newDay = date.getDate()-1;198			    var newMonth = date.getMonth();199			    var newYear = date.getFullYear();200			    if(newDay<1) {201				newDay = daysInMonth(newMonth,newYear);202				newMonth = newMonth - 1;203			    204				if(newMonth<0) {205				    newMonth = 11;206				    newYear = newYear - 1;207				}208			    }209			    date = new Date(newYear,newMonth,newDay);210			}211		    }212		}213214		var newCall = nlapiCreateRecord('phonecall');215216		if(date) {217		    newCall.setFieldValue('startdate',nlapiDateToString(date));218		    if(callStart) {219			var timeFormat = 0;220			var timeFormatParam = request.getParameter('timeFormat');221			if(timeFormatParam) {222			    try {223				timeFormat = parseInt(timeFormatParam);224				if(timeFormat<0 || timeFormat>3) {225				    timeFormat = 0;226				}227			    } catch(e) {228			    }229			} 230231			newCall.setFieldValue('timedevent','T');232			newCall.setFieldValue('starttime',formatTime(callStart,timeFormat));233			if(callEnd) {234			    newCall.setFieldValue('endtime',formatTime(callEnd,timeFormat));235			}236		    }237		}238239		// Check for non-compulsory fields240		var phoneNumber = request.getParameter('phoneNumber');241		if(phoneNumber) {242		    newCall.setFieldValue('phone',phoneNumber);243		}244245		var companyId = request.getParameter('companyId');246		var contactType = request.getParameter('contactType');247		if(!companyId) {248		    if(contactId && contactType) {249			if(contactType=='contact' || contactType=='employee') {250251			    var contact = nlapiLoadRecord(contactType,contactId);252			    var companyId = contact.getFieldValue('company');253			    if(companyId) {254				newCall.setFieldValue('contact',contactId);255				newCall.setFieldValue('company',companyId);256			    } else {257				// Without a company Id, the contact ID cannot be set.258				// Add the contact's name to the title259				var firstName = contact.getFieldValue('firstname');260				var lastName = contact.getFieldValue('lastname');261				if(firstName && lastName) {262				    title += ' ('+contactType+' '+firstName+' '+lastName+')';263				}264			    }265			} else {266			    newCall.setFieldValue('company',contactId);267			}268		    }269		} else {270		    newCall.setFieldValue('company',companyId);271		    if(contactId) {272			newCall.setFieldValue('contact',contactId);273		    }274		}275276		newCall.setFieldValue('title',title);277		newCall.setFieldValue('message',message);278		newCall.setFieldValue('status','COMPLETE');279280		var callId = nlapiSubmitRecord(newCall,true);281	    282		response.write("<callRecordId>"+callId+"</callRecordId>");283	    }284285	} catch(e) {286	    response.write("<error>Exception: "+e+"</error>");287	}288    } else {289	response.write("<error>");290	if(!title) {291	    response.write("No title");292	    if(!message) {293		response.write(" or message");294	    }295	} else {296	    response.write("No message");297	}298	response.write(" given</error>");299    }300    response.write("</createCallRecord>");
...

Full Screen

Full Screen

call-card.js

Source:call-card.js Github

copy

Full Screen

1import "./call-card.html";2import moment from "moment/moment";3import { Session } from "meteor/session";4import { ReactiveDict } from "meteor/reactive-dict";5function correctDigits(str) {6  if (str.length < 2) {7    return "0" + str8  } else {9    return str10  }11} 12Template.CallCard.onCreated(function() {13  this.state = new ReactiveDict();14  this.state.setDefault({15    timeElapsed: 016  });17  //   this.state.set('createdAt', moment().toISOString())18  this.autorun(() => {19    this.subscribe("agents.all");20    this.subscribe("Orders.byCallID", this.data.callID);21    const callEnd = Orders.findOne({call_id:this.data.callID, type:'call_ended'})22    callEnd && this.state.set('endedAt', callEnd.createdAt)23    this.state.set('callEnd', callEnd?true:false)24    25    const orderAgent = Orders.findOne({ call_id:this.data.callID,agent: { $exists: true } });26    if (orderAgent) {27      const agentProvidedNumber = orderAgent.agent;28      console.log('agent bio2 : ', agentProvidedNumber)29      const agentDocNumber = agentProvidedNumber.includes("-")?30      agentProvidedNumber.split("-")[2]31      :agentProvidedNumber;32      console.log('agent bio3 : ', agentDocNumber)33      const agent = Agents.findOne({ DocNumber: agentDocNumber });34      this.state.set(35        "agentName",36        '<i class="zmdi zmdi-headset-mic"></i> ' + agentDocNumber37      );38      if (agent) {39           const firstName = agent.FirstName;40      // console.log('agent bio 4 : ', agent.FirstName)41      const lastName = agent.LastName;42      this.state.set(43        "agentName",44        '<i class="zmdi zmdi-headset-mic"></i> ' + firstName + " " + lastName45      );46      }47    }48    const callStart = Orders.findOne({call_id:this.data.callID, type:'call_started'})49    callStart && this.state.set('startedAt', callStart.createdAt)50    this.state.set("ani", `<i class="zmdi zmdi-phone"></i> ${callStart.ani}`);51    this.state.set("source", `<i class="zmdi zmdi-memory"></i> ${callStart.source}`);52    this.state.set("source_version", callStart.source_version);53    Meteor.setInterval(() => {54      let createdAt = this.state.get("createdAt");55      this.state.set("timeElapsed", moment().diff(createdAt, "minutes"));56    }, 60 * 1000);57    FlowRouter.watchPathChange();58    // console.log("report START --> ", Session.get("REPORT_BEGINNING_DATE"));59    // console.log("report end --> ", Session.get("REPORT_ENDING_DATE"));60    this.subscribe(61      "Orders.byDate",62      Session.get("REPORT_BEGINNING_DATE"),63      Session.get("REPORT_ENDING_DATE")64    );65  });66});67Template.CallCard.onRendered(function() {68  const instance = Template.instance();69  instance.state.set(70    "createdAt",71    Orders.findOne({ call_id: instance.data.callID, type: "call_started" })72      .createdAt73  );74  const createdAt = instance.state.get("createdAt");75  this.state.set("timeElapsed", moment().diff(createdAt, "minutes"));76});77Template.CallCard.helpers({78  agentName() {79    const instance = Template.instance();80    return instance.state.get("agentName");81  },82  ani() {83    const instance = Template.instance();84    return instance.state.get("ani");85  },86  audioLink(relativePath) {87    return Meteor.settings.public.recordings_path + relativePath88  },89  callEnd() {90      const instance = Template.instance();91    return instance.state.get("callEnd");92  },93  callStartDate() {94      const instance = Template.instance();95      const callStart = moment(instance.state.get("callStart"))96      return `<i class="zmdi zmdi-calendar"></i> ${callStart.format("DD/MM/YYYY")}`97  },98  callStartTime() {99      const instance = Template.instance();100    const callStart = Orders.findOne({call_id:instance.data.callID, type:'call_started'})101      const callStartMoment = moment(callStart.createdAt)102      // const callStartMoment = moment(instance.state.get("callStart"))103      return `<i class="zmdi zmdi-time"></i> ${callStartMoment.format("HH:mm:ss")}`104  },105  call() {106    const instance = Template.instance();107    return instance.data.callID;108  },109  duration() {110      const instance = Template.instance();111    const callStart = moment(instance.state.get("createdAt"));112    const callEnd = moment(instance.state.get("endedAt"));113    const elapsed = moment.duration(callEnd.diff(callStart))114    return {115      min: correctDigits( String(elapsed.minutes()) ),116      seg: correctDigits( String(elapsed.seconds()) )117    }118  },119  delta(eventCreatedAt) {120    const instance = Template.instance();121    const callStart = moment(instance.state.get("createdAt"));122    const eventStart = moment(eventCreatedAt);123    // const diff = 124    return {125      min: correctDigits(String(moment.duration(eventStart.diff(callStart)).minutes())),126      seg: correctDigits(String(moment.duration(eventStart.diff(callStart)).seconds()))127    };128  },129  feedByCallID(callID) {130    return Orders.find(131      {132        call_id: callID133      },134      {135        sort: {136          createdAt: -1137        }138      }139    );140  },141  timeElapsed(callID) {142    let instance = Template.instance();143    let callStartEvent = Orders.find({ call_id: callID, type: "call_started" });144    return instance.state.get("timeElapsed");145    // return moment().diff(callStartEvent.createdAt, 'seconds')146  },147  lastIntent(callID) {148    let callEvents = Orders.find({ call_id: callID });149    let arr = [];150    callEvents.map(event => {151      event.intent && arr.push(event.intent);152    });153    return _.last(arr);154  },155  source() {156    const instance = Template.instance();157    return instance.state.get("source");158  },159  source_version() {160    const instance = Template.instance();161    return instance.state.get("source_version");162  }...

Full Screen

Full Screen

MyCall.js

Source:MyCall.js Github

copy

Full Screen

1import { useMutation, useReactiveVar } from "@apollo/client";2import { StackActions } from "@react-navigation/routers";3import React, { useEffect, useState } from "react";4import { Alert, Image, TouchableOpacity, View } from "react-native";5import styled from "styled-components";6import constants from "../../constants";7import { CANCEL_CALL } from "../../queries/CallQueries";8import { myCallVar } from "../../reactiveVars";9const Header = styled.View`10    align-items : center;11`12const CallActiveText = styled.Text`13    font-size : 27;14    font-weight : bold;15    margin-bottom : 15;16`17const RestaurantName = styled.Text`18    font-size : 14;19    opacity : 0.5;20`21const CallRemainingTime = styled.Text`22    font-size : 40;23    color : red;24    margin-top : 5;25`26const CancelBtnContainer = styled.View`27    background-color : rgba(0, 0, 0, 0.25);28    padding-left : 15;29    padding-right : 15;30    padding-top : 7;31    padding-bottom : 7;32    border-radius : 15;33`34const CancelBtnText = styled.Text`35    color : white;36    font-size : 15;37`38export default ({ navigation, route }) => {39    const myCall = useReactiveVar(myCallVar);40    if (!myCall) {41        console.log("TTT");42        navigation.dispatch(StackActions.replace("MethodSelect"))43    }44    const [remainingTimeString, setRemainingTimeString] = useState("00:00:00");45    const [cancelMutation] = useMutation(CANCEL_CALL);46    useEffect(() => {47        const countdown = setInterval(() => {48            getRemainingTime();49        })50        return () => clearInterval(countdown);51    }, [])52    const getRemainingTime = () => {53        const current = new Date();54        let callStart = new Date(myCall.created_at);55        callStart = new Date(callStart.getFullYear(), callStart.getMonth(), callStart.getDate(), callStart.getUTCHours(), callStart.getUTCMinutes());56        // callStart = new Date(`${callStart.getFullYear()}-${callStart.getMonth() + 1}-${callStart.getDate()} ${callStart.getUTCHours()}:${callStart.getUTCMinutes()}`);57        const remainingTime = callStart.getTime() + 6000 * myCall.time_limit - current.getTime();58        let remainingHour = parseInt(remainingTime / (1000 * 60 * 60));59        if (remainingHour < 10) {60            remainingHour = `0${remainingHour}`61        }62        let remainingMinute = parseInt(remainingTime / (1000 * 60));63        if (remainingMinute >= 60) {64            remainingMinute = remainingMinute % 6065        }66        if (remainingMinute < 10) {67            remainingMinute = `0${remainingMinute}`68        }69        let remainingSecond = parseInt(remainingTime / 1000);70        if (remainingSecond >= 60) {71            remainingSecond = remainingSecond % 60;72        }73        if (remainingSecond < 10) {74            remainingSecond = `0${remainingSecond}`75        }76        if (remainingTime <= 0) {77            cancelMutation({78                variables: {79                    seq: myCall.seq80                }81            });82            myCallVar(undefined);83            setRemainingTimeString("00:00:00")84            Alert.alert("콜이 취소되었습니다")85            navigation.dispatch(StackActions.replace("TabNavigation"))86        } else {87            setRemainingTimeString(`${remainingHour}:${remainingMinute}:${remainingSecond}`)88        }89    }90    return (91        <View style={{ flex: 1, justifyContent: "space-between", alignItems: "center", backgroundColor: "white", paddingVertical: constants.height * 0.11 }}>92            <Header>93                <CallActiveText>콜이 신청되었습니다</CallActiveText>94                <RestaurantName>{myCall.restaurant.name}</RestaurantName>95                <CallRemainingTime>{remainingTimeString}</CallRemainingTime>96            </Header>97            <Image source={require("../../assets/deliver.png")} style={{ width: 250, height: 250 * 250 / 341 }} />98            <TouchableOpacity onPress={() => {99                cancelMutation({100                    variables: {101                        seq: myCall.seq102                    }103                });104                myCallVar(undefined);105                Alert.alert("콜이 취소되었습니다")106                navigation.dispatch(StackActions.replace("TabNavigation"))107            }}>108                <CancelBtnContainer>109                    <CancelBtnText>콜 취소하기</CancelBtnText>110                </CancelBtnContainer>111            </TouchableOpacity>112        </View>113    )...

Full Screen

Full Screen

core.js

Source:core.js Github

copy

Full Screen

1import NativeReanimated from './NativeReanimated';2global.__reanimatedWorkletInit = function(worklet) {3  worklet.__worklet = true;4};5function pushFrame(frame) {6  NativeReanimated.pushFrame(frame);7}8export function requestFrame(frame) {9  'worklet';10  if (NativeReanimated.native) {11    requestAnimationFrame(frame);12  } else {13    pushFrame(frame);14  }15}16global._WORKLET = false;17global._log = function(s) {18  console.log(s);19};20export function runOnUI(worklet) {21  return makeShareable(worklet);22}23export function makeShareable(value) {24  return NativeReanimated.makeShareable(value);25}26export function getViewProp(viewTag, propName) {27  return new Promise((resolve, reject) => {28    return NativeReanimated.getViewProp(viewTag, propName, (result) => {29      if (result.substr(0, 6) === 'error:') {30        reject(result);31      } else {32        resolve(result);33      }34    });35  });36}37function workletValueSetter(value) {38  'worklet';39  const previousAnimation = this._animation;40  if (previousAnimation) {41    previousAnimation.cancelled = true;42    this._animation = null;43  }44  if (45    typeof value === 'function' ||46    (value !== null && typeof value === 'object' && value.animation)47  ) {48    // animated set49    const animation = typeof value === 'function' ? value() : value;50    let callStart = (timestamp) => {51      animation.start(animation, this.value, timestamp, previousAnimation);52    };53    const step = (timestamp) => {54      if (animation.cancelled) {55        animation.callback && animation.callback(false /* finished */);56        return;57      }58      if (callStart) {59        callStart(timestamp);60        callStart = null; // prevent closure from keeping ref to previous animation61      }62      const finished = animation.animation(animation, timestamp);63      animation.timestamp = timestamp;64      this._value = animation.current;65      if (finished) {66        animation.callback && animation.callback(true /* finished */);67      } else {68        requestAnimationFrame(step);69      }70    };71    this._animation = animation;72    requestAnimationFrame(step);73  } else {74    this._value = value;75  }76}77// We cannot use pushFrame78// so we use own implementation for js79function workletValueSetterJS(value) {80  const previousAnimation = this._animation;81  if (previousAnimation) {82    previousAnimation.cancelled = true;83    this._animation = null;84  }85  if (86    typeof value === 'function' ||87    (value !== null && typeof value === 'object' && value.animation)88  ) {89    // animated set90    const animation = typeof value === 'function' ? value() : value;91    let callStart = (timestamp) => {92      animation.start(animation, this.value, timestamp, previousAnimation);93    };94    const step = (timestamp) => {95      if (animation.cancelled) {96        animation.callback && animation.callback(false /* finished */);97        return;98      }99      if (callStart) {100        callStart(timestamp);101        callStart = null; // prevent closure from keeping ref to previous animation102      }103      const finished = animation.animation(animation, timestamp);104      animation.timestamp = timestamp;105      this._setValue(animation.current);106      if (finished) {107        animation.callback && animation.callback(true /* finished */);108      } else {109        requestFrame(step);110      }111    };112    this._animation = animation;113    requestFrame(step);114  } else {115    this._setValue(value);116  }117}118NativeReanimated.installCoreFunctions(119  NativeReanimated.native ? workletValueSetter : workletValueSetterJS120);121export function makeMutable(value) {122  return NativeReanimated.makeMutable(value);123}124export function makeRemote(object = {}) {125  return NativeReanimated.makeRemote(object);126}127export function startMapper(mapper, inputs = [], outputs = []) {128  return NativeReanimated.startMapper(mapper, inputs, outputs);129}130export function stopMapper(mapperId) {131  NativeReanimated.stopMapper(mapperId);...

Full Screen

Full Screen

lexer.js

Source:lexer.js Github

copy

Full Screen

1import 'https://unpkg.com/chevrotain@6.1.0/lib/chevrotain.js';2// const chevrotain = require('chevrotain');3const {createToken, Lexer} = chevrotain;4// Tokens5// http://sap.github.io/chevrotain/docs/tutorial/step1_lexing.html#our-first-token6const whitespace = createToken({7  name: 'whitespace',8  pattern: /\s+/,9  group: Lexer.SKIPPED10});11const literal = createToken({12  name: 'literal',13  pattern: /[^(\${)]+/14});15const templateStart = createToken({16  name: 'templateStart',17  pattern: /\${/,18  push_mode: 'template'19});20const templateEnd = createToken({21  name: 'templateEnd',22  pattern: /}/,23  push_mode: 'literal'24});25const stringStart = createToken({26  name: 'stringStart',27  pattern: /'/,28  push_mode: 'string'29});30const stringEnd = createToken({31  name: 'stringEnd',32  pattern: /'/,33  pop_mode: true34});35const stringContent = createToken({36  name: 'stringContent',37  pattern: /[^']+/38});39const star = createToken({40  name: 'star',41  pattern: /\.\.\./,42});43const groupStart = createToken({44  name: 'groupStart',45  pattern: /\[/46});47const groupEnd = createToken({48  name: 'groupEnd',  49  pattern: /\]/50});51const callStart = createToken({52  name: 'callStart',53  pattern: /\(/,54  push_mode: 'call'55});56const callEnd = createToken({57  name: 'callEnd',58  pattern: /\)/,59  pop_mode: true60});61const optionsStart = createToken({62  name: 'optionsStart',63  pattern: /{/,64  push_mode: 'options'65});66const optionsEnd = createToken({67  name: 'optionsEnd',68  pattern: /}/,69  pop_mode: true70});71const colon = createToken({72  name: 'colon',73  pattern: /:/74});75const comma = createToken({76  name: 'comma',77  pattern: /,/78});79const or = createToken({80  name: 'or',81  pattern: /\|/82});83const macroSign = createToken({84  name: 'macroSign',85  pattern: /!/,86});87const identifier = createToken({88  name: 'identifier',89  pattern: /[^ '{}\[\]\(\):,\|(\.\.\.)!]+/90});91// Define a Multi Mode Lexer92// https://sap.github.io/chevrotain/docs/features/lexer_modes.html93const multiModeLexerDefinition = {94  modes: {95    literal: [96      templateStart,97      literal98    ],99    template: [100      whitespace,101      stringStart,102      groupStart,103      groupEnd,104      identifier,105      callStart,106      optionsStart,107      or,108      star,109      macroSign,110      templateEnd111    ],112    string: [113      stringContent,114      stringEnd115    ],116    options: [117      whitespace,118      colon,119      stringStart,120      identifier,121      optionsStart,122      comma,123      optionsEnd124    ],125    call: [126      whitespace,127      identifier,128      macroSign,129      callStart,130      comma,131      optionsStart,132      callEnd133    ]134  },135  defaultMode: 'literal'136}137export const lexer = new Lexer(multiModeLexerDefinition);138export const tokens = {139  whitespace,140  literal,141  templateStart,142  templateEnd,143  stringStart,144  stringEnd,145  stringContent,146  star,147  groupStart,148  groupEnd,149  callStart,150  callEnd,151  optionsStart,152  optionsEnd,153  colon,154  comma,155  or,156  macroSign,157  identifier...

Full Screen

Full Screen

probes.js

Source:probes.js Github

copy

Full Screen

1/*2 * JavaScript probing framework by Sam Saffron3 * MIT license4 *5 *6 * Examples:7 *8 *  someFunction = window.probes.measure(someFunction, {9 *    name: "somename" // or function(args) { return "name"; },10 *    before: function(data, owner, args) {11 *      // if owner is true, we are not in a recursive function call.12 *      //13 *      // data contains the bucker of data already measuer14 *      // data.count >= 015 *      // data.time is the total time measured till now16 *      //17 *      // arguments contains the original arguments sent to the function18 *    },19 *    after: function(data, owner, args) {20 *      // same format as before21 *    }22 *  });23 *24 *25 *  // minimal26 *  someFunction = window.probes.measure(someFunction, "someFunction");27 *28 * */29(function(){30  var measure, clear;31  clear = function() {32    window.probes = {33      clear: clear,34      measure: measure35    };36  };37  measure = function(fn,options) {38    // start is outside so we measure time around recursive calls properly39    var start = null, nameParam, before, after;40    if (!options) {41      options = {};42    }43    if (typeof options === "string") {44      nameParam = options;45    }46    else47    {48      nameParam = options.name;49      if (nameParam === "measure" || nameParam === "clear") {50        throw new Error("can not be called measure or clear");51      }52      if (!nameParam)53      {54        throw new Error("you must specify the name option measure(fn, {name: 'some name'})");55      }56      before = options.before;57      after = options.after;58    }59    var now = (function(){60      var perf = window.performance || {};61      var time = perf.now || perf.mozNow || perf.webkitNow || perf.msNow || perf.oNow;62      return time ? time.bind(perf) : function() { return new Date().getTime(); };63    })();64    return function() {65      var name = nameParam;66      if (typeof name === "function"){67        name = nameParam(arguments);68      }69      var p = window.probes[name];70      var owner = (!start);71      if (before) {72        // would like to avoid try catch so its optimised properly by chrome73        before(p, owner, arguments);74      }75      if (p === undefined) {76        window.probes[name] = {count: 0, time: 0, currentTime: 0};77        p = window.probes[name];78      }79      var callStart;80      if (owner) {81        start = now();82        callStart = start;83      }84      else if(after) {85        callStart = now();86      }87      var r = fn.apply(this, arguments);88      if (owner && start) {89        p.time += now() - start;90        start = null;91      }92      p.count += 1;93      if (after) {94        p.currentTime = now() - callStart;95        // would like to avoid try catch so its optimised properly by chrome96        after(p, owner, arguments);97      }98      return r;99    };100  };101  clear();...

Full Screen

Full Screen

cdr-astpp.js

Source:cdr-astpp.js Github

copy

Full Screen

1const moment = require("moment")2const inicioFinal = (mesAno) => {3    const data = moment(`01-${mesAno}`, "DD-MM-YYYY")4    const inicio = data.format("YYYY-MM-DD HH:mm:ss")5    data.add(1, "month")6    data.subtract(1, "second")7    const termino = data.format("YYYY-MM-DD HH:mm:ss")8    return {9        inicio,10        termino11    }12}13const getTotalChamadasMesRecebidas = (did, mes) => {14    const { inicio, termino } = inicioFinal(mes)15    return new Promise(async (resolve, reject) => {16        try {17            const conn = await require("../service/mysql-astpp").getConnection()18            const [result] = await conn.query(`19        SELECT20          COUNT(*) AS quantidade,21          sum(billseconds) AS segundos,22          DATE_FORMAT(callstart, "%Y-%m") AS mes23        FROM24          cdrs25        WHERE26          callednum = '${did}' and27          callstart BETWEEN '${inicio}' AND '${termino}' and28          billseconds > 029        GROUP BY30          DATE_FORMAT(callstart, "%Y-%m")31      `)32            conn.close()33            resolve(result)34        } catch (error) {35            reject(error)36        }37    })38}39const getTotalChamadasMesDiscadas = (did, mes) => {40    const { inicio, termino } = inicioFinal(mes)41    return new Promise(async (resolve, reject) => {42        try {43            const conn = await require("../service/mysql-astpp").getConnection()44            const [result] = await conn.query(`45        SELECT46          COUNT(*) AS quantidade,47          sum(billseconds) AS segundos,48          DATE_FORMAT(callstart, "%Y-%m") AS mes49        FROM50          cdrs51        WHERE52          callerid LIKE '%${did}%' and53          callstart BETWEEN '${inicio}' AND '${termino}' and54          billseconds > 055        GROUP BY56          DATE_FORMAT(callstart, "%Y-%m")57      `)58            conn.close()59            resolve(result)60        } catch (error) {61            reject(error)62        }63    })64}65module.exports = {66    getTotalChamadasMesRecebidas,67    getTotalChamadasMesDiscadas...

Full Screen

Full Screen

interval.js

Source:interval.js Github

copy

Full Screen

1import React from 'react';2export const CreateIntervalCall = (3  process = async () => {},4  intervalTime = 1000,5  processLimit = 16) => {7  let inProcessStatus = true;8  const intervalProcess = [];9  const intervalCall = () => {10    inProcessStatus && callStart(intervalTime);11  };12  const callNext = (timeout = 0) => {13    intervalProcess.length <= processLimit14      ? intervalProcess.push(15          setTimeout(async () => {16            await process();17            intervalProcess.shift();18            intervalCall();19          }, timeout)20        )21      : callStart();22  };23  const callStart = (time = 100) => callNext(time);24  const callStop = () => {25    inProcessStatus = false;26    intervalProcess.map((ps) => {27      clearTimeout(ps);28    });29  };30  return {31    callStart,32    callStop,33  };34};35const intervalFactory = () => ({ CreateIntervalCall });...

Full Screen

Full Screen

Jest Testing Tutorial

LambdaTest’s Jest Testing Tutorial covers step-by-step guides around Jest with code examples to help you be proficient with the Jest framework. The Jest tutorial has chapters to help you learn right from the basics of Jest framework to code-based tutorials around testing react apps with Jest, perform snapshot testing, import ES modules and more.

Chapters

  1. What is Jest Framework
  2. Advantages of Jest - Jest has 3,898,000 GitHub repositories, as mentioned on its official website. Learn what makes Jest special and why Jest has gained popularity among the testing and developer community.
  3. Jest Installation - All the prerequisites and set up steps needed to help you start Jest automation testing.
  4. Using Jest with NodeJS Project - Learn how to leverage Jest framework to automate testing using a NodeJS Project.
  5. Writing First Test for Jest Framework - Get started with code-based tutorial to help you write and execute your first Jest framework testing script.
  6. Jest Vocabulary - Learn the industry renowned and official jargons of the Jest framework by digging deep into the Jest vocabulary.
  7. Unit Testing with Jest - Step-by-step tutorial to help you execute unit testing with Jest framework.
  8. Jest Basics - Learn about the most pivotal and basic features which makes Jest special.
  9. Jest Parameterized Tests - Avoid code duplication and fasten automation testing with Jest using parameterized tests. Parameterization allows you to trigger the same test scenario over different test configurations by incorporating parameters.
  10. Jest Matchers - Enforce assertions better with the help of matchers. Matchers help you compare the actual output with the expected one. Here is an example to see if the object is acquired from the correct class or not. -

|<p>it('check_object_of_Car', () => {</p><p> expect(newCar()).toBeInstanceOf(Car);</p><p> });</p>| | :- |

  1. Jest Hooks: Setup and Teardown - Learn how to set up conditions which needs to be followed by the test execution and incorporate a tear down function to free resources after the execution is complete.
  2. Jest Code Coverage - Unsure there is no code left unchecked in your application. Jest gives a specific flag called --coverage to help you generate code coverage.
  3. HTML Report Generation - Learn how to create a comprehensive HTML report based on your Jest test execution.
  4. Testing React app using Jest Framework - Learn how to test your react web-application with Jest framework in this detailed Jest tutorial.
  5. Test using LambdaTest cloud Selenium Grid - Run your Jest testing script over LambdaTest cloud-based platform and leverage parallel testing to help trim down your test execution time.
  6. Snapshot Testing for React Front Ends - Capture screenshots of your react based web-application and compare them automatically for visual anomalies with the help of Jest tutorial.
  7. Bonus: Import ES modules with Jest - ES modules are also known as ECMAScript modules. Learn how to best use them by importing in your Jest testing scripts.
  8. Jest vs Mocha vs Jasmine - Learn the key differences between the most popular JavaScript-based testing frameworks i.e. Jest, Mocha, and Jasmine.
  9. Jest FAQs(Frequently Asked Questions) - Explore the most commonly asked questions around Jest framework, with their answers.

Run Jest automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful