Best JavaScript code snippet using testcafe
utils.js
Source:utils.js
1/*2 * Coupons at Checkout Browser Extension3 * Copyright (c) 2012, 2013 CouponFollow, LLC. All rights reserved. Patent Pending.4 * Copying this source code in any manner is strictly prohibited. 5 */67"use strict";89if (!BS) {10 var Config = require("data/config.js").BS;11 var BS = require("data/browserSpecific/backgroundApiWrapper.js").BS;12 var XMLHttpRequest = require("sdk/net/xhr").XMLHttpRequest;13}1415var utils = new (function(window, undefined) {1617 var me = this,18 domainName = null;1920 me.headers = [];2122 me.cartKeywords = ["cart", "checkout", "basket", "order", "merchant.mvc", "shopping|bag", "process", "register", "shipping", 23 "commerce", "promotion", "customer", "mybag", "booking", "confirmation"24 ];25 // domain Specific keywords26 me.domSpecKeywords = {"jockey": "bag", "bloomingdales": "bag", "macys": "bag", "raise": "receipts/new"};27 var dskDomains = Object.keys(me.domSpecKeywords);2829 this.isCart = function(customCartKeyword) {30 var cKeywords,31 isCart = false;3233 // Add site specific cart keywords (if any) at the end34 if (customCartKeyword) {35 cKeywords = me.cartKeywords.concat(customCartKeyword);36 }37 else {38 cKeywords = me.cartKeywords;39 }4041 var hostname = document.location.host;42 // exclude anything without a period (eg. localhost) and any subdomain as dev.* (eg. dev.carters.com), see issue #23743 if (hostname.indexOf(".") === -1 || hostname.indexOf("dev.") === 0) {44 return false;45 }4647 var url = "";48 var dskDomain = me.containsAKeyword(document.location.hostname, dskDomains);4950 //if basedomain is in list of domain specific keyword domains, use the specific domain keyword51 if (dskDomain) {52 var keyword = me.domSpecKeywords[dskDomain];53 url = document.location.href.toLowerCase();54 if (url.indexOf(keyword) !== -1) {55 isCart = true;56 }57 }58 else {59 // otherwise don't include base domain in searching, see #23760 url = (me.getSubdomain() + document.location.pathname + document.location.search + document.location.hash).toLowerCase();61 }6263 // no need to check if we aready know that it's a cart page64 if (!isCart) {65 // Check if the user has landed on a cart page66 for (var i = 0; i < cKeywords.length; i++) {67 var keyword = cKeywords[i];68 if (isCartWordMatched(url, keyword)) {69 isCart = true;70 break;71 }72 }73 }7475 if (isCart) {76 Logger.log("isCart: Cart page found using keyword '" + keyword + "'");77 }78 else {79 Logger.log("isCart: not a cart page.");80 }8182 return isCart;83 };8485 // checks if current page url contains any of the listed cart keywords86 function isCartWordMatched(url, cartKeyword) {87 var keywordParts = cartKeyword.split('|');8889 var matched = true,90 keywordPart;9192 for (var i = 0; i < keywordParts.length; i++) {93 keywordPart = keywordParts[i].toLowerCase();9495 if (keywordPart.length === 0) {96 continue;97 }9899 if (url.indexOf(keywordPart) === -1) {100 matched = false;101 }102 }103104 return matched;105 }106107 this.remoteGet = function(url, func) {108 var xhr = new XMLHttpRequest();109 xhr.open("GET", url, true);110111 // set global headers112 if (me.headers) {113 for (var headerKey in me.headers) {114 if (me.headers.hasOwnProperty(headerKey)) {115 xhr.setRequestHeader(headerKey, me.headers[headerKey]);116 }117 }118 }119120 xhr.onreadystatechange = function() {121 if (xhr.readyState == 4) {122 if (func) {123 func(JSON.parse(xhr.responseText), xhr.status);124 }125 }126 };127 xhr.send();128 };129130 this.remoteGetWithCache = function(cacheKey, expireTime, url, callback) {131 BS.sendMessage({ method: "cacheGet", key: cacheKey}, function(data) {132 if (data == null || !Config.useCache) {133 Logger.log('Cache miss');134 me.remoteGet(url, function(data, status) {135 if (status == 200) {136 BS.sendMessage({ method: "cacheSet", key: cacheKey, value: data, expireTime: expireTime });137 }138 callback(data, status);139 });140 }141 else {142 Logger.log('Cache hit');143 callback(data, 200);144 }145 });146 };147148 // Extracts the domain from the given URL149 this.extractDomain = function(url) {150 var re = /^(?:f|ht)tp(?:s)?:\/\/([^\/]+)/i;151152 url = url.toLowerCase();153154 var matches = url.match(re);155 if (matches != null && matches.length > 0) {156 var domainName = matches[1].toString();157158 domainName = domainName.replace(/cart(\d+)\./, "");159 domainName = domainName.replace(/www(\d*)\./, "");160 domainName = domainName.replace(/secure(\d+)\./, "");161 domainName = domainName.replace(/www\-(\w+)\./, "");162 domainName = domainName.replace(/(\w+)\-secure\./, "");163 domainName = domainName.replace(/secure-www\./, "");164 domainName = domainName.replace(/www-secure\./, "");165 domainName = domainName.replace(/secure\./, "");166 domainName = domainName.replace(/cart\./, "");167 domainName = domainName.replace(/ssl\./, "");168 domainName = domainName.replace(/secure-/, "");169 domainName = domainName.replace(/checkout\./, "");170 domainName = domainName.replace(/checkout-/, "");171 domainName = domainName.replace(/order\./, "");172 domainName = domainName.replace(/espanol\./, "");173174 return domainName;175 }176 else {177 return url;178 }179 };180181 this.extractCurrentDomain = function() {182 if (domainName === null) {183 domainName = me.extractDomain(document.location.href);184 }185186 return domainName;187 };188189 this.getSubdomain = function() {190 var baseDomain = me.extractCurrentDomain();191 return document.location.hostname.replace(baseDomain, "");192 };193194 //Function to convert text cart values to numbers for comparison195 this.convertToNumber = function(currency) {196 currency = currency.replace(/\.$|[^0-9\.,]+/g, "").replace(/(^(,|\.))|((,|\.)$)/g, "");197198 // first detect if comma is used as separator or dot is used as separator199 var indexOfComma = currency.lastIndexOf(",");200 var indexOfPoint = currency.lastIndexOf(".");201202 // if comma and point both are present then last one is used as decimal place while the one that occurred203 // first is separator204 if (indexOfComma != -1 && indexOfPoint != -1) {205 if (indexOfComma > indexOfPoint) {206 currency = currency.replace(/,/g, "-");207 currency = currency.replace(/\./g, ",");208 currency = currency.replace(/-/g, ".");209 }210 }211 else if (indexOfPoint != -1) {212 if (currency.length - indexOfPoint - 1 > 2) {213 currency = currency.replace(/\./g, ",");214 }215 }216 else if (indexOfComma != -1) {217 if (currency.length - indexOfComma - 1 <= 2) {218 currency = currency.replace(/,/g, ".");219 }220 }221222 // remove commas223 currency = currency.replace(/,+/g, "");224225 var number = Number.NaN;226 if (currency !== "") {227 number = Number(currency);228 }229230 return number;231 };232233 this.fireHtmlEvent = function(element, eventName, canBubble) {234 if (typeof canBubble == "undefined") {235 canBubble = false;236 }237238 var evt = document.createEvent("HTMLEvents");239 evt.initEvent(eventName, canBubble, true);240 element.dispatchEvent(evt);241 };242243 this.fireGeneralEvent = function(element, eventName, canBubble) {244 if (typeof canBubble == "undefined") {245 canBubble = true;246 }247248 var evt = document.createEvent("Events");249 evt.initEvent(eventName, canBubble, true);250 element.dispatchEvent(evt);251 };252253 this.fireKeyboardEvent = function(element, eventName, key) {254 /*var event = document.createEvent("KeyboardEvent");255 if (event.initKeyEvent) {256 event.initKeyEvent(eventName, true, true, window, 0, 0, 0, 0, 0, key);257 }258 else {259 event.initKeyboardEvent(eventName, true, true, window, 0, 0, 0, 0, 0, key);260 }261 element.dispatchEvent(event);*/262263 var event = new KeyboardEvent(eventName, {key: key, bubbles: true});264 element.dispatchEvent(event);265 };266267 this.getElemId = function(elem) {268 var elemId = elem.id;269270 if (!elemId) {271 elemId = "z" + this.getRandomNum();272 elem.id = elemId;273 }274275 return elem.id;276 };277278 // returns a random number within the provided limit279 this.getRandomNum = function(lowerLimit, upperLimit) {280 if (typeof lowerLimit == "undefined") {281 lowerLimit = 0;282 }283 if (typeof upperLimit == "undefined") {284 upperLimit = 10000000000;285 }286287 return Math.round(Math.random() * upperLimit) + lowerLimit;288 };289290 function onDOMModification($elem, matchFunc, callback) {291 var fired = false;292 var observer = new MutationObserver(function (mutations) {293 // just to make sure the event fires only once294 if (fired) {295 return;296 }297298 $elem.each(function() {299 // just to make sure the event fires only once300 if (fired) {301 return;302 }303304 var $this = $(this);305 if (matchFunc(this)) {306 fired = true;307 observer.disconnect();308 callback(mutations);309 }310 });311 });312313 observer.observe(document.body, { attributes: true, subtree: true, childList: true, attributeFilter: ["style", "class"], characterData: true });314315 return observer;316 }317318 // fires callback only once319 this.onShow = function($elem, callback, checkImmediately, checkText) {320 // if element is already visible, fire callback immediately321 if (checkImmediately && $elem.is(":visible") && $elem.css("visibility") != "hidden" && $elem[0].offsetHeight > 0 && $elem[0].offsetWidth > 0 && (!checkText || $elem.text().length > 0)) {322 callback();323 return;324 }325326 return onDOMModification($elem, function (element) {327 var $element = $(element);328 return $element.is(":visible") && $element.css("visibility") != "hidden" && element.offsetHeight > 0 && element.offsetWidth > 0 && (!checkText || $element.text().length > 0);329 }, callback);330 };331332 // fires callback only once333 this.onHide = function($elem, callback) {334 return onDOMModification($elem, function (element) {335 var $element = $(element);336 return !$element.is(":visible") || $element.css("visibility") == "hidden" || element.offsetHeight == 0 || element.offsetWidth == 0;337 }, callback);338 };339340 // simulates click on an element341 this.simulateClick = function(element)342 {343 element.focus();344345 // click function is not preset on all element i.e. anchor tag346 if (element.click)347 {348 element.click();349 }350 else351 {352 var evt = new MouseEvent("click", {353 bubbles: true,354 cancelable: true,355 view: window356 });357358 var canceled = !element.dispatchEvent(evt);359 if(canceled) {360 // A handler called preventDefault361 console.warn("simulateClick: a handler called preventDefault");362 }363 }364 };365366 // simulates click on an element367 this.simulateClickInSiteContext = function(element)368 {369 var elemId = utils.getElemId(element);370371 var script = "var element = document.getElementById('" + elemId + "');" +372 "var evt = new MouseEvent(\"click\", {" +373 "bubbles: true," +374 "cancelable: true," +375 "view: window" +376 "});" +377 "var canceled = !element.dispatchEvent(evt);" +378 "if(canceled) {" +379 "console.warn(\"simulateClick: a handler called preventDefault\");" +380 "}";381382 var $script = $("<script>").text(script);383 $("body").append($script);384 };385386 // logs catc2 messages to console387 this.log = function(message) {388 Logger.log('CouponFollow > ' + message);389 };390391 // clones a javascript object392 this.clone = function(obj) {393 return JSON.parse(JSON.stringify(obj));394 };395396 // extracts root domain from complete domain, i.e. passed www.example.com, it'll return example.com397 this.getRootDomain = function(domain) {398 var domainParts = domain.split(".");399 return domainParts[domainParts.length - 2] + "." + domainParts[domainParts.length - 1];400 };401402 this.contains = function(a, obj) {403 var i = a.length;404 while (i--) {405 if (a[i] === obj) {406 return true;407 }408 }409 return false;410 };411412 this.simulateTextInput = function($elem, text) {413 $elem.val(text);414415 var elem = $elem[0];416417 // some sites actually listen for change,keydown,keyup,keypress events to change the coupon code internally (for example418 // rei.com, colehaan.com), so we need to fire these events after changing text419 utils.fireKeyboardEvent(elem, "keydown", 97);420 utils.fireKeyboardEvent(elem, "keypress", 97);421 utils.fireKeyboardEvent(elem, "keyup", 97);422 utils.fireGeneralEvent(elem, "input", true);423 utils.fireHtmlEvent(elem, "change", true);424 };425426 this.onClassChange = function($elem, callback) {427 var observer = new MutationObserver(callback);428429 observer.observe($elem[0], { attributes: true, attributeFilter: ["class"] });430431 return observer;432 };433434 this.openPopup = function(url, options) {435 var optionsStr = "'toolbar=0, location=0, directories=0, status=0, menubar=0, scrollbars=0, resizable=0";436437 if (options) {438 if (options.centerAlign) {439 options.left = (screen.width / 2) - (options.width / 2);440 options.top = (screen.height / 2) - (options.height / 2) - 40;441 }442443 if (typeof options.width !== "undefined") {444 optionsStr += ", width=" + options.width;445 }446 if (typeof options.height !== "undefined") {447 optionsStr += ", height=" + options.height;448 }449 if (typeof options.top !== "undefined") {450 optionsStr += ", top=" + options.top;451 }452 if (typeof options.left !== "undefined") {453 optionsStr += ", left=" + options.left;454 }455 }456457 window.open(url, options.windowName, optionsStr);458 };459460 this.parseQueryParams = function(querySeparator) {461 if (!querySeparator) {462 querySeparator = "?";463 }464465 var queryObj = {};466 var query = location.href.split(querySeparator)[1];467 if (query) {468 var params = query.split("&");469 for (var i=0, param; param=params[i]; i++) {470 var p = param.split("=");471 queryObj[p[0]] = decodeURIComponent(p[1]);472 }473 }474475 return queryObj;476 };477478 this.containsAKeyword = function (string, keywords) {479 string = string.toLowerCase();480 for (var i = 0; i < keywords.length; i++) {481 if (string.indexOf(keywords[i].toLowerCase()) !== -1) {482 return keywords[i];483 }484 }485486 return false;487 };488489 this.waitUntilVisible = function(selector, callback) {490 var alreadyFired = false;491492 var stopListener = function() {493 document.unbindArrive(selector, arriveListener);494495 for (var i = 0; i < observers.length; i++) {496 observer = observers[i];497 observer.disconnect();498 }499500 observers = [];501 };502503 var arriveListener = function() {504 Logger.log("Arrive fired for selector " + selector + " ...");505506 var $elem = $(this);507508 // if element is not visible, wait until it becomes visible509 var observer = utils.onShow($elem, function () {510 // make sure the callback is called only once511 if (!alreadyFired) {512 Logger.log("Element (selector: " + selector + ") became visible...");513514 stopListener();515 callback($elem[0]);516517 alreadyFired = true;518 }519 }, true);520521 if (observer) {522 observers.push(observer);523 }524 };525526 var observers = [],527 observer;528529 if (selector && selector.length > 0) {530 document.arrive(selector, { existing: true, fireOnAttributesModification: true }, arriveListener);531 }532 else {533 // schedule in next event loop to make it behave asynchronously534 setTimeout(callback, 1);535 }536537 return { stopListener: stopListener };538 };539540 this.preLoad = function(url) {541 var image = new Image();542 image.src = url;543 };544545 this.escapeHtml = function(str) {546 var replacements = { "&": "&", '"': """, "<": "<", ">": ">" };547 return str.replace(/[&"<>]/g, function (m){ return replacements[m]});548 };549550 window.Logger = {};551 552 if (Config && Config.dumpLogs == false) {553 Logger.log = function() {};554 }555 else {556 Logger.log = console.log.bind(window.console);557 }558559})(this, undefined);560561562// need to export in case of firefox so it can be accessed in other files563if (typeof exports !== "undefined") {564 exports.utils = utils;
...
functions.spec.js
Source:functions.spec.js
...173 />174 );175 }176 }177 simulateTextInput(TrailingEdgeInput);178 simulateTextInput(LeadingEdgeInput);179 });180 it('lock', (done) => {181 const simulateTextInput = (Input) => {182 const rendered = ReactTestUtils.renderIntoDocument(<Input />);183 const input = ReactTestUtils.findRenderedDOMComponentWithTag(rendered, 'input');184 ReactTestUtils.Simulate.change(input, { target: { value: 'first' } });185 ReactTestUtils.Simulate.change(input, { target: { value: 'second' } });186 setTimeout(() => {187 ReactTestUtils.Simulate.change(input, { target: { value: 'third' } });188 }, 400);189 };190 // eslint-disable-next-line191 class LockedInput extends React.Component {192 constructor(...params) {193 super(...params);194 this.onChange = this.onChange.bind(this);195 this.counter = 0;196 }197 @lock198 onChange(e) {199 expect(e.target.value).toEqual('first');200 this.counter += 1;201 if (this.counter > 0) {202 expect(this.counter).toEqual(1);203 done();204 }205 }206 render() {207 return (208 <input209 onChange={this.onChange}210 />211 );212 }213 }214 simulateTextInput(LockedInput);215 });216 it('throttle', (done) => {217 const simulateTextInput = (Input) => {218 const rendered = ReactTestUtils.renderIntoDocument(<Input />);219 const input = ReactTestUtils.findRenderedDOMComponentWithTag(rendered, 'input');220 ReactTestUtils.Simulate.change(input, { target: { value: 'first' } });221 ReactTestUtils.Simulate.change(input, { target: { value: 'second' } });222 setTimeout(() => {223 ReactTestUtils.Simulate.change(input, { target: { value: 'third' } });224 }, 400);225 };226 // eslint-disable-next-line227 class LeadingEdgeInput extends React.Component {228 constructor(...params) {229 super(...params);230 this.onChange = this.onChange.bind(this);231 }232 @throttle(undefined, { trailing: false })233 onChange(e) {234 if (this.first) {235 expect(e.target.value).toEqual('first');236 this.first = false;237 } else {238 expect(e.target.value).toEqual('third');239 }240 }241 first = true242 render() {243 return (244 <input245 onChange={this.onChange}246 />247 );248 }249 }250 // eslint-disable-next-line251 class TrailingEdgeInput extends React.Component {252 constructor(...params) {253 super(...params);254 this.onChange = this.onChange.bind(this);255 }256 @throttle(undefined, { leading: false })257 onChange(e) {258 if (this.first) {259 expect(e.target.value).toEqual('second');260 this.first = false;261 } else {262 expect(e.target.value).toEqual('third');263 done();264 }265 }266 first = true267 render() {268 return (269 <input270 onChange={this.onChange}271 />272 );273 }274 }275 // eslint-disable-next-line276 class LeadingAndTrailingEdgeInput extends React.Component {277 constructor(...params) {278 super(...params);279 this.onChange = this.onChange.bind(this);280 }281 @throttle(300)282 onChange(e) {283 if (this.times === 0) {284 expect(e.target.value).toEqual('first');285 this.times++;286 } else if (this.times === 1) {287 expect(e.target.value).toEqual('second');288 this.times++;289 } else {290 expect(e.target.value).toEqual('third');291 }292 }293 times = 0294 render() {295 return (296 <input297 onChange={this.onChange}298 />299 );300 }301 }302 simulateTextInput(LeadingEdgeInput);303 simulateTextInput(LeadingAndTrailingEdgeInput);304 setTimeout(() => {305 simulateTextInput(TrailingEdgeInput);306 }, 500);307 });308 it('trace', (done) => {309 let spy = null;310 // eslint-disable-next-line311 class Input extends React.Component {312 @trace313 onChange(e) {314 expect(e.target.value).toEqual('foo');315 expect(this.foo).toEqual('bar');316 expect(spy).toHaveBeenCalled();317 done();318 }319 foo = 'bar'...
content.js
Source:content.js
...30 $(function () {31 BS.onMessage(32 function (request, sender, sendResponse) {33 if (request.method == "pasteCoupon") {34 utils.simulateTextInput($(couponInputSelector), request.couponCode);35 $('#cf-panel').hide();36 }37 }38 );3940 // Mark domain as visited41 BS.sendMessage({call: 'markVisited', arg: domain});4243 // Get CouponFollow helpers and start the scraping process44 BS.sendMessage({call: 'cf'}, function (response) {45 cf = response;46 helper = cf.helpers[domain] || {};4748 // Test current page for cart page
...
KeyMapManager.js
Source:KeyMapManager.js
...210 eventType: event.type,211 keyboardEventTarget: target,212 });213 if (event.defaultPrevented && event.type === 'keydown') {214 this.simulateTextInput(event);215 }216 }217 if (dispatchedExactMatch) {218 this.bindingsToDisable.push(dispatchedExactMatch);219 }220 if (hasPartialMatches && shouldUsePartialMatches) {221 let enabledTimeout = (222 this.pendingStateTimeoutHandle ||223 dispatchedExactMatch ||224 characterForKeyboardEvent(this.queuedKeyboardEvents[0])225 );226 if (replay) {227 enableTimeout = false;228 }229 this.enterPendingState(partialMatches, enableTimeout);230 } else if (dispatchedExactMatch && !hasPartialMatches && this.pendingPartialMatches) {231 this.terminatePendingState();232 } else {233 this.clearQueuedKeystrokes();234 }235 }236 keystrokeForKeyboardEvent(event) {237 return keystrokeForKeyboardEvent(event, this.customKeystrokeResolvers)238 }239 addKeystrokeResolver(resolver) {240 this.customKeystrokeResolvers.push(resolver);241 new Disposable(() => {242 let index = this.customKeystrokeResolvers.indexOf(resolver);243 if (index >= 0) {244 this.customKeystrokeResolvers.splice(index, 1);245 }246 });247 }248 getPartialTimeout() {249 return this.partialMatchTimeout;250 }251 simulateTextInput(keydownEvent) {252 // var character, textInputEvent;253 // if (character = characterForKeyboardEvent(keydownEvent)) {254 // textInputEvent = document.createEvent("TextEvent");255 // textInputEvent.initTextEvent("textInput", true, true, window, character);256 // return keydownEvent.path[0].dispatchEvent(textInputEvent);257 // }258 }259 findMatchCandidates(keystrokeArray, disabledBindings) {260 let partialMatchCandidates = [];261 let exactMatchCandidates = [];262 let pendingKeyupMatchCandidates = [];263 let disabledBindingSet = new Set(disabledBindings);264 for (var i = 0, l = this.keyBindings.length; i < l; i ++) {265 const binding = this.keyBindings[i];...
tokenizer-test.js
Source:tokenizer-test.js
...8var Tokenizer = require('../src/tokenizer');9var Token = require('../src/tokenizer/token');10var Keyevent = require('../src/keyevent');11var TestUtils = React.addons.TestUtils;12function simulateTextInput(component, value) {13 var node = component.refs.entry.getDOMNode();14 node.value = value;15 TestUtils.Simulate.change(node);16 return TestUtils.scryRenderedComponentsWithType(component, TypeaheadOption);17}18function simulateTokenInput(component, value) {19 var typeahead = component.refs.typeahead;20 return simulateTextInput(typeahead, value);21}22function getTokens(component) {23 return TestUtils.scryRenderedComponentsWithType(component, Token);24}25var BEATLES = ['John', 'Paul', 'George', 'Ringo'];26describe('TypeaheadTokenizer Component', function() {27 describe('basic tokenizer', function() {28 beforeEach(function() {29 this.component = TestUtils.renderIntoDocument(30 <Tokenizer31 options={BEATLES}32 customClasses={{33 token: 'custom-token'34 }}...
type-text.js
Source:type-text.js
...128 preventEvent();129 }130 // NOTE: IE11 does not raise input event when type to contenteditable131 const beforeContentChanged = () => {132 needProcessInput = simulateTextInput(element, textInputData);133 needRaiseInputEvent = needProcessInput && !browserUtils.isIE11;134 listeners.addInternalEventListener(window, ['input'], onInput);135 listeners.addInternalEventListener(window, ['textinput'], onTextInput);136 };137 const afterContentChanged = () => {138 nextTick()139 .then(() => {140 if (needRaiseInputEvent)141 eventSimulator.input(element);142 listeners.removeInternalEventListener(window, ['input'], onInput);143 listeners.removeInternalEventListener(window, ['textinput'], onTextInput);144 });145 };146 if (!startNode || !endNode || !domUtils.isContentEditableElement(startNode) ||147 !domUtils.isContentEditableElement(endNode))148 return;149 if (!domUtils.isTheSameNode(startNode, endNode)) {150 textSelection.deleteSelectionContents(element);151 // NOTE: after deleting the selection contents we should refresh the stored startNode because152 // contentEditable element's content could change and we can no longer find parent elements153 // of the nodes. In MSEdge, 'parentElement' for the deleted element isn't undefined154 currentSelection = _updateSelectionAfterDeletionContent(element, currentSelection);155 startNode = currentSelection.startPos.node;156 }157 if (!startNode || !domUtils.isContentEditableElement(startNode) || !domUtils.isRenderedNode(startNode))158 return;159 beforeContentChanged();160 if (needProcessInput) {161 // NOTE: we can type only to the text nodes; for nodes with the 'element-node' type, we use a special behavior162 if (domUtils.isElementNode(startNode))163 _typeTextInElementNode(startNode, text);164 else165 _typeTextInChildTextNode(element, _excludeInvisibleSymbolsFromSelection(currentSelection), text);166 }167 afterContentChanged();168}169function _typeTextToTextEditable (element, text) {170 const elementValue = domUtils.getElementValue(element);171 const textLength = text.length;172 let startSelection = textSelection.getSelectionStart(element);173 let endSelection = textSelection.getSelectionEnd(element);174 const isInputTypeNumber = domUtils.isInputElement(element) && element.type === 'number';175 const needProcessInput = simulateTextInput(element, text);176 if (!needProcessInput)177 return;178 // NOTE: the 'maxlength' attribute doesn't work in all browsers. IE still doesn't support input with the 'number' type179 let elementMaxLength = !browserUtils.isIE && isInputTypeNumber ? null : parseInt(element.maxLength, 10);180 if (elementMaxLength < 0)181 elementMaxLength = browserUtils.isIE && browserUtils.version < 17 ? 0 : null;182 if (elementMaxLength === null || isNaN(elementMaxLength) || elementMaxLength > elementValue.length) {183 // NOTE: B254013184 if (isInputTypeNumber && browserUtils.isIOS && elementValue[elementValue.length - 1] === '.') {185 startSelection += 1;186 endSelection += 1;187 }188 domUtils.setElementValue(element, elementValue.substring(0, startSelection) + text +189 elementValue.substring(endSelection, elementValue.length));...
typeahead-test.js
Source:typeahead-test.js
...5var TypeaheadOption = require('../src/typeahead/option');6var TypeaheadSelector = require('../src/typeahead/selector');7var Keyevent = require('../src/keyevent');8var TestUtils = React.addons.TestUtils;9function simulateTextInput(component, value) {10 var node = component.refs.entry.getDOMNode();11 node.value = value;12 TestUtils.Simulate.change(node);13 return TestUtils.scryRenderedComponentsWithType(component, TypeaheadOption);14}15var BEATLES = ['John', 'Paul', 'George', 'Ringo'];16describe('Typeahead Component', function() {17 describe('sanity', function() {18 beforeEach(function() {19 this.component = TestUtils.renderIntoDocument(Typeahead({20 options: BEATLES,21 }));22 });23 it('should fuzzy search and render matching results', function() {24 // input value: num of expected results25 var testplan = {26 'o': 3,27 'pa': 1,28 'Grg': 1,29 'Ringo': 1,30 'xxx': 031 };32 _.each(testplan, function(expected, value) {33 var results = simulateTextInput(this.component, value);34 assert.equal(results.length, expected, 'Text input: ' + value);35 }, this);36 });37 describe('keyboard controls', function() {38 it('down arrow + return selects an option', function() {39 var results = simulateTextInput(this.component, 'o');40 var secondItem = results[1].getDOMNode().innerText;41 var node = this.component.refs.entry.getDOMNode();42 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });43 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });44 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN });45 assert.equal(node.value, secondItem); // Poor Ringo46 });47 it('up arrow + return navigates and selects an option', function() {48 var results = simulateTextInput(this.component, 'o');49 var firstItem = results[0].getDOMNode().innerText;50 var node = this.component.refs.entry.getDOMNode();51 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });52 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });53 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_UP });54 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_RETURN });55 assert.equal(node.value, firstItem);56 });57 it('escape clears selection', function() {58 var results = simulateTextInput(this.component, 'o');59 var firstItem = results[0].getDOMNode();60 var node = this.component.refs.entry.getDOMNode();61 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });62 assert.ok(firstItem.classList.contains('hover'));63 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_ESCAPE });64 assert.notOk(firstItem.classList.contains('hover'));65 });66 it('tab to choose first item', function() {67 var results = simulateTextInput(this.component, 'o');68 var itemText = results[0].getDOMNode().innerText;69 var node = this.component.refs.entry.getDOMNode();70 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_TAB });71 assert.equal(node.value, itemText);72 });73 it('tab to selected current item', function() {74 var results = simulateTextInput(this.component, 'o');75 var itemText = results[1].getDOMNode().innerText;76 var node = this.component.refs.entry.getDOMNode();77 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });78 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_DOWN });79 TestUtils.Simulate.keyDown(node, { keyCode: Keyevent.DOM_VK_TAB });80 assert.equal(node.value, itemText);81 });82 });83 });84 describe('props', function() {85 context('maxVisible', function() {86 it('limits the result set based on the maxVisible option', function() {87 var component = TestUtils.renderIntoDocument(Typeahead({88 options: BEATLES,89 maxVisible: 190 }));91 var results = simulateTextInput(component, 'o');92 assert.equal(results.length, 1);93 });94 });95 context('customClasses', function() {96 before(function() {97 this.component = TestUtils.renderIntoDocument(Typeahead({98 options: BEATLES,99 customClasses: {100 input: 'topcoat-text-input',101 results: 'topcoat-list__container',102 listItem: 'topcoat-list__item',103 listAnchor: 'topcoat-list__link'104 }105 }));106 simulateTextInput(this.component, 'o');107 });108 it('adds a custom class to the typeahead input', function() {109 var input = this.component.refs.entry.getDOMNode();110 assert.isTrue(input.classList.contains('topcoat-text-input'));111 });112 it('adds a custom class to the results component', function() {113 var results = TestUtils.findRenderedComponentWithType(this.component, TypeaheadSelector).getDOMNode();114 assert.isTrue(results.classList.contains('topcoat-list__container'));115 });116 it('adds a custom class to the list items', function() {117 var typeaheadOptions = TestUtils.scryRenderedComponentsWithType(this.component, TypeaheadOption);118 var listItem = typeaheadOptions[1].getDOMNode();119 assert.isTrue(listItem.classList.contains('topcoat-list__item'));120 });...
translate_deepl.js
Source:translate_deepl.js
1function countMatches(str, regex){2 return ((str || '').match(regex) || []).length3}4function simulateTextInput(text) {5 var el = document.getElementsByClassName("lmt__textarea lmt__source_textarea lmt__textarea_base_style")[0];6 el.value = text;7 var evt = document.createEvent("Events");8 evt.initEvent("change", true, true);9 el.dispatchEvent(evt);10}11if (window.self !== window.top){12 console.log("DeepL translate script");13 var toLang = "";14 var toLang_prev = "";15 var converter;16 // initial language setting17 chrome.storage.local.get(['lang_select'], function(result) {18 let lang_temp = result.lang_select;19 if (lang_temp == "yue" || lang_temp == "zh-Hans" || lang_temp == "zh-Hant")20 {21 toLang = 'zh';22 }23 else if (lang_temp == "en")24 {25 toLang = 'en';26 }27 // actual language change28 if (toLang != toLang_prev)29 {30 // inform background to redirect31 chrome.runtime.sendMessage({ method: "BG_change_deepl_lang", data: toLang});32 toLang_prev = toLang;33 if (lang_temp = "yue")34 {35 converter = OpenCC.Converter({ from: 'cn', to: 'hk' });36 } 37 else if (lang_temp = "zh-Hant")38 {39 converter = OpenCC.Converter({ from: 'cn', to: 'tw' });40 }41 console.log("initial deepL language is set to "+toLang);42 }43 });44 //listen to language change45 chrome.storage.onChanged.addListener(function(changes, namespace) {46 for (key in changes)47 {48 if (key == "lang_select" )49 {50 if (changes[key].newValue == "yue" || changes[key].newValue == "zh-Hans" || changes[key].newValue == "zh-Hant")51 {52 toLang = 'zh';53 }54 else if (changes[key].newValue == "en")55 {56 toLang = 'en';57 }58 // actual language change59 if (toLang != toLang_prev)60 {61 // inform background to redirect62 chrome.runtime.sendMessage({ method: "BG_change_deepl_lang", data: toLang});63 toLang_prev = toLang;64 if (changes[key].newValue = "yue")65 {66 converter = OpenCC.Converter({ from: 'cn', to: 'hk' });67 } 68 else if (changes[key].newValue = "zh-Hant")69 {70 converter = OpenCC.Converter({ from: 'cn', to: 'tw' });71 }72 }73 }74 }75 });76 var outputTextArea = document.getElementById('target-dummydiv');77 const queue = async.queue((task, completed) => {78 79 var beforeText = outputTextArea.innerHTML;80 simulateTextInput(task.message.text.replace(/\n/g,' '));81 const remaining = queue.length();82 var time_elapsed = 0;83 var id = setInterval(function()84 {85 let temp = outputTextArea.cloneNode(true);86 time_elapsed = time_elapsed + 100;87 const afterText = temp.innerHTML;88 if(afterText != beforeText)89 {90 clearInterval(id);91 if ( 92 ( (task.toLang == "yue" || task.toLang == "zh-Hant" || task.toLang == "zh-Hans") && countMatches(afterText, /[\p{sc=Han}]/gu) > 0 )93 || (task.toLang == "en" && countMatches(afterText, /\w/g) > 0 ) 94 || (task.toLang != "yue" && task.toLang != "zh-Hant" && task.toLang != "zh-Hans" && task.toLang != "en")...
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 let headerText = await articleHeader.innerText;7});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'Peter')4 .click('#submit-button');5});6const simulateTextInput = async (t, element, text) => {7 for (const char of text) {8 .pressKey(char)9 .wait(0.5);10 }11};12test('My second test', async t => {13 .click('#tried-test-cafe')14 .click('#tried-test-cafe-2')15 .click('#tried-test-cafe-3');16 await simulateTextInput(t, '#comments', 'Peter');17 .click('#submit-button');18});192 passed (0s)
Using AI Code Generation
1import { Selector } from 'testcafe';2import { ClientFunction } from 'testcafe';3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#windows')6 .click('#submit-button');7});8export default async function simulateTextInput(element, text) {9 await ClientFunction(() => {10 const event = new Event('input', { bubbles: true });11 event.simulated = true;12 element.value = text;13 element.dispatchEvent(event);14 }, { dependencies: { text } })(element);15}16export default async function simulateTextInput(element, text) {17 await ClientFunction(() => {18 const event = new Event('input', { bubbles: true });19 event.simulated = true;20 element.value = text;21 element.dispatchEvent(event);22 }, { dependencies: { text } })(element);23}24export default async function simulateTextInput(element, text) {25 await ClientFunction(() => {26 const event = new Event('input', { bubbles: true });27 event.simulated = true;28 element.value = text;29 element.dispatchEvent(event);30 }, { dependencies: { text } })(element);31}32export default async function simulateTextInput(element, text) {33 await ClientFunction(() => {34 const event = new Event('input', { bubbles: true });35 event.simulated = true;36 element.value = text;37 element.dispatchEvent(event);38 }, { dependencies: { text } })(element);39}40export default async function simulateTextInput(element, text) {41 await ClientFunction(() => {42 const event = new Event('input', { bubbles: true });43 event.simulated = true;44 element.value = text;45 element.dispatchEvent(event);46 }, { dependencies: { text } })(element);47}48export default async function simulateTextInput(element, text) {49 await ClientFunction(() => {50 const event = new Event('input', { bubbles: true });
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 const developerName = Selector('#developer-name');4 .typeText(developerName, 'Peter Parker')5 .click('#submit-button')6 .expect(Selector('#article-header').innerText).eql('Thank you, Peter Parker!');7});8const simulateTextInput = (element, text) => {9 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;10 nativeInputValueSetter.call(element, text);11 const inputEvent = new Event('input', { bubbles: true });12 element.dispatchEvent(inputEvent);13};14const simulateTextInput = (element, text) => {15 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;16 nativeInputValueSetter.call(element, text);17 const inputEvent = new Event('input', { bubbles: true });18 element.dispatchEvent(inputEvent);19};20const simulateTextInput = (element, text) => {21 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;22 nativeInputValueSetter.call(element, text);23 const inputEvent = new Event('input', { bubbles: true });24 element.dispatchEvent(inputEvent);25};26const simulateTextInput = (element, text) => {27 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;28 nativeInputValueSetter.call(element, text);29 const inputEvent = new Event('input', { bubbles: true });30 element.dispatchEvent(inputEvent);31};32const simulateTextInput = (element, text) => {33 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;34 nativeInputValueSetter.call(element, text);35 const inputEvent = new Event('input', { bubbles: true });36 element.dispatchEvent(inputEvent);37};38const simulateTextInput = (element, text) => {39 const nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLInputElement.prototype, "value").set;40 nativeInputValueSetter.call(element, text);
Using AI Code Generation
1import { Selector } from 'testcafe';2import { ClientFunction } from 'testcafe';3test('My first test', async t => {4 .typeText('#developer-name', 'John Smith')5 .click('#submit-button');6});7const simulateTextInput = ClientFunction((selector, text) => {8 const el = document.querySelector(selector);9 el.value = text;10 el.dispatchEvent(new Event('input', { bubbles: true }));11});12test('My first test', async t => {13 .click(Selector('#populate'))14 .click(Selector('#submit-button'));15});16const simulateTextInput = ClientFunction((selector, text) => {17 const el = document.querySelector(selector);18 el.value = text;19 el.dispatchEvent(new Event('input', { bubbles: true }));20});21test('My first test', async t => {22 .click(Selector('#populate'))23 .click(Selector('#submit-button'));24});25const simulateTextInput = ClientFunction((selector, text) => {26 const el = document.querySelector(selector);27 el.value = text;28 el.dispatchEvent(new Event('input', { bubbles: true }));29});30test('My first test', async t => {31 .click(Selector('#populate'))32 .click(Selector('#submit-button'));33});34const simulateTextInput = ClientFunction((selector, text) => {35 const el = document.querySelector(selector);36 el.value = text;37 el.dispatchEvent(new Event('input', { bubbles: true }));38});39test('My first test', async t => {40 .click(Selector('#populate'))41 .click(Selector('#submit-button'));42});43const simulateTextInput = ClientFunction((selector, text) => {44 const el = document.querySelector(selector);45 el.value = text;46 el.dispatchEvent(new Event('input', { bubbles: true }));47});48test('My first test', async t => {49 .click(Selector('#populate'))50 .click(Selector('#submit
Using AI Code Generation
1import { Selector } from 'testcafe';2import { ClientFunction } from 'testcafe';3import { t } from 'testcafe';4test('My first test', async t => {5 const simulateTextInput = ClientFunction((element, text) => {6 const event = new Event('input', { bubbles: true });7 Object.defineProperty(event, 'target', { writable: false, value: element });8 Object.defineProperty(event, 'currentTarget', { writable: false, value: element });9 Object.defineProperty(event, 'srcElement', { writable: false, value: element });10 Object.defineProperty(event, 'target', { writable: false, value: element });11 Object.defineProperty(event, 'which', { writable: false, value: text.charCodeAt(0) });12 Object.defineProperty(event, 'charCode', { writable: false, value: text.charCodeAt(0) });13 element.value = text;14 element.dispatchEvent(event);15 });16 const input = Selector('#developer-name');17 .typeText(input, 'Peter')18 .click('#submit-button')19 .expect(Selector('#article-header').innerText).eql('Thank you, Peter!');20});21test('My second test', async t => {22 const simulateTextInput = ClientFunction((element, text) => {23 const event = new Event('input', { bubbles: true });24 Object.defineProperty(event, 'target', { writable: false, value: element });25 Object.defineProperty(event, 'currentTarget', { writable: false, value: element });26 Object.defineProperty(event, 'srcElement', { writable: false, value: element });27 Object.defineProperty(event, 'target', { writable: false, value: element });28 Object.defineProperty(event, 'which', { writable: false, value: text.charCodeAt(0) });29 Object.defineProperty(event, 'charCode', { writable: false, value: text.charCodeAt(0) });30 element.value = text;31 element.dispatchEvent(event);32 });33 const input = Selector('#developer-name');34 .typeText(input, 'Peter')35 .click('#submit-button')
Using AI Code Generation
1import { Selector } from 'testcafe';2import { ClientFunction } from 'testcafe';3const simulateTextInput = ClientFunction((selector, text) => {4 const input = document.querySelector(selector);5 input.value = text;6 input.dispatchEvent(new Event('input'));7});8test('My first test', async t => {9 await simulateTextInput('#input', 'Hello, World!');10 .expect(Selector('#input').value).eql('Hello, World!')11 .expect(Selector('#output').innerText).eql('Hello, World!');12});13 document.querySelector('#input').addEventListener('input', function() {14 document.querySelector('#output').innerText = this.value;15 });
Using AI Code Generation
1import { Selector, t } from 'testcafe';2test('Testcafe Demo', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#submit-button');5 const articleHeader = await Selector('.result-content').find('h1');6 const headerText = await articleHeader.innerText;7 await t.expect(headerText).eql('Thank you, John Smith!');8});9export async function simulateTextInput(selector, text) {10 const input = await Selector(selector);11 .expect(input.exists).ok()12 .click(input)13 .pressKey('ctrl+a delete')14 .typeText(input, text);15}16test('Testcafe Demo', async t => {17 await simulateTextInput('#developer-name', 'John Smith');18 await t.click('#submit-button');19 const articleHeader = await Selector('.result-content').find('h1');20 const headerText = await articleHeader.innerText;21 await t.expect(headerText).eql('Thank you, John Smith!');22});23export async function simulateTextInput(selector, text) {24 const input = await Selector(selector);25 .expect(input.exists).ok()26 .click(input)27 .pressKey('ctrl+a delete')28 .typeText(input, text);29}30test('Testcafe Demo', async t => {31 await simulateTextInput('#developer-name', 'John Smith');32 await t.click('#submit-button');33 const articleHeader = await Selector('.result-content').find('h1');34 const headerText = await articleHeader.innerText;35 await t.expect(headerText).eql('Thank you, John Smith!');36});
Using AI Code Generation
1import { Selector, t } from 'testcafe';2const simulateTextInput = require('testcafe/lib/client-functions/simulate-text-input');3const input = Selector('#input');4const output = Selector('#output');5test('Test', async t => {6 .expect(input.value).eql('')7 .expect(output.textContent).eql('0');8 await simulateTextInput(input, '1');9 .expect(input.value).eql('1')10 .expect(output.textContent).eql('1');11});12import { Selector, t } from 'testcafe';13const simulateTextInput = require('testcafe/lib/client-functions/simulate-text-input');14const input = Selector('#input');15const output = Selector('#output');16test('Test', async t => {17 .expect(input.value).eql('')18 .expect(output.textContent).eql('0');19 await simulateTextInput(input, '1');20 .expect(input.value).eql('1')21 .expect(output.textContent).eql('1');22});23import { Selector, t } from 'testcafe';24const simulateTextInput = require('testcafe/lib/client-functions/simulate-text-input');25const input = Selector('#input');26const output = Selector('#output');27test('Test', async t => {28 .expect(input.value).eql('')29 .expect(output.textContent).eql('0');30 await simulateTextInput(input, '1');31 .expect(input.value).eql('1')32 .expect(output.textContent).eql('1');33});34import { Selector, t } from 'testcafe';35const simulateTextInput = require('testcafe/lib/client-functions/simulate-text-input');36const input = Selector('#input');
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!