How to use dispatchEvent method in Playwright Internal

Best JavaScript code snippet using playwright-internal

group.js

Source:group.js Github

copy

Full Screen

...132 );133 }134 this.__cbListLoad(_key,_options.onload,_json);135 if (!!_json.result.count){136 _v._$dispatchEvent(137 _p._$$CacheGroup,138 'countupdate',_json.result.count139 );140 }141 }._$bind(this),142 onerror:this.__cbListLoad._$bind(this,_key,_options.onload,_o)143 });144 };145 /**146 * 从缓存中取组织信息147 * @return {Object} 组织信息148 */149 _proCacheGroup._$getGroupInCache = function(_gid){150 return this.__getDataInCache('group'+(_gid||''));151 };152 /**153 * 创建组织154 * @param {Object} 组织信息155 * @return {Void} 156 */157 _proCacheGroup._$create = function(_group){158 var _xkey = 'cb_'+(_seed++);159 window[_xkey] = function(_json){160 if ((_json||_o).status==0){161 var _location = _json.result.location||_o;162 _group.latitude = _location.lat||'0.0';163 _group.longitude = _location.lng||'0.0';164 }else{165 _group.latitude = '0.0';166 _group.longitude = '0.0';167 }168 _j._$request('/rest/group/create',{169 type:'json',170 method:'POST',171 data:_u._$object2query(_group),172 onload:function(_json){173 if (_json.code==1)174 this.__setDataInCache('group',_json.result);175 this._$dispatchEvent('ongroupcreate',_json);176 }._$bind(this),177 onerror:this._$dispatchEvent._$bind(this,'ongroupcreate',_o)178 });179 }._$bind(this);180 _j._$loadScript(181 _baidu+_u._$object2query({182 city:_group.city,183 address:_group.area,184 callback:_xkey185 }),{186 onerror:window[_xkey]187 }188 );189 };190 /**191 * 更新组织信息192 * @param {Object} 组织信息193 * @return {Void}194 */195 _proCacheGroup._$update = function(_group){196 _j._$request('/rest/group/update',{197 type:'json',198 method:'POST',199 data:_u._$object2query(_group),200 onload:this._$dispatchEvent._$bind(this,'ongroupupdate'),201 onerror:this._$dispatchEvent._$bind(this,'ongroupupdate',_o)202 });203 };204 /**205 * 删除组织206 * @param {String} 组织ID207 * @return {Void}208 */209 _proCacheGroup._$delete = function(_gid){210 211 };212 /**213 * 取推荐标签列表214 * @return {Void}215 */216 _proCacheGroup._$getRecTag = function(){217 _j._$request('/rest/tag/rec',{218 type:'json',219 method:'POST',220 onload:this._$dispatchEvent._$bind(this,'onrectagload'),221 onerror:this._$dispatchEvent._$bind(this,'onrectagload',_o)222 });223 };224 /**225 * 更新组织标签226 * @param {String} 组织标识227 * @param {String} 组织标签228 * @return {Void}229 */230 _proCacheGroup._$updateTag = function(_tag){231 var _group = this._$getGroupInCache();232 _j._$request('/rest/tag/group',{233 type:'json',234 method:'POST',235 data:_u._$object2query({gid:_group.id,tag:_tag}),236 onload:this._$dispatchEvent._$bind(this,'ontagupdate'),237 onerror:this._$dispatchEvent._$bind(this,'ontagupdate',_o)238 });239 };240 /**241 * 添加问题242 * @param {Object} _question 问题信息243 * @return {Void}244 */245 _proCacheGroup._$addQuestion = function(_question){246 var _group = this._$getGroupInCache();247 _j._$request('/rest/group/addQuestion',{248 type:'json',249 method:'POST',250 data:_u._$object2query({251 gid:_group.id,252 publish:_question.publish,253 question:_question.question254 }),255 onload:this._$dispatchEvent._$bind(this,'onquestionadd',_question),256 onerror:this._$dispatchEvent._$bind(this,'onquestionadd',_question,_o)257 });258 };259 /**260 * 更新问题261 * @param {Object} _question 问题信息262 * @return {Void}263 */264 _proCacheGroup._$updateQuestion = function(_question){265 var _group = this._$getGroupInCache();266 _j._$request('/rest/group/updateQuestion',{267 type:'json',268 method:'POST',269 data:_u._$object2query({270 gid:_group.id,271 qid:_question.qid,272 publish:_question.publish,273 question:_question.question274 }),275 onload:this._$dispatchEvent._$bind(this,'onquestionupdate',_question),276 onerror:this._$dispatchEvent._$bind(this,'onquestionupdate',_question,_o)277 });278 };279 /**280 * 删除问题281 * @param {String} _qid 问题标识282 * @return {Void}283 */284 _proCacheGroup._$deleteQuestion = function(_question){285 var _group = this._$getGroupInCache();286 _j._$request('/rest/group/deleteQuestion',{287 type:'json',288 method:'POST',289 data:_u._$object2query({gid:_group.id,qid:_question.qid}),290 onload:this._$dispatchEvent._$bind(this,'onquestiondelete',_question),291 onerror:this._$dispatchEvent._$bind(this,'onquestiondelete',_question,_o)292 });293 };294 /**295 * 更新加入组织条件设置296 * @param {Object} _setting297 */298 _proCacheGroup._$updateJoinSetting = function(_setting){299 var _group = this._$getGroupInCache();300 if (!!_group) _setting.gid = _group.id;301 _j._$request('/rest/group/updateJoinSetting',{302 type:'json',303 method:'POST',304 data:_u._$object2query(_setting),305 onload:this._$dispatchEvent._$bind(this,'onjoinsettingupdate'),306 onerror:this._$dispatchEvent._$bind(this,'onjoinsettingupdate',_o)307 });308 };309 /**310 * 311 */312 _proCacheGroup._$updatePrivacy = function(_setting){313 _j._$request('/rest/group/updatePrivacy',{314 type:'json',315 method:'POST',316 data:_u._$object2query(_setting),317 onload:this._$dispatchEvent._$bind(this,'onprivacyupdate'),318 onerror:this._$dispatchEvent._$bind(this,'onprivacyupdate',_o)319 });320 };321 /**322 * 323 */324 _proCacheGroup._$updateLogo = function(_form){325 _form.action = '/rest/group/updateLogo';326 _j._$upload(_form,{327 type:'json',328 onload:this._$dispatchEvent._$bind(this,'onlogoupdate'),329 onerror:this._$dispatchEvent._$bind(this,'onlogoupdate',_o)330 });331 };332 /**333 * 334 * @param {Object} _data335 */336 _proCacheGroup._$clipLogo = function(_data){337 _j._$request('/rest/group/clipLogo',{338 type:'json',339 method:'POST',340 data:_u._$object2query(_data),341 onload:this._$dispatchEvent._$bind(this,'onlogoclip'),342 onerror:this._$dispatchEvent._$bind(this,'onlogoclip',_o)343 });344 };345 /**346 * 加入组织347 * @param {Object} _form348 */349 _proCacheGroup._$join = function(_data){350 _j._$request('/rest/group/join',{351 type:'json',352 method:'POST',353 data:_u._$object2query(_data),354 onload:this._$dispatchEvent._$bind(this,'onjoin'),355 onerror:this._$dispatchEvent._$bind(this,'onjoin',_o)356 });357 };358 /**359 * 群通知360 * @param {Object} _form361 */362 _proCacheGroup._$inform = function(_data){363 _j._$request('/rest/message/inform',{364 type:'json',365 method:'POST',366 data:_u._$object2query(_data),367 onload:this._$dispatchEvent._$bind(this,'oninform'),368 onerror:this._$dispatchEvent._$bind(this,'oninform',_o)369 });370 };371 /**372 * 373 */374 _proCacheGroup._$exit = function(_gid){375 _j._$request('/rest/group/exit',{376 type:'json',377 method:'POST',378 data:_u._$object2query({gid:_gid}),379 onload:this._$dispatchEvent._$bind(this,'onexit'),380 onerror:this._$dispatchEvent._$bind(this,'onexit',_o)381 });382 };383 /**384 * 385 */386 _proCacheGroup._$dismiss = function(_gid){387 _j._$request('/rest/group/dismiss',{388 type:'json',389 method:'POST',390 data:_u._$object2query({gid:_gid}),391 onload:this._$dispatchEvent._$bind(this,'ondismiss'),392 onerror:this._$dispatchEvent._$bind(this,'ondismiss',_o)393 });394 };395 /**396 * 397 */398 _proCacheGroup._$invite = function(_data){399 _j._$request('/rest/user/invite',{400 type:'json',401 method:'POST',402 data:_u._$object2query(_data),403 onload:this._$dispatchEvent._$bind(this,'oninvite'),404 onerror:this._$dispatchEvent._$bind(this,'oninvite',_o)405 });406 };407 /**408 * 409 */410 _proCacheGroup._$getMsgSettingInCache = function(_uid,_gid){411 return this.__getDataInCache(_uid+'-'+_gid);412 };413 /**414 * 取某个用户对组织的消息设置415 * @param {Object} _uid416 * @param {Object} _gid417 */418 _proCacheGroup._$getMsgSetting = function(_uid,_gid){419 var _key = _uid+'-'+_gid,420 _data = this._$getMsgSettingInCache(_uid,_gid);421 if (!!_data){422 this._$dispatchEvent('onmsgsettingload',_key);423 return;424 }425 _j._$request('/rest/settings/get',{426 type:'json',427 method:'POST',428 data:_u._$object2query({gid:_gid}),429 onload:this.__getMsgSetting._$bind(this,_key),430 onerror:this.__getMsgSetting._$bind(this,_key,_o)431 });432 };433 /**434 * 435 * @param {Object} _key436 */437 _proCacheGroup.__getMsgSetting = function(_key,_json){438 if (_json.code==1){439 this.__setDataInCache(_key,_json.result);440 }441 this._$dispatchEvent('onmsgsettingload',_key);442 };443 /**444 * 445 * @param {Object} _setting446 */447 _proCacheGroup._$updateMsgSetting = function(_uid,_setting){448 var _key = _uid+'-'+_setting.gid;449 _j._$request('/rest/settings/update',{450 type:'json',451 method:'POST',452 data:_u._$object2query(_setting),453 onload:this.__updateMsgSetting._$bind(this,_key),454 onerror:this.__updateMsgSetting._$bind(this,_key,_o)455 });456 };457 /**458 * 459 * @param {Object} _setting460 */461 _proCacheGroup.__updateMsgSetting = function(_key,_json){462 if (_json.code==1){463 this.__setDataInCache(_key,_json.result);464 }465 this._$dispatchEvent('onmsgsettingupdate',_key,_json);466 };467 /**468 * 469 * @param {Object} _data470 */471 _proCacheGroup._$apply = function(_data){472 var _url = '/rest/group/apply';473 if (!!_data.updated){474 _url = '/rest/group/updateApplication';475 }476 delete _data.updated;477 _j._$request(_url,{478 type:'json',479 method:'POST', ...

Full Screen

Full Screen

index.spec.js

Source:index.spec.js Github

copy

Full Screen

...24 expect(selector.innerHTML).toEqual("");25 });26 it("should be opened on click", () => {27 const input = rangePicker.element.querySelector('.rangepicker__input');28 input.dispatchEvent(new MouseEvent("click"));29 expect(rangePicker.element.classList).toContain('rangepicker_open');30 });31 it("should be closed on second click", function() {32 const input = rangePicker.element.querySelector('.rangepicker__input');33 input.dispatchEvent(new MouseEvent("click"));34 input.dispatchEvent(new MouseEvent("click"));35 expect(rangePicker.element.classList).not.toContain('rangepicker_open');36 });37 it("should show selected dates 'dateFrom-dateTo' in input", () => {38 const input = rangePicker.element.querySelector('.rangepicker__input');39 const dateFrom = input.firstElementChild.innerHTML;40 const dateTo = input.lastElementChild.innerHTML;41 input.dispatchEvent(new MouseEvent("click"));42 expect(dateFrom).toMatch("02.10.2019");43 expect(dateTo).toMatch("05.11.2019");44 });45 it("should highlight selected 'from' and 'to' dates in calendar", () => {46 const rangePicker = new RangePicker({47 from: new Date(2019, 9, 12),48 to: new Date(2019, 10, 25)49 });50 const input = rangePicker.element.querySelector('.rangepicker__input');51 input.dispatchEvent(new MouseEvent("click"));52 const from = rangePicker.element.querySelector('.rangepicker__selected-from');53 const to = rangePicker.element.querySelector('.rangepicker__selected-to');54 expect(from.textContent.trim()).toMatch("12");55 expect(to.textContent.trim()).toMatch("25");56 });57 it("should highlight selected dates range in calendar", () => {58 const from = new Date(2020, 5, 8);59 const to = new Date(2020, 6, 13);60 const totalDays = getDaysBetweenDates(from, to);61 const RANGE_BORDERS_COUNT = 2;62 const rangePicker = new RangePicker({from, to});63 const input = rangePicker.element.querySelector('.rangepicker__input');64 input.dispatchEvent(new MouseEvent("click"));65 const selectedBetween = rangePicker.element.querySelectorAll('.rangepicker__selected-between');66 expect(selectedBetween.length).toEqual(totalDays - RANGE_BORDERS_COUNT);67 });68 it("should clear highlighting of previous selection", () => {69 const input = rangePicker.element.querySelector('.rangepicker__input');70 input.dispatchEvent(new MouseEvent("click"));71 const from = rangePicker.element.querySelector('.rangepicker__selected-from');72 const prevDate = from.previousElementSibling;73 prevDate.dispatchEvent(new MouseEvent("click", {bubbles: true}));74 const selectedBetween = rangePicker.element.querySelectorAll('.rangepicker__selected-between');75 expect(selectedBetween.length).toEqual(0);76 });77 it("should keep selected dates range after reopening", () => {78 const input = rangePicker.element.querySelector('.rangepicker__input');79 // open date picker80 input.dispatchEvent(new MouseEvent("click"));81 let from = rangePicker.element.querySelector('.rangepicker__selected-from');82 const prevDate = from.previousElementSibling;83 const nextDate = from.nextElementSibling;84 prevDate.dispatchEvent(new MouseEvent("click", {bubbles: true}));85 nextDate.dispatchEvent(new MouseEvent("click", {bubbles: true}));86 from = rangePicker.element.querySelector('.rangepicker__selected-from');87 const to = rangePicker.element.querySelector('.rangepicker__selected-to');88 expect(from.textContent.trim()).toEqual("1");89 expect(to.textContent.trim()).toEqual("3");90 });91 it("should show correct initial months in calendar", () => {92 const input = rangePicker.element.querySelector('.rangepicker__input');93 // open date picker94 input.dispatchEvent(new MouseEvent("click"));95 const [first, second] = rangePicker.element.querySelectorAll('.rangepicker__month-indicator');96 expect(first.textContent.trim()).toEqual("октябрь");97 expect(second.textContent.trim()).toEqual("ноябрь");98 });99 it("should have ability to switch to the next couple of months", () => {100 const input = rangePicker.element.querySelector('.rangepicker__input');101 // open date picker102 input.dispatchEvent(new MouseEvent("click"));103 const rightNavigation = rangePicker.element.querySelector('.rangepicker__selector-control-right');104 rightNavigation.dispatchEvent(new MouseEvent("click"));105 const [first, second] = rangePicker.element.querySelectorAll('.rangepicker__month-indicator');106 expect(first.textContent.trim()).toEqual("ноябрь");107 expect(second.textContent.trim()).toEqual("декабрь");108 });109 it("should have ability to switch to the previous couple of months", () => {110 const input = rangePicker.element.querySelector('.rangepicker__input');111 // open date picker112 input.dispatchEvent(new MouseEvent("click"));113 const rightNavigation = rangePicker.element.querySelector('.rangepicker__selector-control-left');114 rightNavigation.dispatchEvent(new MouseEvent("click"));115 const [first, second] = rangePicker.element.querySelectorAll('.rangepicker__month-indicator');116 expect(first.textContent.trim()).toEqual("сентябрь");117 expect(second.textContent.trim()).toEqual("октябрь");118 });119 it("should have ability to select all dates in two visible months", () => {120 const input = rangePicker.element.querySelector('.rangepicker__input');121 const selector = rangePicker.element.querySelector('.rangepicker__selector');122 // open date picker123 input.dispatchEvent(new MouseEvent("click"));124 const [firstCalendar, secondCalendar] = selector.querySelectorAll('.rangepicker__calendar');125 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');126 const secondDateGrid = secondCalendar.querySelector('.rangepicker__date-grid');127 const firstDate = firstDateGrid.firstElementChild;128 const lastDate = secondDateGrid.lastElementChild;129 // change "from" and "to" dates130 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));131 lastDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));132 let from = rangePicker.element.querySelector('.rangepicker__selected-from');133 let to = rangePicker.element.querySelector('.rangepicker__selected-to');134 // check dates selection in calendar135 expect(from.textContent.trim()).toEqual("1");136 expect(to.textContent.trim()).toEqual("30");137 // close date picker138 input.dispatchEvent(new MouseEvent("click"));139 from = rangePicker.element.querySelector('.rangepicker__selected-from');140 to = rangePicker.element.querySelector('.rangepicker__selected-to');141 // check selection after second opening142 expect(from.textContent.trim()).toEqual("1");143 expect(to.textContent.trim()).toEqual("30");144 });145 it("should have ability to select dates range bigger than two months", () => {146 const input = rangePicker.element.querySelector('.rangepicker__input');147 const selector = rangePicker.element.querySelector('.rangepicker__selector');148 // open date picker149 input.dispatchEvent(new MouseEvent("click"));150 const [firstCalendar] = selector.querySelectorAll('.rangepicker__calendar');151 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');152 const firstDate = firstDateGrid.firstElementChild;153 // change "from" date154 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));155 const rightNavigation = rangePicker.element.querySelector('.rangepicker__selector-control-right');156 // got to the next couple of months157 rightNavigation.dispatchEvent(new MouseEvent("click"));158 const [_, secondCalendar] = selector.querySelectorAll('.rangepicker__calendar');159 const secondDateGrid = secondCalendar.querySelector('.rangepicker__date-grid');160 const lastDate = secondDateGrid.lastElementChild;161 // change "to" date162 lastDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));163 // close date picker164 input.dispatchEvent(new MouseEvent("click"));165 const dateFrom = input.firstElementChild.innerHTML;166 const dateTo = input.lastElementChild.innerHTML;167 expect(dateFrom).toMatch("01.10.2019");168 expect(dateTo).toMatch("31.12.2019");169 });170 it("should not change dates 'from' and 'to' inside input element if selected only one date", () => {171 const input = rangePicker.element.querySelector('.rangepicker__input');172 const selector = rangePicker.element.querySelector('.rangepicker__selector');173 // open date picker174 input.dispatchEvent(new MouseEvent("click"));175 const [firstCalendar] = selector.querySelectorAll('.rangepicker__calendar');176 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');177 const firstDate = firstDateGrid.firstElementChild;178 // change "from" date179 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));180 // close date picker181 input.dispatchEvent(new MouseEvent("click"));182 const dateFrom = input.firstElementChild.innerHTML;183 const dateTo = input.lastElementChild.innerHTML;184 expect(dateFrom).toMatch("02.10.2019");185 expect(dateTo).toMatch("05.11.2019");186 });187 it("should have ability to select minimal dates range equal two days", () => {188 const input = rangePicker.element.querySelector('.rangepicker__input');189 const selector = rangePicker.element.querySelector('.rangepicker__selector');190 // open date picker191 input.dispatchEvent(new MouseEvent("click"));192 const [firstCalendar] = selector.querySelectorAll('.rangepicker__calendar');193 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');194 const firstDate = firstDateGrid.firstElementChild;195 const nexDate = firstDate.nextElementSibling;196 // change "from" date to "01.10.2019"197 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));198 // change "to" date to "02.10.2019"199 nexDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));200 // close date picker201 input.dispatchEvent(new MouseEvent("click"));202 const dateFrom = input.firstElementChild.innerHTML;203 const dateTo = input.lastElementChild.innerHTML;204 expect(dateFrom).toMatch("01.10.2019");205 expect(dateTo).toMatch("02.10.2019");206 });207 // TODO: maybe we need fix this behaviour in DateRange component?208 it("should have ability to select minimal dates range equal one day", () => {209 const input = rangePicker.element.querySelector('.rangepicker__input');210 const selector = rangePicker.element.querySelector('.rangepicker__selector');211 // open date picker212 input.dispatchEvent(new MouseEvent("click"));213 const [firstCalendar] = selector.querySelectorAll('.rangepicker__calendar');214 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');215 const firstDate = firstDateGrid.firstElementChild;216 // change "from" date to "01.10.2019"217 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));218 // change "to" date to "01.10.2019"219 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));220 // close date picker221 input.dispatchEvent(new MouseEvent("click"));222 const dateFrom = input.firstElementChild.innerHTML;223 const dateTo = input.lastElementChild.innerHTML;224 expect(dateFrom).toMatch("01.10.2019");225 expect(dateTo).toMatch("01.10.2019");226 });227 it("should have ability select more than 1 year dates range", () => {228 const MONTHS_COUNT = 12;229 const input = rangePicker.element.querySelector('.rangepicker__input');230 const selector = rangePicker.element.querySelector('.rangepicker__selector');231 // open date picker232 input.dispatchEvent(new MouseEvent("click"));233 const [firstCalendar] = selector.querySelectorAll('.rangepicker__calendar');234 const firstDateGrid = firstCalendar.querySelector('.rangepicker__date-grid');235 const firstDate = firstDateGrid.firstElementChild;236 // change "from" date to "01.10.2019"237 firstDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));238 const rightNavigation = rangePicker.element.querySelector('.rangepicker__selector-control-right');239 for (let i = 0; i < MONTHS_COUNT; i++) {240 rightNavigation.dispatchEvent(new MouseEvent('click'));241 }242 const [_, secondCalendar] = selector.querySelectorAll('.rangepicker__calendar');243 const secondDateGrid = secondCalendar.querySelector('.rangepicker__date-grid');244 const lastDate = secondDateGrid.firstElementChild;245 // change "to" date "01.11.2020"246 lastDate.dispatchEvent(new MouseEvent("click", { bubbles: true }));247 // close date picker248 input.dispatchEvent(new MouseEvent("click"));249 const dateFrom = input.firstElementChild.innerHTML;250 const dateTo = input.lastElementChild.innerHTML;251 expect(dateFrom).toMatch("01.10.2019");252 expect(dateTo).toMatch("01.11.2020");253 });...

Full Screen

Full Screen

pastehandler_test.js

Source:pastehandler_test.js Github

copy

Full Screen

...53 // user clicks on the textarea and give it focus54 goog.events.listen(55 handlerThatSupportsPasteEvents, goog.events.PasteHandler.EventType.PASTE,56 function() { pasted = true; });57 textarea.dispatchEvent(newBrowserEvent('paste'));58 assertTrue(pasted);59}60function testJustTypingDoesntFirePasteEvent() {61 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {62 return;63 }64 // user clicks on the textarea and give it focus65 textarea.dispatchEvent(newBrowserEvent(goog.events.EventType.FOCUS));66 assertFalse(pasted);67 // user starts typing68 textarea.dispatchEvent(newBrowserEvent({69 type: goog.events.EventType.KEYDOWN,70 keyCode: goog.events.KeyCodes.A71 }));72 textarea.value = 'a';73 assertFalse(pasted);74 // still typing75 textarea.dispatchEvent(76 {type: goog.events.EventType.KEYDOWN, keyCode: goog.events.KeyCodes.B});77 textarea.value = 'ab';78 assertFalse(pasted);79 // ends typing80 textarea.dispatchEvent(81 {type: goog.events.EventType.KEYDOWN, keyCode: goog.events.KeyCodes.C});82 textarea.value = 'abc';83 assertFalse(pasted);84}85function testStartsOnInitialState() {86 assertTrue(handler.getState() == goog.events.PasteHandler.State.INIT);87 assertFalse(pasted);88}89function testBlurOnInit() {90 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {91 return;92 }93 textarea.dispatchEvent(goog.events.EventType.BLUR);94 assertTrue(handler.getState() == goog.events.PasteHandler.State.INIT);95 assertFalse(pasted);96}97function testFocusOnInit() {98 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {99 return;100 }101 textarea.dispatchEvent(goog.events.EventType.FOCUS);102 assertTrue(handler.getState() == goog.events.PasteHandler.State.FOCUSED);103 assertFalse(pasted);104}105function testInputOnFocus() {106 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {107 return;108 }109 // user clicks on the textarea110 textarea.dispatchEvent(newBrowserEvent(goog.events.EventType.FOCUS));111 clock.tick(112 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +113 1);114 // and right click -> paste a text!115 textarea.dispatchEvent(newBrowserEvent('input'));116 assertTrue(handler.getState() == goog.events.PasteHandler.State.FOCUSED);117 // make sure we detected it118 assertTrue(pasted);119}120function testKeyPressOnFocus() {121 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {122 return;123 }124 // user clicks on the textarea125 textarea.dispatchEvent(newBrowserEvent(goog.events.EventType.FOCUS));126 // starts typing something127 textarea.dispatchEvent(newBrowserEvent({128 type: goog.events.EventType.KEYDOWN,129 keyCode: goog.events.KeyCodes.A130 }));131 assertTrue(handler.getState() == goog.events.PasteHandler.State.TYPING);132 assertFalse(pasted);133 // and then presses ctrl+v134 textarea.dispatchEvent(newBrowserEvent({135 type: goog.events.EventType.KEYDOWN,136 keyCode: goog.events.KeyCodes.V,137 ctrlKey: true138 }));139 assertTrue(handler.getState() == goog.events.PasteHandler.State.TYPING);140 // makes sure we detected it141 assertTrue(pasted);142}143function testMouseOverOnInit() {144 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {145 return;146 }147 // user has something on the events148 textarea.value = 'pasted string';149 // and right click -> paste it on the textarea, WITHOUT giving focus150 textarea.dispatchEvent(newBrowserEvent(goog.events.EventType.MOUSEOVER));151 assertTrue(handler.getState() == goog.events.PasteHandler.State.INIT);152 // makes sure we detect it153 assertTrue(pasted);154 pasted = false;155 // user normaly mouseovers the textarea, with no text change156 textarea.dispatchEvent(goog.events.EventType.MOUSEOVER);157 assertTrue(handler.getState() == goog.events.PasteHandler.State.INIT);158 // text area value doesn't change159 assertFalse(pasted);160}161function testMouseOverAfterTyping() {162 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {163 return;164 }165 textarea.dispatchEvent(goog.events.EventType.FOCUS);166 assertFalse(pasted);167 textarea.dispatchEvent(168 {type: goog.events.EventType.KEYDOWN, keyCode: goog.events.KeyCodes.A});169 assertFalse(pasted);170 textarea.value = 'a';171 textarea.dispatchEvent('input');172 assertFalse(pasted);173 assertEquals('a', handler.oldValue_);174 textarea.dispatchEvent(goog.events.EventType.MOUSEOVER);175 assertFalse(pasted);176}177function testTypingAndThenRightClickPaste() {178 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {179 return;180 }181 textarea.dispatchEvent(goog.events.EventType.FOCUS);182 textarea.dispatchEvent(183 {type: goog.events.EventType.KEYDOWN, keyCode: goog.events.KeyCodes.A});184 assertFalse(pasted);185 textarea.value = 'a';186 clock.tick(187 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +188 1);189 textarea.dispatchEvent('input');190 assertFalse(pasted);191 assertEquals('a', handler.oldValue_);192 textarea.value = 'ab';193 clock.tick(194 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +195 1);196 textarea.dispatchEvent(newBrowserEvent('input'));197 assertTrue(pasted);198}199function testTypingReallyFastDispatchesTwoInputEventsBeforeTheKeyDownEvent() {200 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {201 return;202 }203 textarea.dispatchEvent(goog.events.EventType.FOCUS);204 // keydown and input events seems to be fired indepently: even though input205 // should happen after the key event, it doesn't if the user types fast206 // enough. FF2 + linux doesn't fire keydown events for every key pressed when207 // you type fast enough. if one of the keydown events gets swallowed, two208 // input events are fired consecutively. notice that there is a similar209 // scenario, that actually does produce a valid paste action.210 // {@see testRightClickRightClickAlsoDispatchesTwoConsecutiveInputEvents}211 textarea.dispatchEvent(212 {type: goog.events.EventType.KEYDOWN, keyCode: goog.events.KeyCodes.A});213 assertFalse(pasted);214 textarea.value = 'a';215 clock.tick(216 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER -217 1);218 textarea.dispatchEvent('input');219 assertFalse(pasted);220 // second key down events gets fired on a different order221 textarea.value = 'ab';222 clock.tick(223 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER -224 1);225 textarea.dispatchEvent('input');226 assertFalse(pasted);227}228function testRightClickRightClickAlsoDispatchesTwoConsecutiveInputEvents() {229 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {230 return;231 }232 textarea.dispatchEvent(goog.events.EventType.FOCUS);233 // there is also another case that two consecutive INPUT events are fired,234 // but in a valid paste action: if the user edit -> paste -> edit -> paste,235 // it is a valid paste action.236 textarea.value = 'a';237 clock.tick(238 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +239 1);240 textarea.dispatchEvent(newBrowserEvent('input'));241 assertTrue(pasted);242 // second key down events gets fired on a different order243 textarea.value = 'ab';244 clock.tick(245 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +246 1);247 textarea.dispatchEvent(newBrowserEvent('input'));248 assertTrue(pasted);249}250function testMiddleClickWithoutFocusTriggersPasteEvent() {251 if (goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {252 return;253 }254 // if the textarea is NOT selected, and then we use the middle button,255 // FF2+linux pastes what was last highlighted, causing a paste action.256 textarea.dispatchEvent(goog.events.EventType.FOCUS);257 textarea.dispatchEvent(newBrowserEvent('input'));258 assertTrue(pasted);259}260function testMacRightClickPasteRequiresCtrlBecauseItHasOneButton() {261 if (!goog.userAgent.OPERA || !goog.userAgent.MAC) {262 return;263 }264 const handler = new goog.events.PasteHandler(textarea);265 // user clicks on the textarea and give it focus266 goog.events.listen(267 handler, goog.events.PasteHandler.EventType.PASTE,268 function() { pasted = true; });269 textarea.dispatchEvent(goog.events.EventType.FOCUS);270 assertFalse(pasted);271 textarea.dispatchEvent({type: goog.events.EventType.KEYDOWN, keyCode: 0});272 assertFalse(pasted);273 clock.tick(274 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +275 1);276 textarea.dispatchEvent(newBrowserEvent('input'));277 assertTrue(pasted);278}279function testOperaMacFiresKeyCode17WhenAppleKeyPressedButDoesNotFireKeyDown() {280 if (!goog.userAgent.OPERA || !goog.userAgent.MAC) {281 return;282 }283 const handler = new goog.events.PasteHandler(textarea);284 // user clicks on the textarea and give it focus285 goog.events.listen(286 handler, goog.events.PasteHandler.EventType.PASTE,287 function() { pasted = true; });288 textarea.dispatchEvent(goog.events.EventType.FOCUS);289 assertFalse(pasted);290 // apple key is pressed, generating a keydown event291 textarea.dispatchEvent({type: goog.events.EventType.KEYDOWN, keyCode: 17});292 assertFalse(pasted);293 clock.tick(294 goog.events.PasteHandler.MANDATORY_MS_BETWEEN_INPUT_EVENTS_TIE_BREAKER +295 1);296 // and then text is added magically without any extra keydown events.297 textarea.dispatchEvent(newBrowserEvent('input'));298 assertTrue(pasted);299}300function testScriptingDoesntTriggerPasteEvents() {301 const handlerUsedToListenForScriptingChanges =302 new goog.events.PasteHandler(textarea);303 pasted = false;304 // user clicks on the textarea and give it focus305 goog.events.listen(306 handlerUsedToListenForScriptingChanges,307 goog.events.PasteHandler.EventType.PASTE, function() { pasted = true; });308 goog.dom.getElement('foo').value = 'dear paste handler,';309 assertFalse(pasted);310 goog.dom.getElement('foo').value = 'please dont misunderstand script changes';311 assertFalse(pasted);312 goog.dom.getElement('foo').value = 'with user generated paste events';313 assertFalse(pasted);314 goog.dom.getElement('foo').value = 'thanks!';315 assertFalse(pasted);316}317function testAfterPaste() {318 if (!goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {319 return;320 }321 const handlerThatSupportsPasteEvents = new goog.events.PasteHandler(textarea);322 pasted = false;323 goog.events.listen(324 handlerThatSupportsPasteEvents, goog.events.PasteHandler.EventType.PASTE,325 function() { pasted = true; });326 let afterPasteFired = false;327 goog.events.listen(328 handlerThatSupportsPasteEvents,329 goog.events.PasteHandler.EventType.AFTER_PASTE,330 function() { afterPasteFired = true; });331 // Initial paste event comes before AFTER_PASTE has fired.332 textarea.dispatchEvent(newBrowserEvent('paste'));333 assertTrue(pasted);334 assertFalse(afterPasteFired);335 // Once text is pasted, it takes a bit to detect it, at which point336 // AFTER_PASTE is fired.337 clock.tick(goog.events.PasteHandler.PASTE_POLLING_PERIOD_MS_);338 textarea.value = 'text';339 clock.tick(goog.events.PasteHandler.PASTE_POLLING_PERIOD_MS_);340 assertTrue(afterPasteFired);341}342function testAfterPasteNotFiredIfDelayTooLong() {343 if (!goog.events.PasteHandler.SUPPORTS_NATIVE_PASTE_EVENT) {344 return;345 }346 const handlerThatSupportsPasteEvents = new goog.events.PasteHandler(textarea);347 pasted = false;348 goog.events.listen(349 handlerThatSupportsPasteEvents, goog.events.PasteHandler.EventType.PASTE,350 function() { pasted = true; });351 let afterPasteFired = false;352 goog.events.listen(353 handlerThatSupportsPasteEvents,354 goog.events.PasteHandler.EventType.AFTER_PASTE,355 function() { afterPasteFired = true; });356 // Initial paste event comes before AFTER_PASTE has fired.357 textarea.dispatchEvent(newBrowserEvent('paste'));358 assertTrue(pasted);359 assertFalse(afterPasteFired);360 // If the new text doesn't show up in time, we never fire AFTER_PASTE.361 clock.tick(goog.events.PasteHandler.PASTE_POLLING_TIMEOUT_MS_);362 textarea.value = 'text';363 clock.tick(goog.events.PasteHandler.PASTE_POLLING_PERIOD_MS_);364 assertFalse(afterPasteFired);...

Full Screen

Full Screen

Hover-test.internal.js

Source:Hover-test.internal.js Github

copy

Full Screen

...44 );45 ReactDOM.render(element, container);46 });47 it('is called after "pointerover" event', () => {48 ref.current.dispatchEvent(createPointerEvent('pointerover'));49 expect(onHoverStart).toHaveBeenCalledTimes(1);50 });51 it('is not called if "pointerover" pointerType is touch', () => {52 const event = createPointerEvent('pointerover');53 event.pointerType = 'touch';54 ref.current.dispatchEvent(event);55 expect(onHoverStart).not.toBeCalled();56 });57 it('ignores browser emulated "mouseover" event', () => {58 ref.current.dispatchEvent(createPointerEvent('pointerover'));59 ref.current.dispatchEvent(createPointerEvent('mouseover'));60 expect(onHoverStart).toHaveBeenCalledTimes(1);61 });62 // No PointerEvent fallbacks63 it('is called after "mouseover" event', () => {64 ref.current.dispatchEvent(createPointerEvent('mouseover'));65 expect(onHoverStart).toHaveBeenCalledTimes(1);66 });67 it('is not called after "touchstart"', () => {68 ref.current.dispatchEvent(createPointerEvent('touchstart'));69 ref.current.dispatchEvent(createPointerEvent('touchend'));70 ref.current.dispatchEvent(createPointerEvent('mouseover'));71 expect(onHoverStart).not.toBeCalled();72 });73 describe('delayHoverStart', () => {74 it('can be configured', () => {75 const element = (76 <Hover delayHoverStart={2000} onHoverStart={onHoverStart}>77 <div ref={ref} />78 </Hover>79 );80 ReactDOM.render(element, container);81 ref.current.dispatchEvent(createPointerEvent('pointerover'));82 jest.advanceTimersByTime(1999);83 expect(onHoverStart).not.toBeCalled();84 jest.advanceTimersByTime(1);85 expect(onHoverStart).toHaveBeenCalledTimes(1);86 });87 it('is reset if "pointerout" is dispatched during a delay', () => {88 const element = (89 <Hover delayHoverStart={500} onHoverStart={onHoverStart}>90 <div ref={ref} />91 </Hover>92 );93 ReactDOM.render(element, container);94 ref.current.dispatchEvent(createPointerEvent('pointerover'));95 jest.advanceTimersByTime(499);96 ref.current.dispatchEvent(createPointerEvent('pointerout'));97 jest.advanceTimersByTime(1);98 expect(onHoverStart).not.toBeCalled();99 ref.current.dispatchEvent(createPointerEvent('pointerover'));100 jest.runAllTimers();101 expect(onHoverStart).toHaveBeenCalledTimes(1);102 });103 it('onHoverStart is called synchronously if delay is 0ms', () => {104 const element = (105 <Hover delayHoverStart={0} onHoverStart={onHoverStart}>106 <div ref={ref} />107 </Hover>108 );109 ReactDOM.render(element, container);110 ref.current.dispatchEvent(createPointerEvent('pointerover'));111 expect(onHoverStart).toHaveBeenCalledTimes(1);112 });113 it('onHoverStart is only called once per active hover', () => {114 const element = (115 <Hover116 delayHoverStart={500}117 delayHoverEnd={100}118 onHoverStart={onHoverStart}>119 <div ref={ref} />120 </Hover>121 );122 ReactDOM.render(element, container);123 ref.current.dispatchEvent(createPointerEvent('pointerover'));124 jest.advanceTimersByTime(500);125 expect(onHoverStart).toHaveBeenCalledTimes(1);126 ref.current.dispatchEvent(createPointerEvent('pointerout'));127 jest.advanceTimersByTime(10);128 ref.current.dispatchEvent(createPointerEvent('pointerover'));129 jest.runAllTimers();130 expect(onHoverStart).toHaveBeenCalledTimes(1);131 });132 });133 });134 describe('onHoverChange', () => {135 let onHoverChange, ref;136 beforeEach(() => {137 onHoverChange = jest.fn();138 ref = React.createRef();139 const element = (140 <Hover onHoverChange={onHoverChange}>141 <div ref={ref} />142 </Hover>143 );144 ReactDOM.render(element, container);145 });146 it('is called after "pointerover" and "pointerout" events', () => {147 ref.current.dispatchEvent(createPointerEvent('pointerover'));148 expect(onHoverChange).toHaveBeenCalledTimes(1);149 expect(onHoverChange).toHaveBeenCalledWith(true);150 ref.current.dispatchEvent(createPointerEvent('pointerout'));151 expect(onHoverChange).toHaveBeenCalledTimes(2);152 expect(onHoverChange).toHaveBeenCalledWith(false);153 });154 // No PointerEvent fallbacks155 it('is called after "mouseover" and "mouseout" events', () => {156 ref.current.dispatchEvent(createPointerEvent('mouseover'));157 expect(onHoverChange).toHaveBeenCalledTimes(1);158 expect(onHoverChange).toHaveBeenCalledWith(true);159 ref.current.dispatchEvent(createPointerEvent('mouseout'));160 expect(onHoverChange).toHaveBeenCalledTimes(2);161 expect(onHoverChange).toHaveBeenCalledWith(false);162 });163 });164 describe('onHoverEnd', () => {165 let onHoverEnd, ref;166 beforeEach(() => {167 onHoverEnd = jest.fn();168 ref = React.createRef();169 const element = (170 <Hover onHoverEnd={onHoverEnd}>171 <div ref={ref} />172 </Hover>173 );174 ReactDOM.render(element, container);175 });176 it('is called after "pointerout" event', () => {177 ref.current.dispatchEvent(createPointerEvent('pointerover'));178 ref.current.dispatchEvent(createPointerEvent('pointerout'));179 expect(onHoverEnd).toHaveBeenCalledTimes(1);180 });181 it('is not called if "pointerover" pointerType is touch', () => {182 const event = createPointerEvent('pointerover');183 event.pointerType = 'touch';184 ref.current.dispatchEvent(event);185 ref.current.dispatchEvent(createPointerEvent('pointerout'));186 expect(onHoverEnd).not.toBeCalled();187 });188 it('ignores browser emulated "mouseout" event', () => {189 ref.current.dispatchEvent(createPointerEvent('pointerover'));190 ref.current.dispatchEvent(createPointerEvent('pointerout'));191 ref.current.dispatchEvent(createPointerEvent('mouseout'));192 expect(onHoverEnd).toHaveBeenCalledTimes(1);193 });194 it('is called after "pointercancel" event', () => {195 ref.current.dispatchEvent(createPointerEvent('pointerover'));196 ref.current.dispatchEvent(createPointerEvent('pointercancel'));197 expect(onHoverEnd).toHaveBeenCalledTimes(1);198 });199 it('is not called again after "pointercancel" event if it follows "pointerout"', () => {200 ref.current.dispatchEvent(createPointerEvent('pointerover'));201 ref.current.dispatchEvent(createPointerEvent('pointerout'));202 ref.current.dispatchEvent(createPointerEvent('pointercancel'));203 expect(onHoverEnd).toHaveBeenCalledTimes(1);204 });205 // No PointerEvent fallbacks206 it('is called after "mouseout" event', () => {207 ref.current.dispatchEvent(createPointerEvent('mouseover'));208 ref.current.dispatchEvent(createPointerEvent('mouseout'));209 expect(onHoverEnd).toHaveBeenCalledTimes(1);210 });211 it('is not called after "touchend"', () => {212 ref.current.dispatchEvent(createPointerEvent('touchstart'));213 ref.current.dispatchEvent(createPointerEvent('touchend'));214 ref.current.dispatchEvent(createPointerEvent('mouseout'));215 expect(onHoverEnd).not.toBeCalled();216 });217 describe('delayHoverEnd', () => {218 it('can be configured', () => {219 const element = (220 <Hover delayHoverEnd={2000} onHoverEnd={onHoverEnd}>221 <div ref={ref} />222 </Hover>223 );224 ReactDOM.render(element, container);225 ref.current.dispatchEvent(createPointerEvent('pointerover'));226 ref.current.dispatchEvent(createPointerEvent('pointerout'));227 jest.advanceTimersByTime(1999);228 expect(onHoverEnd).not.toBeCalled();229 jest.advanceTimersByTime(1);230 expect(onHoverEnd).toHaveBeenCalledTimes(1);231 });232 it('delayHoverEnd is called synchronously if delay is 0ms', () => {233 const element = (234 <Hover delayHoverEnd={0} onHoverEnd={onHoverEnd}>235 <div ref={ref} />236 </Hover>237 );238 ReactDOM.render(element, container);239 ref.current.dispatchEvent(createPointerEvent('pointerover'));240 ref.current.dispatchEvent(createPointerEvent('pointerout'));241 expect(onHoverEnd).toHaveBeenCalledTimes(1);242 });243 it('onHoverEnd is only called once per active hover', () => {244 const element = (245 <Hover delayHoverEnd={500} onHoverEnd={onHoverEnd}>246 <div ref={ref} />247 </Hover>248 );249 ReactDOM.render(element, container);250 ref.current.dispatchEvent(createPointerEvent('pointerover'));251 ref.current.dispatchEvent(createPointerEvent('pointerout'));252 jest.advanceTimersByTime(499);253 ref.current.dispatchEvent(createPointerEvent('pointerover'));254 jest.advanceTimersByTime(100);255 ref.current.dispatchEvent(createPointerEvent('pointerout'));256 jest.runAllTimers();257 expect(onHoverEnd).toHaveBeenCalledTimes(1);258 });259 it('onHoverEnd is not called if "pointerover" is dispatched during a delay', () => {260 const element = (261 <Hover delayHoverEnd={500} onHoverEnd={onHoverEnd}>262 <div ref={ref} />263 </Hover>264 );265 ReactDOM.render(element, container);266 ref.current.dispatchEvent(createPointerEvent('pointerover'));267 ref.current.dispatchEvent(createPointerEvent('pointerout'));268 jest.advanceTimersByTime(499);269 ref.current.dispatchEvent(createPointerEvent('pointerover'));270 jest.advanceTimersByTime(1);271 expect(onHoverEnd).not.toBeCalled();272 });273 it('onHoverEnd is not called if there was no active hover', () => {274 const element = (275 <Hover276 delayHoverStart={500}277 delayHoverEnd={100}278 onHoverEnd={onHoverEnd}>279 <div ref={ref} />280 </Hover>281 );282 ReactDOM.render(element, container);283 ref.current.dispatchEvent(createPointerEvent('pointerover'));284 ref.current.dispatchEvent(createPointerEvent('pointerout'));285 jest.runAllTimers();286 expect(onHoverEnd).not.toBeCalled();287 });288 });289 });290 it('expect displayName to show up for event component', () => {291 expect(Hover.displayName).toBe('Hover');292 });...

Full Screen

Full Screen

createWebSpeechMock.js

Source:createWebSpeechMock.js Github

copy

Full Screen

...79 }, this);80 }81 microphoneMuted() {82 this.abort = this.stop = NULL_FN;83 this.dispatchEvent({ type: 'start' });84 this.dispatchEvent({ type: 'audiostart' });85 this.dispatchEvent({ type: 'audioend' });86 this.dispatchEvent({ type: 'error', error: 'no-speech' });87 this.dispatchEvent({ type: 'end' });88 }89 birdTweet() {90 this.abort = this.stop = NULL_FN;91 this.dispatchEvent({ type: 'start' });92 this.dispatchEvent({ type: 'audiostart' });93 this.dispatchEvent({ type: 'soundstart' });94 this.dispatchEvent({ type: 'soundend' });95 this.dispatchEvent({ type: 'audioend' });96 this.dispatchEvent({ type: 'end' });97 }98 unrecognizableSpeech() {99 this.abort = this.stop = NULL_FN;100 this.dispatchEvent({ type: 'start' });101 this.dispatchEvent({ type: 'audiostart' });102 this.dispatchEvent({ type: 'soundstart' });103 this.dispatchEvent({ type: 'speechstart' });104 this.dispatchEvent({ type: 'speechend' });105 this.dispatchEvent({ type: 'soundend' });106 this.dispatchEvent({ type: 'audioend' });107 this.dispatchEvent({ type: 'end' });108 }109 airplaneMode() {110 this.abort = this.stop = NULL_FN;111 this.dispatchEvent({ type: 'start' });112 this.dispatchEvent({ type: 'audiostart' });113 this.dispatchEvent({ type: 'audioend' });114 this.dispatchEvent({ type: 'error', error: 'network' });115 this.dispatchEvent({ type: 'end' });116 }117 accessDenied() {118 this.abort = this.stop = NULL_FN;119 this.dispatchEvent({ type: 'error', error: 'not-allowed' });120 this.dispatchEvent({ type: 'end' });121 }122 abortAfterAudioStart() {123 this.abort = () => {124 this.dispatchEvent({ type: 'audioend' });125 this.dispatchEvent({ type: 'error', error: 'aborted' });126 this.dispatchEvent({ type: 'end' });127 };128 this.stop = NULL_FN;129 this.dispatchEvent({ type: 'start' });130 this.dispatchEvent({ type: 'audiostart' });131 }132 recognize(transcript) {133 this.abort = this.stop = NULL_FN;134 this.dispatchEvent({ type: 'start' });135 this.dispatchEvent({ type: 'audiostart' });136 this.dispatchEvent({ type: 'soundstart' });137 this.dispatchEvent({ type: 'speechstart' });138 this.interimResults &&139 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });140 this.dispatchEvent({ type: 'speechend' });141 this.dispatchEvent({ type: 'soundend' });142 this.dispatchEvent({ type: 'audioend' });143 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(true, transcript) });144 this.dispatchEvent({ type: 'end' });145 }146 recognizing(transcript) {147 this.abort = this.stop = NULL_FN;148 this.dispatchEvent({ type: 'start' });149 this.dispatchEvent({ type: 'audiostart' });150 this.dispatchEvent({ type: 'soundstart' });151 this.dispatchEvent({ type: 'speechstart' });152 this.interimResults &&153 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });154 }155 recognizeButAborted(transcript) {156 this.abort = () => {157 this.dispatchEvent({ type: 'speechend' });158 this.dispatchEvent({ type: 'soundend' });159 this.dispatchEvent({ type: 'audioend' });160 this.dispatchEvent({ type: 'error', error: 'aborted' });161 this.dispatchEvent({ type: 'end' });162 };163 this.stop = NULL_FN;164 this.dispatchEvent({ type: 'start' });165 this.dispatchEvent({ type: 'audiostart' });166 this.dispatchEvent({ type: 'soundstart' });167 this.dispatchEvent({ type: 'speechstart' });168 this.interimResults &&169 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });170 }171 recognizeButNotConfident(transcript) {172 this.abort = this.stop = NULL_FN;173 this.dispatchEvent({ type: 'start' });174 this.dispatchEvent({ type: 'audiostart' });175 this.dispatchEvent({ type: 'soundstart' });176 this.dispatchEvent({ type: 'speechstart' });177 this.interimResults &&178 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });179 this.dispatchEvent({ type: 'speechend' });180 this.dispatchEvent({ type: 'soundend' });181 this.dispatchEvent({ type: 'audioend' });182 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });183 this.dispatchEvent({ type: 'end' });184 }185}186[187 'audiostart',188 'audioend',189 'end',190 'error',191 'nomatch',192 'result',193 'soundstart',194 'soundend',195 'speechstart',196 'speechend',197 'start'198].forEach(name => defineEventAttribute(SpeechRecognition.prototype, name));199class SpeechGrammarList {200 addFromString() {201 throw new Error('Not implemented');202 }203 addFromURI() {204 throw new Error('Not implemented');205 }206}207const SPEECH_SYNTHESIS_VOICES = [208 {209 default: true,210 lang: 'en-US',211 localService: true,212 name: 'Mock Voice (en-US)',213 voiceURI: 'mock://web-speech/voice/en-US'214 },215 {216 default: false,217 lang: 'zh-YUE',218 localService: true,219 name: 'Mock Voice (zh-YUE)',220 voiceURI: 'mock://web-speech/voice/zh-YUE'221 }222];223class SpeechSynthesis extends EventTarget {224 constructor() {225 super();226 this.ignoreFirstUtteranceIfEmpty = true;227 }228 getVoices() {229 return SPEECH_SYNTHESIS_VOICES;230 }231 cancel() {232 speechSynthesisBroker.cancel();233 }234 pause() {235 throw new Error('pause is not implemented.');236 }237 resume() {238 throw new Error('resume is not implemented.');239 }240 speak(utterance) {241 // We prime the speech engine by sending an empty utterance on start.242 // We should ignore the first utterance if it is empty.243 if (!this.ignoreFirstUtteranceIfEmpty || utterance.text) {244 speechSynthesisBroker.produce(utterance);245 }246 this.ignoreFirstUtteranceIfEmpty = false;247 }248}249defineEventAttribute(SpeechSynthesis.prototype, 'voiceschanged');250class SpeechSynthesisUtterance extends EventTarget {251 constructor(text) {252 super();253 const [firstVoice] = SPEECH_SYNTHESIS_VOICES;254 this.lang = firstVoice.lang;255 this.pitch = 1;256 this.rate = 1;257 this.text = text;258 this.voice = firstVoice;259 this.volume = 1;260 }261}262['boundary', 'end', 'error', 'mark', 'pause', 'resume', 'start'].forEach(name =>263 defineEventAttribute(SpeechSynthesisUtterance.prototype, name)264);265export default function createWebSpeechMock() {266 return {267 mockEndSynthesize() {268 return new Promise(resolve => {269 speechSynthesisBroker.consume(utterance => {270 utterance.dispatchEvent({ type: 'end' });271 const { lang, pitch, rate, text, voice, volume } = utterance;272 resolve({ lang, pitch, rate, text, voice, volume });273 });274 });275 },276 mockErrorSynthesize(error = 'artificial-error') {277 return new Promise(resolve => {278 speechSynthesisBroker.consume(utterance => {279 utterance.dispatchEvent({ error, type: 'error' });280 const { lang, pitch, rate, text, voice, volume } = utterance;281 resolve({ lang, pitch, rate, text, voice, volume });282 });283 });284 },285 mockRecognize(...args) {286 speechRecognitionBroker.produce(...args);287 },288 mockStartSynthesize() {289 const [utterance] = speechSynthesisBroker.peek() || [];290 if (!utterance) {291 throw new Error('No utterance pending synthesize.');292 }293 utterance.dispatchEvent({ type: 'start' });294 const { lang, pitch, rate, text, voice, volume } = utterance;295 return { lang, pitch, rate, text, voice, volume };296 },297 speechRecognitionStartCalled() {298 const context = speechRecognitionBroker.hasConsumer();299 if (context) {300 const { continuous, grammars, interimResults, lang, maxAlternatives, serviceURI } = context;301 return {302 continuous,303 grammars,304 interimResults,305 lang,306 maxAlternatives,307 serviceURI...

Full Screen

Full Screen

mockWebSpeech.js

Source:mockWebSpeech.js Github

copy

Full Screen

...61 }, this);62 }63 microphoneMuted() {64 this.abort = this.stop = NULL_FN;65 this.dispatchEvent({ type: 'start' });66 this.dispatchEvent({ type: 'audiostart' });67 this.dispatchEvent({ type: 'audioend' });68 this.dispatchEvent({ type: 'error', error: 'no-speech' });69 this.dispatchEvent({ type: 'end' });70 }71 birdTweet() {72 this.abort = this.stop = NULL_FN;73 this.dispatchEvent({ type: 'start' });74 this.dispatchEvent({ type: 'audiostart' });75 this.dispatchEvent({ type: 'soundstart' });76 this.dispatchEvent({ type: 'soundend' });77 this.dispatchEvent({ type: 'audioend' });78 this.dispatchEvent({ type: 'end' });79 }80 unrecognizableSpeech() {81 this.abort = this.stop = NULL_FN;82 this.dispatchEvent({ type: 'start' });83 this.dispatchEvent({ type: 'audiostart' });84 this.dispatchEvent({ type: 'soundstart' });85 this.dispatchEvent({ type: 'speechstart' });86 this.dispatchEvent({ type: 'speechend' });87 this.dispatchEvent({ type: 'soundend' });88 this.dispatchEvent({ type: 'audioend' });89 this.dispatchEvent({ type: 'end' });90 }91 airplaneMode() {92 this.abort = this.stop = NULL_FN;93 this.dispatchEvent({ type: 'start' });94 this.dispatchEvent({ type: 'audiostart' });95 this.dispatchEvent({ type: 'audioend' });96 this.dispatchEvent({ type: 'error', error: 'network' });97 this.dispatchEvent({ type: 'end' });98 }99 accessDenied() {100 this.abort = this.stop = NULL_FN;101 this.dispatchEvent({ type: 'error', error: 'not-allowed' });102 this.dispatchEvent({ type: 'end' });103 }104 abortAfterAudioStart() {105 this.abort = () => {106 this.dispatchEvent({ type: 'audioend' });107 this.dispatchEvent({ type: 'error', error: 'aborted' });108 this.dispatchEvent({ type: 'end' });109 };110 this.stop = NULL_FN;111 this.dispatchEvent({ type: 'start' });112 this.dispatchEvent({ type: 'audiostart' });113 }114 recognize(transcript) {115 this.abort = this.stop = NULL_FN;116 this.dispatchEvent({ type: 'start' });117 this.dispatchEvent({ type: 'audiostart' });118 this.dispatchEvent({ type: 'soundstart' });119 this.dispatchEvent({ type: 'speechstart' });120 this.interimResults &&121 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });122 this.dispatchEvent({ type: 'speechend' });123 this.dispatchEvent({ type: 'soundend' });124 this.dispatchEvent({ type: 'audioend' });125 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(true, transcript) });126 this.dispatchEvent({ type: 'end' });127 }128 recognizing(transcript) {129 this.abort = this.stop = NULL_FN;130 this.dispatchEvent({ type: 'start' });131 this.dispatchEvent({ type: 'audiostart' });132 this.dispatchEvent({ type: 'soundstart' });133 this.dispatchEvent({ type: 'speechstart' });134 this.interimResults &&135 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });136 }137 recognizeButAborted(transcript) {138 this.abort = () => {139 this.dispatchEvent({ type: 'speechend' });140 this.dispatchEvent({ type: 'soundend' });141 this.dispatchEvent({ type: 'audioend' });142 this.dispatchEvent({ type: 'error', error: 'aborted' });143 this.dispatchEvent({ type: 'end' });144 };145 this.stop = NULL_FN;146 this.dispatchEvent({ type: 'start' });147 this.dispatchEvent({ type: 'audiostart' });148 this.dispatchEvent({ type: 'soundstart' });149 this.dispatchEvent({ type: 'speechstart' });150 this.interimResults &&151 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });152 }153 recognizeButNotConfident(transcript) {154 this.abort = this.stop = NULL_FN;155 this.dispatchEvent({ type: 'start' });156 this.dispatchEvent({ type: 'audiostart' });157 this.dispatchEvent({ type: 'soundstart' });158 this.dispatchEvent({ type: 'speechstart' });159 this.interimResults &&160 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });161 this.dispatchEvent({ type: 'speechend' });162 this.dispatchEvent({ type: 'soundend' });163 this.dispatchEvent({ type: 'audioend' });164 this.dispatchEvent({ type: 'result', results: createSpeechRecognitionResults(false, transcript) });165 this.dispatchEvent({ type: 'end' });166 }167}168[169 'audiostart',170 'audioend',171 'end',172 'error',173 'nomatch',174 'result',175 'soundstart',176 'soundend',177 'speechstart',178 'speechend',179 'start'180].forEach(name => defineEventAttribute(SpeechRecognition.prototype, name));181class SpeechGrammarList {182 addFromString() {183 throw new Error('Not implemented');184 }185 addFromURI() {186 throw new Error('Not implemented');187 }188}189const SPEECH_SYNTHESIS_VOICES = [190 {191 default: true,192 lang: 'en-US',193 localService: true,194 name: 'Mock Voice (en-US)',195 voiceURI: 'mock://web-speech/voice/en-US'196 },197 {198 default: false,199 lang: 'zh-YUE',200 localService: true,201 name: 'Mock Voice (zh-YUE)',202 voiceURI: 'mock://web-speech/voice/zh-YUE'203 }204];205class SpeechSynthesis extends EventTarget {206 constructor() {207 super();208 this.ignoreFirstUtteranceIfEmpty = true;209 }210 getVoices() {211 return SPEECH_SYNTHESIS_VOICES;212 }213 cancel() {214 speechSynthesisBroker.cancel();215 }216 pause() {217 throw new Error('pause is not implemented.');218 }219 resume() {220 throw new Error('resume is not implemented.');221 }222 speak(utterance) {223 // We prime the speech engine by sending an empty utterance on start.224 // We should ignore the first utterance if it is empty.225 if (!this.ignoreFirstUtteranceIfEmpty || utterance.text) {226 speechSynthesisBroker.produce(utterance);227 }228 this.ignoreFirstUtteranceIfEmpty = false;229 }230}231defineEventAttribute(SpeechSynthesis.prototype, 'voiceschanged');232class SpeechSynthesisUtterance extends EventTarget {233 constructor(text) {234 super();235 this.lang = SPEECH_SYNTHESIS_VOICES[0].lang;236 this.pitch = 1;237 this.rate = 1;238 this.text = text;239 this.voice = SPEECH_SYNTHESIS_VOICES[0];240 this.volume = 1;241 }242}243['boundary', 'end', 'error', 'mark', 'pause', 'resume', 'start'].forEach(name =>244 defineEventAttribute(SpeechSynthesisUtterance.prototype, name)245);246window.WebSpeechMock = {247 mockEndSynthesize() {248 return new Promise(resolve => {249 speechSynthesisBroker.consume(utterance => {250 utterance.dispatchEvent({ type: 'end' });251 const { lang, pitch, rate, text, voice, volume } = utterance;252 resolve({ lang, pitch, rate, text, voice, volume });253 });254 });255 },256 mockErrorSynthesize(error = 'artificial-error') {257 return new Promise(resolve => {258 speechSynthesisBroker.consume(utterance => {259 utterance.dispatchEvent({ error, type: 'error' });260 const { lang, pitch, rate, text, voice, volume } = utterance;261 resolve({ lang, pitch, rate, text, voice, volume });262 });263 });264 },265 mockRecognize(...args) {266 speechRecognitionBroker.produce(...args);267 },268 mockStartSynthesize() {269 const [utterance] = speechSynthesisBroker.peek() || [];270 if (!utterance) {271 throw new Error('No utterance pending synthesize.');272 }273 utterance.dispatchEvent({ type: 'start' });274 const { lang, pitch, rate, text, voice, volume } = utterance;275 return { lang, pitch, rate, text, voice, volume };276 },277 speechRecognitionStartCalled() {278 const context = speechRecognitionBroker.hasConsumer();279 if (context) {280 const { continuous, grammars, interimResults, lang, maxAlternatives, serviceURI } = context;281 return {282 continuous,283 grammars,284 interimResults,285 lang,286 maxAlternatives,287 serviceURI...

Full Screen

Full Screen

zoomOnTouch.spec.js

Source:zoomOnTouch.spec.js Github

copy

Full Screen

...19 pointerMoveEvent1.pageY = 125;20 pointerMoveEvent2.pointerId = 2;21 pointerMoveEvent2.pageX = 175;22 pointerMoveEvent2.pageY = 175;23 cropper.cropper.dispatchEvent(pointerDownEvent1);24 cropper.cropper.dispatchEvent(pointerDownEvent2);25 cropper.cropper.dispatchEvent(pointerMoveEvent1);26 cropper.cropper.dispatchEvent(pointerMoveEvent2);27 } else {28 const touchStartEvent1 = window.createEvent('touchstart');29 const touchStartEvent2 = window.createEvent('touchstart');30 const touchMoveEvent1 = window.createEvent('touchmove');31 const touchMoveEvent2 = window.createEvent('touchmove');32 touchStartEvent1.changedTouches = {33 0: {34 identifier: 1,35 pageX: 100,36 pageY: 100,37 },38 length: 1,39 };40 touchStartEvent2.changedTouches = {41 0: {42 identifier: 2,43 pageX: 200,44 pageY: 200,45 },46 length: 1,47 };48 touchMoveEvent1.changedTouches = {49 0: {50 identifier: 1,51 pageX: 125,52 pageY: 125,53 },54 length: 1,55 };56 touchMoveEvent2.changedTouches = {57 0: {58 identifier: 2,59 pageX: 175,60 pageY: 175,61 },62 length: 1,63 };64 cropper.cropper.dispatchEvent(touchStartEvent1);65 cropper.cropper.dispatchEvent(touchStartEvent2);66 cropper.cropper.dispatchEvent(touchMoveEvent1);67 cropper.cropper.dispatchEvent(touchMoveEvent2);68 }69 },70 zoom() {71 done();72 },73 });74 expect(cropper.options.zoomOnTouch).to.be.true;75 });76 it('should not zoom on touch', (done) => {77 const image = window.createImage();78 const cropper = new Cropper(image, {79 zoomOnTouch: false,80 ready() {81 if (window.PointerEvent) {82 cropper.cropper.dispatchEvent(new PointerEvent('pointerdown', {83 pointerId: 1,84 pageX: 100,85 pageY: 100,86 }));87 cropper.cropper.dispatchEvent(new PointerEvent('pointerdown', {88 pointerId: 2,89 pageX: 200,90 pageY: 200,91 }));92 cropper.cropper.dispatchEvent(new PointerEvent('pointermove', {93 pointerId: 1,94 pageX: 125,95 pageY: 125,96 }));97 cropper.cropper.dispatchEvent(new PointerEvent('pointermove', {98 pointerId: 2,99 pageX: 175,100 pageY: 175,101 }));102 cropper.cropper.dispatchEvent(new PointerEvent('pointerup', {103 pointerId: 1,104 pageX: 125,105 pageY: 125,106 }));107 cropper.cropper.dispatchEvent(new PointerEvent('pointerup', {108 pointerId: 2,109 pageX: 175,110 pageY: 175,111 }));112 } else {113 cropper.cropper.dispatchEvent(new TouchEvent('touchstart', {114 changedTouches: {115 0: {116 identifier: 1,117 pageX: 100,118 pageY: 100,119 },120 1: {121 identifier: 2,122 pageX: 200,123 pageY: 200,124 },125 length: 2,126 },127 }));128 cropper.cropper.dispatchEvent(new TouchEvent('touchmove', {129 changedTouches: {130 0: {131 identifier: 1,132 pageX: 125,133 pageY: 125,134 },135 1: {136 identifier: 2,137 pageX: 175,138 pageY: 175,139 },140 length: 2,141 },142 }));143 cropper.cropper.dispatchEvent(new TouchEvent('touchend', {144 changedTouches: {145 0: {146 identifier: 1,147 pageX: 125,148 pageY: 125,149 },150 1: {151 identifier: 2,152 pageX: 175,153 pageY: 175,154 },155 length: 2,156 },157 }));...

Full Screen

Full Screen

observable.test.js

Source:observable.test.js Github

copy

Full Screen

...14 listener = sinon.spy();15 });16 it('registers a listener for events of the given type', function() {17 observable.on('foo', listener);18 observable.dispatchEvent('foo');19 expect(listener.calledOnce).to.be(true);20 observable.dispatchEvent('foo');21 expect(listener.callCount).to.be(2);22 });23 it('accepts an array of event types', function() {24 observable.on(['foo', 'bar'], listener);25 observable.dispatchEvent('foo');26 expect(listener.calledOnce).to.be(true);27 observable.dispatchEvent('bar');28 expect(listener.callCount).to.be(2);29 });30 it('accepts an optional `this` arg for the listener', function() {31 var thisArg = {};32 observable.on('foo', listener, thisArg);33 observable.dispatchEvent('foo');34 expect(listener.calledOnce).to.be(true);35 expect(listener.calledOn(thisArg)).to.be(true);36 });37 it('returns a listener key', function() {38 var key = observable.on('foo', listener);39 expect(key).to.be.a(goog.events.Listener);40 });41 });42 describe('#once()', function() {43 var observable, listener;44 beforeEach(function() {45 observable = new ol.Observable();46 listener = sinon.spy();47 });48 it('registers a listener that is only called once', function() {49 observable.once('foo', listener);50 observable.dispatchEvent('foo');51 expect(listener.calledOnce).to.be(true);52 observable.dispatchEvent('foo');53 expect(listener.callCount).to.be(1);54 });55 it('accepts an array of event types (called once for each)', function() {56 observable.once(['foo', 'bar'], listener);57 observable.dispatchEvent('foo');58 expect(listener.calledOnce).to.be(true);59 observable.dispatchEvent('foo');60 expect(listener.callCount).to.be(1);61 observable.dispatchEvent('bar');62 expect(listener.callCount).to.be(2);63 observable.dispatchEvent('bar');64 expect(listener.callCount).to.be(2);65 });66 it('accepts an optional `this` arg for the listener', function() {67 var thisArg = {};68 observable.once('foo', listener, thisArg);69 observable.dispatchEvent('foo');70 expect(listener.calledOnce).to.be(true);71 expect(listener.calledOn(thisArg)).to.be(true);72 });73 it('returns a listener key', function() {74 var key = observable.once('foo', listener);75 expect(key).to.be.a(goog.events.Listener);76 });77 });78 describe('#un()', function() {79 var observable, listener;80 beforeEach(function() {81 observable = new ol.Observable();82 listener = sinon.spy();83 });84 it('unregisters a previously registered listener', function() {85 observable.on('foo', listener);86 observable.dispatchEvent('foo');87 expect(listener.calledOnce).to.be(true);88 observable.un('foo', listener);89 observable.dispatchEvent('foo');90 expect(listener.calledOnce).to.be(true);91 });92 it('accepts a `this` arg', function() {93 var thisArg = {};94 observable.on('foo', listener, thisArg);95 observable.dispatchEvent('foo');96 expect(listener.calledOnce).to.be(true);97 // will not unregister without the same thisArg98 observable.un('foo', listener);99 observable.dispatchEvent('foo');100 expect(listener.callCount).to.be(2);101 // properly unregister by providing the same thisArg102 observable.un('foo', listener, thisArg);103 observable.dispatchEvent('foo');104 expect(listener.callCount).to.be(2);105 });106 });107 describe('ol.Observable.unByKey()', function() {108 var observable, listener;109 beforeEach(function() {110 observable = new ol.Observable();111 listener = sinon.spy();112 });113 it('unregisters a listener given the key returned by `on`', function() {114 var key = observable.on('foo', listener);115 observable.dispatchEvent('foo');116 expect(listener.calledOnce).to.be(true);117 ol.Observable.unByKey(key);118 observable.dispatchEvent('foo');119 expect(listener.callCount).to.be(1);120 });121 });122});123goog.require('goog.events.EventTarget');124goog.require('goog.events.Listener');...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });7 await browser.close();8})();9const puppeteer = require('puppeteer');10(async () => {11 const browser = await puppeteer.launch();12 const page = await browser.newPage();13 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });14 await browser.close();15})();16const puppeteer = require('puppeteer');17(async () => {18 const browser = await puppeteer.launch();19 const page = await browser.newPage();20 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });21 await browser.close();22})();23const puppeteer = require('puppeteer');24(async () => {25 const browser = await puppeteer.launch();26 const page = await browser.newPage();27 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });28 await browser.close();29})();30const puppeteer = require('puppeteer');31(async () => {32 const browser = await puppeteer.launch();33 const page = await browser.newPage();34 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });35 await browser.close();36})();37const puppeteer = require('puppeteer');38(async () => {39 const browser = await puppeteer.launch();40 const page = await browser.newPage();41 await page.dispatchEvent('input[name="q"]', 'input', { value: 'hello' });42 await browser.close();43})();

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2(async () => {3 const browser = await chromium.launch({headless: false});4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.dispatchEvent('input[name="q"]', 'input', {data: 'hello'});7 await browser.close();8})();9const {chromium} = require('playwright');10(async () => {11 const browser = await chromium.launch({headless: false});12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.dispatchEvent('input[name="q"]', 'input', {data: 'hello'});15 await browser.close();16})();17const {chromium} = require('playwright');18(async () => {19 const browser = await chromium.launch({headless: false});20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.dispatchEvent('input[name="q"]', 'input', {data: 'hello'});23 await browser.close();24})();25Error: Protocol error (DOM.dispatchEvent): Cannot find context with specified id26const {chromium} = require('playwright');27(async () => {28 const browser = await chromium.launch({headless: false});29 const context = await browser.newContext();30 const page = await context.newPage();31 await page.dispatchEvent('input[name="q"]', 'input', {data: 'hello'});32 await browser.close();33})();34Error: Protocol error (DOM.dispatchEvent): Cannot find context with specified id

Full Screen

Using AI Code Generation

copy

Full Screen

1await page.dispatchEvent('button', 'click');2await page.$('button').dispatchEvent('click');3await page.frames()[0].dispatchEvent('button', 'click');4await page.evaluateHandle(() => document.body).dispatchEvent('click');5await page.waitForEvent('worker').dispatchEvent('click');6await page.waitForEvent('websocket').dispatchEvent('click');7await page.waitForEvent('console').dispatchEvent('click');8await page.waitForEvent('dialog').dispatchEvent('click');9await page.waitForEvent('download').dispatchEvent('click');10await page.waitForEvent('request').dispatchEvent('click');11await page.waitForEvent('response').dispatchEvent('click');12await page.waitForEvent('stream').dispatchEvent('click');13await page.dispatchEvent('button', 'click');14await page.$('button').dispatchEvent('click');15await page.frames()[0].dispatchEvent('button', 'click');16await page.evaluateHandle(() => document.body).dispatchEvent('click');17await page.waitForEvent('worker').dispatchEvent('click');18await page.waitForEvent('websocket').dispatchEvent('click');19await page.waitForEvent('console').dispatchEvent('click');

Full Screen

Using AI Code Generation

copy

Full Screen

1const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');2const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');3const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');4const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');5const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');6const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');7const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');8const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');9const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');10const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');11const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');12const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');13const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');14const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');15const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');16const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');17const { dispatchEvent } = require('playwright/lib/internal/inspectorInstrumentation');

Full Screen

Using AI Code Generation

copy

Full Screen

1const {chromium} = require('playwright');2const {dispatchEvent} = require('playwright/lib/internal/protocol/protocol.js');3(async () => {4 const browser = await chromium.launch({headless: false});5 const context = await browser.newContext();6 const page = await context.newPage();7 await dispatchEvent(page, 'keydown', {key: 'a', code: 'KeyA'});8 await page.close();9 await browser.close();10})();11const {helper} = require('./helper');12const {Events} = require('../events');13 * @param {!Page} page14 * @param {string} type15 * @param {!Object=} eventInit16 * @return {!Promise}17module.exports.dispatchEvent = async function(page, type, eventInit) {18 const event = new Event(type, eventInit);19 event._fromPlaywright = true;20 await page._delegate.dispatchEvent(event);21};22const {helper} = require('./helper');23const {Events} = require('./events');24 * @param {!Event} event25Page.prototype.dispatchEvent = async function(event) {26 await this._delegate.dispatchEvent(event);27};28const {helper} = require('../helper');29const {Events} = require('../events');30 * @param {!Event} event31CrPage.prototype.dispatchEvent = async function(event) {32 await this._client.send('Input.dispatchKeyEvent', {33 });34};35const {helper} = require('../helper');

Full Screen

Using AI Code Generation

copy

Full Screen

1const {dispatchEvent} = require('playwright-core/lib/server/injected/injectedScriptSource');2const {dispatchEvent} = require('playwright/lib/server/injected/injectedScriptSource');3const {dispatchEvent} = require('playwright-chromium/lib/server/injected/injectedScriptSource');4const {dispatchEvent} = require('playwright-firefox/lib/server/injected/injectedScriptSource');5const {dispatchEvent} = require('playwright-webkit/lib/server/injected/injectedScriptSource');6const {dispatchEvent} = require('playwright-electron/lib/server/injected/injectedScriptSource');7const {dispatchEvent} = require('playwright-android/lib/server/injected/injectedScriptSource');8const {dispatchEvent} = require('playwright-ios/lib/server/injected/injectedScriptSource');9const {dispatchEvent} = require('puppeteer/lib/cjs/puppeteer/common/DOMWorld.js');10const {dispatchEvent} = require('puppeteer-core/lib/cjs/puppeteer/common/DOMWorld.js');11const {dispatchEvent} = require('puppeteer-firefox/lib/cjs/puppeteer/common/DOMWorld.js');12const {dispatchEvent} = require('puppeteer-ios/lib/cjs/puppeteer/common/DOMWorld.js');13const {dispatchEvent} = require('puppeteer-android/lib/cjs/puppeteer/common/DOMWorld.js');14const {dispatchEvent} = require('puppeteer-electron/lib/cjs/puppeteer/common/DOMWorld.js');15const {dispatchEvent} = require('puppeteer-webkit/lib/cjs/puppeteer/common/DOM

Full Screen

Using AI Code Generation

copy

Full Screen

1const { helper } = require('@playwright/test');2const event = new Event('myEvent');3helper.dispatchEvent(event);4test('test', async ({ page }) => {5 await page.evaluate(() => {6 window.addEventListener('myEvent', () => {7 console.log('event received');8 });9 });10});11const { helper } = require('@playwright/test');12const event = new Event('myEvent');13helper.dispatchEvent(event);14test('test', async ({ page }) => {15 await page.evaluate(() => {16 window.addEventListener('myEvent', () => {17 console.log('event received');18 });19 });20 await page.waitForEvent('myEvent');21});22const { helper } = require('@playwright/test');23const event = new Event('myEvent');24helper.dispatchEvent(event);25test('test', async ({ page }) => {26 await page.evaluate(() => {27 window.addEventListener('myEvent', () => {28 console.log('event received');29 });30 });31 await page.waitForFunction(() => window.eventReceived);32});

Full Screen

Using AI Code Generation

copy

Full Screen

1const event = new Event('custom-event');2event.customProperty = 'custom value';3document.dispatchEvent(event);4const event = await page.evaluateHandle(() => {5 return new Promise((resolve) => {6 document.addEventListener('custom-event', (event) => {7 resolve(event);8 });9 });10});11expect(await event.getProperty('customProperty')).toBeTruthy();12expect(await event.getProperty('customProperty')).toEqual('custom value');13it('should be visible', async () => {14 const page = await browser.newPage();15 await page.waitForSelector('.gLFyf');16 const element = await page.$('.gLFyf');17 const visible = await element.isVisible();18 expect(visible).toBe(true);19});

Full Screen

Using AI Code Generation

copy

Full Screen

1const playwright = require("playwright");2(async () => {3 for (const browserType of BROWSER) {4 const browser = await playwright[browserType].launch();5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.evaluate(() => {8 document.dispatchEvent(9 new CustomEvent("myCustomEvent", { detail: "Hello World" })10 );11 });12 await browser.close();13 }14})();15const playwright = require("playwright");16(async () => {17 for (const browserType of BROWSER) {18 const browser = await playwright[browserType].launch();19 const context = await browser.newContext();20 const page = await context.newPage();21 await page.evaluate(() => {22 document.dispatchEvent(23 new CustomEvent("myCustomEvent", { detail: "Hello World" })24 );25 });26 await browser.close();27 }28})();29const playwright = require("playwright");30(async () => {31 for (const browserType of BROWSER) {32 const browser = await playwright[browserType].launch();33 const context = await browser.newContext();34 const page = await context.newPage();35 await page.evaluate(() => {36 document.dispatchEvent(37 new CustomEvent("myCustomEvent", { detail: "Hello World" })38 );39 });40 await browser.close();41 }42})();43const playwright = require("playwright");44(async () => {45 for (const browserType of BROWSER) {46 const browser = await playwright[browserType].launch();47 const context = await browser.newContext();48 const page = await context.newPage();49 await page.goto("https

Full Screen

Playwright tutorial

LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.

Chapters:

  1. What is Playwright : Playwright is comparatively new but has gained good popularity. Get to know some history of the Playwright with some interesting facts connected with it.
  2. How To Install Playwright : Learn in detail about what basic configuration and dependencies are required for installing Playwright and run a test. Get a step-by-step direction for installing the Playwright automation framework.
  3. Playwright Futuristic Features: Launched in 2020, Playwright gained huge popularity quickly because of some obliging features such as Playwright Test Generator and Inspector, Playwright Reporter, Playwright auto-waiting mechanism and etc. Read up on those features to master Playwright testing.
  4. What is Component Testing: Component testing in Playwright is a unique feature that allows a tester to test a single component of a web application without integrating them with other elements. Learn how to perform Component testing on the Playwright automation framework.
  5. Inputs And Buttons In Playwright: Every website has Input boxes and buttons; learn about testing inputs and buttons with different scenarios and examples.
  6. Functions and Selectors in Playwright: Learn how to launch the Chromium browser with Playwright. Also, gain a better understanding of some important functions like “BrowserContext,” which allows you to run multiple browser sessions, and “newPage” which interacts with a page.
  7. Handling Alerts and Dropdowns in Playwright : Playwright interact with different types of alerts and pop-ups, such as simple, confirmation, and prompt, and different types of dropdowns, such as single selector and multi-selector get your hands-on with handling alerts and dropdown in Playright testing.
  8. Playwright vs Puppeteer: Get to know about the difference between two testing frameworks and how they are different than one another, which browsers they support, and what features they provide.
  9. Run Playwright Tests on LambdaTest: Playwright testing with LambdaTest leverages test performance to the utmost. You can run multiple Playwright tests in Parallel with the LammbdaTest test cloud. Get a step-by-step guide to run your Playwright test on the LambdaTest platform.
  10. Playwright Python Tutorial: Playwright automation framework support all major languages such as Python, JavaScript, TypeScript, .NET and etc. However, there are various advantages to Python end-to-end testing with Playwright because of its versatile utility. Get the hang of Playwright python testing with this chapter.
  11. Playwright End To End Testing Tutorial: Get your hands on with Playwright end-to-end testing and learn to use some exciting features such as TraceViewer, Debugging, Networking, Component testing, Visual testing, and many more.
  12. Playwright Video Tutorial: Watch the video tutorials on Playwright testing from experts and get a consecutive in-depth explanation of Playwright automation testing.

Run Playwright Internal 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