Best JavaScript code snippet using testcafe
nunit.js
Source:nunit.js
1/**2 * Copyright (c) 2013 Neal Xiong3 */4(function(global){5 6 var NUnit = {};7 8 NUnit.Assert = function(test){9 this.test = test ;10 this.assertCount = 0;11 };12 var assert = {13 "strictEquals": function(obj1, obj2, desc){14 if(obj1 === obj2) return true ;15 throw Error("Expecting " + toStr(obj1) + " but was " + toStr(obj2));16 },17 /** 18 * Assert equals. Do not use to compare two null value. Use {@link #isNull} to assert a null(or undefined) value.19 * @memberOf assert 20 * */21 "equals": function(obj1, obj2, desc){22 if(obj1 === obj2 || toStr(obj1) == toStr(obj2)){23 return true ;24 };25 throw new Error(desc || "Expecting " + toStr(obj1) + " but was " + toStr(obj2)) ;26 },27 "notEquals": function(obj1, obj2, desc){28 var _assert = this ;29 return this.exception(function(){30 _assert.equals(obj1, obj2);31 }, "Expecting " + toStr(obj1) + " to be not equal to " + toStr(obj2));32 },33 // "notEqual": function(obj1, obj2, desc){34 // return this.notEquals(obj1, obj2, desc);35 // },36 37 "isTrue": function(obj, desc){38 if(obj === true){39 return true ;40 }41 throw new Error(desc || "Expecting true");42 },43 "isFalse": function(obj, desc){44 if(obj === false){45 return true ;46 }47 throw new Error(desc || "Expecting false");48 },49 "isNull": function(obj, desc){50 if(isNull(obj)){51 return true ;52 }53 throw Error(desc || "Expecting null");54 },55 "notNull": function(obj, desc){56 if(!isNull(obj)){57 return true ;58 }59 throw Error(desc || "Expecting not null");60 },61 "fail": function(msg){62 msg = isNull(msg)? "": msg ;63 throw Error(msg);64 },65 "contains": function(obj1, obj2, desc){66 try{67 return this.isTrue(obj1.indexOf(obj2) > -1, desc)68 }catch(e){69 throw Error("Expecting " + toStr(obj2) + " in " + toStr(obj1));70 }71 },72 "exception": function(callback, desc){73 var err ;74 try{75 //FIXME ?? context of callback?76 callback();77 }catch(e){78 err = e ;79 }80 return this.notNull(err, desc || "Expecting exception from closure.");81 }82 // "guarantee": function(){83 // return {84 // counter: 0,85 // crossPoints: [],86 // cross: function(desc){87 // this.crossPoints.push(desc);88 // this.counter ++;89 // },90 // count : function(num, desc){91 // try{92 // var pass = assert.eq(this.counter, num, desc); 93 // this.counter = 0;94 // this.crossPoints = [];95 // }catch(e){96 // var msg = desc || e.message ;97 // throw Error(msg + "\n" + "Captured cross points: " + toStr(this.crossPoints) );98 // }99 100 // }101 // };102 // }103 104 };105 //106 var makeAlias = function(targetObj, targetFuncName, aliases ){107 if(!targetObj || !targetObj[targetFuncName] || !aliases){108 return ;109 }110 if(typeof aliases == "string"){111 if(typeof targetObj[aliases] == "undefined"){112 targetObj[aliases] = targetObj[targetFuncName] ;113 }else{114 //? already exists115 }116 }else if(aliases.length){117 for(var i = 0 ;i < aliases.length; i ++){118 makeAlias(targetObj, targetFuncName, aliases[i]);119 }120 }121 };122 // makeAlias(assert, "strictEquals", ["strictEqual", "assertStrictEqual", "assertStrictEquals"]);123 // makeAlias(assert, "equals", ["eq", "equal", "assertEquals", "assertEqual"]);124 // makeAlias(assert, "notEquals", ["neq", "notEqual", "assertNotEqual", "assertNotEquals"]);125 // makeAlias(assert, "isTrue", ["t", "assertTrue"]);126 // makeAlias(assert, "isFalse", ["f", "assertFalse"]);127 // makeAlias(assert, "isNull", ["assertNull"]);128 // makeAlias(assert, "notNull", ["assertNotNull"]);129 // makeAlias(assert, "contains", ["contain"]);130 /** Dispatch the function call to assert.prop(params) */131 NUnit.Assert._dispatch = function(a, prop, params){132 try{133 var ret = invoke(assert, prop, params);134 a.assertCount ++ ;135 return ret ;136 }catch(e){137 for(var idx in params){138 params[idx] = toStr(params[idx]);139 }140 e.assertStack = e.assertStack || [];141 e.assertStack.push("at " + prop + "(" + params.join(",") + ")");142 throw e;143 } 144 };145 // Dispatch all the function call from NUnit.Asssert.prototype.prop to assert.prop146 for(var prop in assert){147 if(typeof assert[prop] == "function"){148 NUnit.Assert.prototype[prop] = (function(prop){149 return function(){150 return NUnit.Assert._dispatch(this, prop, argsToArray(arguments));151 };152 })(prop);153 }154 };155 makeAlias(NUnit.Assert.prototype, "strictEquals", ["strictEqual", "assertStrictEqual", "assertStrictEquals"]);156 makeAlias(NUnit.Assert.prototype, "equals", ["eq", "equal", "assertEquals", "assertEqual"]);157 makeAlias(NUnit.Assert.prototype, "notEquals", ["neq", "notEqual", "assertNotEqual", "assertNotEquals"]);158 makeAlias(NUnit.Assert.prototype, "isTrue", ["t", "assertTrue"]);159 makeAlias(NUnit.Assert.prototype, "isFalse", ["f", "assertFalse"]);160 makeAlias(NUnit.Assert.prototype, "isNull", ["assertNull"]);161 makeAlias(NUnit.Assert.prototype, "notNull", ["assertNotNull"]);162 makeAlias(NUnit.Assert.prototype, "contains", ["contain"]);163 NUnit.Assert.prototype.tracer = function(desc){164 return new Tracer(this);165 }166 var Tracer = function(assert){167 this.assert = assert ;168 this.traceQueue = [];169 this.traceCount = 0;170 this.traceMap = {};171 };172 Tracer.prototype = {173 trace: function(desc){174 this.traceCount ++ ;175 this.traceQueue.push(["trace", desc]);176 },177 once: function(desc){178 var key = toStr(desc);179 var val = this.traceMap[key];180 if(val){181 this.traceMap[key] = val + 1;182 }else{183 this.traceMap[key] = 1;184 this.traceQueue.push(["traceOnce", desc]);185 }186 },187 verify: function(count, desc){188 try{189 switch(typeof count){190 case "number" :191 return this.assert.eq(count, this.traceQueue.length, desc);192 break;193 case "object":194 default:195 } 196 }catch(e){197 //Failed verification198 if(e.assertStack){199 e.assertStack.push("at tracer.verify(" + toStr(count) + ", " + toStr(desc) + ")");200 }201 throw e ;202 }203 204 }205 };206 /** 207 * Uses JSON.stringify to convert the object into a string.208 * @private */209 var toStr = function(obj){210 if(typeof obj == "function"){211 return obj.toString();212 }213 if (isNull(obj)){214 return "" + obj;215 }216 217 return JSON.stringify(obj);218 };219 /** 220 * Returns true if obj is null of undefined 221 * @private222 * */223 var isNull = function(obj){224 /* null === undefined is false 225 * null == undefined is true */226 return obj == undefined ;227 };228 /** Return an array containing all the parameters in the argument object (used to delegate function calls). 229 @private 230 @params {Arguments} args */231 var argsToArray = function(args){232 var arr = [];233 if(args && args.length)234 for(var i = 0 ;i < args.length; i ++){235 arr.push(args[i]);236 }237 return arr ;238 };239 var invoke = function(thisArg, funcName, params){240 var alen = arguments.length ;241 if(alen < 2 || !thisArg){242 throw Error("Must have thisArg and funcName");243 }244 var cParams = [];245 var func = thisArg[funcName] ;246 switch(alen){247 case 2:248 break;249 case 3:250 Array.isArray(params) ? cParams = params: cParams = [params] ;251 break;252 default:253 // > 3254 for(var i = 2 ; i < alen ; i ++){255 cParams.push(arguments[i]);256 }257 }258 // cParams.unshift(thisArg);259 if(func && typeof func == "function"){260 // return func.call.apply(func, cParams) ;261 return func.apply(thisArg, cParams) ;262 }else{263 throw Error( funcName + " is not found on object.");264 }265 };266 267 var Test = NUnit.Test = function(desc){268 if(this instanceof Test == false){269 return new Test(desc);270 }271 this.id = "_" + Date.now();272 this.desc = desc || "";273 this.assert = new NUnit.Assert(this);274 /** 275 * A map of result objects - function name -> result276 * @field */277 this.results = {};278 //Add new test object into Test.instances array279 Test.instances.push(this);280 };281 var EMPTY_FUNC = function(){};282 Test.prototype.before = EMPTY_FUNC ;283 Test.prototype.after = EMPTY_FUNC ;284 Test.prototype.beforeEach = EMPTY_FUNC ;285 Test.prototype.afterEach = EMPTY_FUNC ;286 Test.prototype.hasTest = function(funcName){287 return this.hasOwnProperty(funcName) && typeof this[funcName] === "function" && Test.isValidTestName(funcName);288 };289 Test.beforeClass = EMPTY_FUNC ;290 Test.afterClass = EMPTY_FUNC ;291 Test.BEFORE_ALL = "beforeAll" ;292 Test.AFTER_ALL = "afterAll" ;293 Test.BEFORE = "before" ;294 Test.AFTER = "after" ;295 Test.BEFORE_CLASS = "beforeClass" ;296 Test.AFTER_CLASS = "afterClass";297 /**Keep track of all instances of Test */298 Test.instances = [];299 /** Returns true if the argument is a valid test case function name */300 Test.isValidTestName = function(funcName){301 if(!funcName || funcName === Test.BEFORE_ALL || funcName === Test.AFTER_ALL || funcName === Test.BEFORE || funcName === Test.AFTER){302 return false ;303 }304 return true ;305 };306 307 var TestRunner = NUnit.TestRunner = function(){308 if(this instanceof TestRunner == false){309 return new TestRunner();310 }311 /** 312 * A list of result objects313 * @field */314 this.results = [];315 this.total = 0;316 this.failed = [];317 /**318 * A list of appenders319 */320 this.appenders = [];321 this.reporters = [];322 };323 TestRunner.prototype = {324 /** @param {Test} test */325 run: function(test){326 var total = 0, failed = 0 , successful = 0, target = test ;327// this.out.println('log', '[TestRunner] ' + 'Starting test.');328 if(!test || !test instanceof Test ){329 throw new Error('No test found.');330 return ;331 }332 // Count number of total tests333 for(var attr in test){334 if(test.hasTest(attr)){335 total ++;336 }337 }338 // failedTarget={};339 this.info('[TestRunner] ' + 'Starting test.');340 this.report("testUnitBegin", [total, test.desc]);341 342 //Run Test.before343 if(test.hasOwnProperty(Test.BEFORE_ALL) ){344 this.log('[TestRunner] ' + 'Running BEFORE_ALL function.');345 invoke(test, Test.BEFORE_ALL);346 }347 for(var prop in test){348 if(test.hasTest(prop)){349 350 if(test.hasOwnProperty(Test.BEFORE) && typeof test[Test.BEFORE] === "function"){351 this.log('[TestRunner] ' + 'Running BEFORE.');352 try{353 invoke(test,Test.BEFORE);354 }catch(e){355 ;356 }357 358 }359 360 if(typeof test[prop] === "function"){361 this.log('[TestRunner] ' + 'Running #' + prop);362 var result = new TestResult(test, prop);363 this.report("testBegin", [result.id, prop]);364 this.results.push(result);365 test.results[prop] = result ;366 // total ++ ;367 var preCount = test.assert.assertCount ;368 try{369 result.startTime = Date.now();370 invoke(test,prop, test.assert) ;371 result.endTime = Date.now();372 successful ++ ;373 result.passed = true;//result.passed = false by default374 result.assertCount = test.assert.assertCount - preCount ;375 }catch(e){376 failed ++ ;377 result.endTime = Date.now();378 result.assertCount = test.assert.assertCount - preCount ;379 380 var msg = e.message;381 if(e.assertStack){382 e.assertStack.push(result.assertCount + " asserts so far.");383 msg += " " + e.assertStack.join("\n") ;384 }385 this.err("[#" + prop +"] " + msg);386 this.report("println", ["ERROR", "[#" + prop +"] " + msg]);387 //this.err("Failed: #"+ prop );388 //this.report("println", ["ERROR", "Failed: #"+ prop ]);389 result.error = e;390 }finally{391 this.report("testEnd", [result.id, prop, result]);392 }393 //Put result into394 }395 if(test.hasOwnProperty(Test.AFTER) && typeof test[Test.AFTER] === "function"){396 this.log('[TestRunner] ' + 'Running AFTER');397 invoke(test,Test.AFTER);398 }399 }400 }401 if(test.hasOwnProperty(Test.AFTER_ALL) ){402 this.log('[TestRunner] ' + 'Running AFTERALL');403 invoke(test, Test.AFTER_ALL);404 }405 this.report("testUnitEnd", [total, test.desc, failed]);406 this.log('[TestRunner] ' + 'Finishing test.');407 this.info('[TestRunner] ' + 'Ran ' + total + ' tests, ' + successful + ' were successful, ' + failed + ' were failed.');408 },409 info: function(msg){410 this._log("INFO", msg)411 },412 error: function(msg){413 this._log("ERROR", msg);414 },415 err: function(msg){416 this.error(msg);417 },418 log: function(msg){419 this._log("LOG", msg);420 },421 _log: function(level, msg, skipAppenders){422 var debug = this.debug ;423 if(console && debug){424 switch(level){425 case "LOG":426 console.log(msg);427 break;428 case "INFO":429 console.info(msg);430 break;431 case "ERROR":432 console.error(msg);433 break ;434 }435 }436 if(this.appenders && !skipAppenders){437 for(var index in this.appenders){438 try{439 this.appenders[index]['append'](level, msg);440 }catch(e){441 this._log("ERROR", e.message, true);442 }443 444 }445 446 }447 },448 addReporter: function(reporter){449 if(typeof reporter == "string") {450 switch(reporter){451 case "ConsoleReporter":452 reporter = ConsoleReporter;453 break;454 }455 }456 this.reporters.push(reporter);457 },458 report: function(event, params){459 for(var index in this.reporters){460 try{461 var rep = this.reporters[index] ;462 if(typeof rep[event] == "function") rep[event].apply(rep, params);463 }catch(e){464 if(console){465 console.error("Error in reporter." + event + "(): " + e.message);466 }467 throw e ;468 }469 }470 },471 debug : false 472 473 };474 var TestResult = NUnit.TestResult = function(test, testName){475 this.testName = testName ;476 this.id = test.id + "." + testName;477 this.passed = false ;478 this.error = null;479 this.assertCount = 0;480 this.startTime = Date.now();481 this.endTime = -1 ;482 };483 /** Global config object */484 var _config = null;485 /** Gets global config object */486 var _getConfig = function(){487 _config = _config || NUnit.defaultConfig();488 return _config ;489 };490 /** Copy all the attributes that options does not have from optTemplate to options */491 var _replicateConfig = function(options, optTemplate){492 for(var attr in optTemplate){493 if(typeof options[attr] === "undefined"){494 options[attr] = optTemplate[attr];495 }496 }497 };498 /** Returns default config */499 NUnit.defaultConfig = function(){500 return {501 tests: Test.instances,502 reporters: [ConsoleReporter],503 debug: false504 };505 };506 /** Get or set global config */507 NUnit.config = function(options){508 if(options){509 _replicateConfig(options, _getConfig())510 _config = options ;511 }512 return _getConfig();513 };514 /** Convenient method to run all instances of Test */515 NUnit.execute = function(opt){516 opt = opt || {} ;517 _replicateConfig(opt, _getConfig()) ;518 var runner = new NUnit.TestRunner();519 if(opt.debug){520 runner.debug = true ;521 }522 for(var index in opt.reporters){523 runner.addReporter(opt.reporters[index]);524 }525 for(var index in opt.tests){526 runner.run(opt.tests[index]);527 }528 }529 var ConsoleReporter = {530 id: "ConsoleReporter",531 /** @param {Number} testCount */532 /** @param {String} desc */533 testUnitBegin: function(testCount, desc){534 this.println("INFO", 'Starting to run ' + testCount + ' tests in module: ' + desc);535 },536 /** @param {String} testName */537 testBegin: function(id, testName){538 //this.println("INFO", "Running #" + testName);539 },540 /** @param {NUnit.Test} test */541 /** @param {String} testName */542 /** @param {Boolean} result */543 testEnd: function(id, testName, result){544 if(result.passed){545 this.println("INFO", "PASSED" + " " + "#" + testName + "(). " + result.assertCount + " asserts.");546 }else{547 this.println("ERROR", "FAILED" + " " + "#" + testName + "(). ");548 }549 },550 testUnitEnd: function(testCount, desc, failedCount){551 this.println("INFO", "Finishing test module. Ran " + testCount + " tests. " + (testCount - failedCount) + " were successful.");552 if(failedCount > 0) this.println("ERROR", failedCount + " tests were failed.");553 },554 println: function(level, msg){555 var id = "[" + this.id + "] " ;556 if(console){557 switch(level){558 case "LOG":559 console.log(id + msg);560 break;561 case "INFO":562 console.info(id + msg);563 break;564 case "ERROR":565 console.error(id + msg);566 break ;567 }568 }569 }570 } 571 if(typeof module !== "undefined") module.exports = NUnit ;572 if(global && global.window === global){573 global.NUnit = NUnit ;574 }575 ...
engine.js
Source:engine.js
...81 this.Primitive = function (name, func) {82 var f = func;83 var word = function () {84 var len = f.length;85 assertStack(len);86 var args = context.Stack.slice(0, len).reverse(); // TODO: more efficient that slice/reverse87 context.Stack = context.Stack.slice(len);88 var result = f.apply(null, args);89 if (result) {90 if (result.kind == "tuple") {91 for (var i = 0; i < result.length; i++) {92 context.Stack.unshift(result[i]);93 }94 }95 else {96 context.Stack.unshift(result);97 }98 }99 }100 word.kind = "primitive";101 word.disp = name;102 dictionary[name] = word;103 return word;104 };105106 var context = { Stack: [] };107108 this.Reset = function () {109 context = { Stack: [] };110 };111112 function assertStack(length) {113 //if (context.Stack.length < length)114 // alert("Stack underflow!");115 }116117 this.Push = function (val) {118 if (val !== null && val !== undefined)119 context.Stack.unshift(val);120 };121122 this.Peek = function () {123 assertStack(1);124 return context.Stack[0];125 };126127 this.Pop = function () {128 assertStack(1);129 return context.Stack.shift();130 };131132 function literal(val) {133 var lit = eval(val);134 return { kind: "literal", disp: val, val: lit };135 }136137 function error(token) {138 var e = function () { /* alert("Undefined word: '" + token + "'"); */ };139 e.kind = "error";140 e.disp = token;141 return e;142 }
...
assert.test.js
Source:assert.test.js
...48 } catch (err) {49 return err;50 }51 }52 function assertStack(stack) {53 ok(typeof stack === 'string', 'Expected err to have a stack');54 const source = stack.split('\n').slice(1, 2).shift().trim().replace(__dirname, '');55 ok.strictEqual(source, 'at createErr (/assert.test.js:50:16)');56 }57 const status = 500;58 const statusText = 'Internal Server Error';59 const message = 'Error Message';60 const props = { code: 'ERR_CODE', odd: 1, even: 2 };61 const inspect = obj => util.inspect(obj, { colors: false, depth: 1, compact: true });62 it(`should create an error with: assert.fail(${status}, '${message}', ${inspect(props)})`, () => {63 const err = createErr(status, message, props);64 ok(err instanceof Error, 'Expected err to be an instance of Error');65 ok.strictEqual(err.message, message);66 ok.deepStrictEqual({ ...err }, { ...props, status, statusCode: status, statusText });67 assertStack(err.stack);68 });69 it(`should create an error with: assert.fail(${status}, '${message}')`, () => {70 const err = createErr(status, message);71 ok(err instanceof Error, 'Expected err to be an instance of Error');72 ok.strictEqual(err.message, message);73 ok.deepStrictEqual({ ...err }, { status, statusCode: status, statusText });74 assertStack(err.stack);75 });76 it(`should create an error with: assert.fail(new Error('${message}'), ${inspect(props)})`, () => {77 const err = createErr(new Error(message), props);78 ok(err instanceof Error, 'Expected err to be an instance of Error');79 ok.strictEqual(err.message, message);80 ok.deepStrictEqual({ ...err }, { ...props });81 assertStack(err.stack);82 });83 it(`should create an error with: assert.fail(${status})`, () => {84 const err = createErr(status);85 ok(err instanceof Error, 'Expected err to be an instance of Error');86 ok.strictEqual(err.message, `HTTP ${status} - ${statusText}`);87 ok.deepStrictEqual({ ...err }, { status, statusCode: status, statusText });88 assertStack(err.stack);89 });90 it(`should create an error with: assert.fail(new Error('${message}'))`, () => {91 const err = createErr(new Error(message));92 ok(err instanceof Error, 'Expected err to be an instance of Error');93 ok.strictEqual(err.message, message);94 ok.deepStrictEqual({ ...err }, {});95 assertStack(err.stack);96 });97 it(`should create an error with: assert.fail(${inspect(props)})`, () => {98 const err = createErr(props);99 ok(err instanceof Error, 'Expected err to be an instance of Error');100 ok.strictEqual(err.message, 'An error occurred');101 ok.deepStrictEqual({ ...err }, { ...props });102 assertStack(err.stack);103 });104 it(`should create an error with: assert.fail(${inspect({ ...props, message, status })})`, () => {105 const err = createErr({ ...props, message, status });106 ok(err instanceof Error, 'Expected err to be an instance of Error');107 ok.strictEqual(err.message, message);108 ok.deepStrictEqual({ ...err }, { ...props, status, statusCode: status, statusText });109 assertStack(err.stack);110 });111 it(`should create an error with: assert.fail(${inspect({ ...props, error: message, statusCode: status })})`, () => {112 const err = createErr({ ...props, error: message, statusCode: status });113 ok(err instanceof Error, 'Expected err to be an instance of Error');114 ok.strictEqual(err.message, message);115 ok.deepStrictEqual({ ...err }, { ...props, error: message, status, statusCode: status, statusText });116 assertStack(err.stack);117 });118 it('should create an error with: assert.fail()', () => {119 const err = createErr();120 ok(err instanceof Error, 'Expected err to be an instance of Error');121 ok.strictEqual(err.message, 'An error occurred');122 ok.deepStrictEqual({ ...err }, {});123 assertStack(err.stack);124 });125 it('should throw an error with invalid arguments', () => {126 try {127 assert.fail(true);128 ok.fail('Should have errored');129 } catch (err) {130 ok(err instanceof TypeError, 'Expected err to be an instance of TypeError');131 ok.strictEqual(err.message, 'Invalid arguments passed to http-assert-plus');132 }133 });134 });135 describe('#create', () => {136 let instance = null;137 before(() => {...
vmdebugger.js
Source:vmdebugger.js
...67 .clearValue('#txinput')68 .setValue('#txinput', '0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')69 .click('#load')70 .multipleClick('#intoforward', 63)71 .assertStack(['0:0x', '1:0x60', '2:0x65', '3:0x38', '4:0x55', '5:0x60fe47b1'])72 .assertStorageChanges(['0x290decd9548b62a8d60345a988386fc84ba6bc95484008f6362f93160ef3e563:Objectkey:0x00value:0x38'])73 .assertCallData(['0:0x60fe47b10000000000000000000000000000000000000000000000000000000000000038'])74 .assertCallStack(['0:0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5'])75 .assertStackValue(1, '1:0x60')76 .assertMemoryValue(6, '0x60:60606040526040516020806045833981????R??Q????E?9?')77 .assertMemoryValue(7, '0x70:01604052808051906020019091905050???R??Q???????PP')78 .assertMemoryValue(8, '0x80:5b806001016000600050819055505b50?????????P??UP?P')79 .click('#intoforward') // CREATE80 .assertStack([''])81 .assertStorageChanges([])82 .assertMemory([''])83 .assertCallData(['0:0x0000000000000000000000000000000000000000000000000000000000000000000000000000006060606040526040516020806045833981016040528080519060200190919050505b806001016000600050819055'])84 .assertCallStack(['0:0x0d3a18d64dfe4f927832ab58d6451cecc4e517c5', '1:(ContractCreation-Step63)'])85 return browser86}87function slider (browser) {88 browser89 .clearValue('#txinput')90 .setValue('#txinput', '0x20ef65b8b186ca942fcccd634f37074dde49b541c27994fc7596740ef44cfd51')91 .click('#load')92 .click('#intoforward')93 .click('#intoforward')94 .click('#intoforward')...
head_win64cfi.js
Source:head_win64cfi.js
...102// Test that the top of the given stack (from extra data) matches the given103// expected frames.104//105// expected is { symbol: "", trust: "" }106function assertStack(stack, expected) {107 for (let i = 0; i < stack.length; ++i) {108 if (i >= expected.length) {109 ok("Top stack frames were expected");110 return;111 }112 let frame = stack[i];113 let expectedFrame = expected[i];114 let dumpThisFrame = function() {115 info(" Actual frame: " + stackFrameToString(i, frame));116 info(117 "Expected { symbol: " +118 expectedFrame.symbol +119 ", trust: " +120 expectedFrame.trust +121 "}"122 );123 };124 if (expectedFrame.trust) {125 if (expectedFrame.trust.startsWith("!")) {126 // A "!" prefix on the frame trust matching is a logical "not".127 if (frame.trust === expectedFrame.trust.substring(1)) {128 dumpThisFrame();129 info("Expected frame trust matched when it should not have.");130 ok(false);131 }132 } else if (frame.trust !== expectedFrame.trust) {133 dumpThisFrame();134 info("Expected frame trust did not match.");135 ok(false);136 }137 }138 if (expectedFrame.symbol) {139 if (typeof frame.module_index === "undefined") {140 // Without a module_index, it happened in an unknown module. Currently141 // you can't specify an expected "unknown" module.142 info("Unknown symbol in unknown module.");143 ok(false);144 }145 if (frame.module_index < 0 || frame.module_index >= gModules.length) {146 dumpThisFrame();147 info("Unknown module.");148 ok(false);149 return;150 }151 let base = gModules[frame.module_index].base_addr;152 let moduleOffset = getModuleOffset(base, frame.ip);153 let filename = gModules[frame.module_index].filename;154 if (filename == "testcrasher.dll") {155 let nearestSym = findNearestTestCrasherSymbol(moduleOffset);156 if (nearestSym === null) {157 dumpThisFrame();158 info("Unknown symbol.");159 ok(false);160 return;161 }162 if (nearestSym.symbol !== expectedFrame.symbol) {163 dumpThisFrame();164 info("Mismatching symbol.");165 ok(false);166 }167 }168 }169 }170}171// Performs a crash, runs minidump-analyzer, and checks expected stack analysis.172//173// how: The crash to perform. Constants defined in both CrashTestUtils.jsm174// and nsTestCrasher.cpp (i.e. CRASH_X64CFI_PUSH_NONVOL)175// expectedStack: An array of {"symbol", "trust"} where trust is "cfi",176// "context", "scan", et al. May be null if you don't need to check the stack.177// minidumpAnalyzerArgs: An array of additional arguments to pass to178// minidump-analyzer.exe.179function do_x64CFITest(how, expectedStack, minidumpAnalyzerArgs) {180 // Setup is run in the subprocess so we cannot use any closures.181 let setupFn = "crashType = CrashTestUtils." + how + ";";182 let callbackFn = function(minidumpFile, extra, extraFile) {183 runMinidumpAnalyzer(minidumpFile, minidumpAnalyzerArgs);184 // Refresh updated extra data185 extra = parseKeyValuePairsFromFile(extraFile);186 initTestCrasherSymbols();187 let stackTraces = JSON.parse(extra.StackTraces);188 let crashingThreadIndex = stackTraces.crash_info.crashing_thread;189 gModules = stackTraces.modules;190 let crashingFrames = stackTraces.threads[crashingThreadIndex].frames;191 dumpStackFrames(crashingFrames, 10);192 assertStack(crashingFrames, expectedStack);193 };194 do_crash(setupFn, callbackFn, true, true);...
UndoStack.spec.js
Source:UndoStack.spec.js
...7describe('array/Stack', function () {8 it('shall push items to stack', function () {9 const s = new UndoStack({ max: 3 })10 s.push(1).push(2).push(3)11 assertStack(s, { max: 3, stack: [1, 2, 3], low: 0, high: 2, pos: 2 })12 })13 it('shall push items to stack beyond max', function () {14 const s = new UndoStack({ max: 3 })15 s.push(1).push(2).push(3).push(4)16 assertStack(s, { max: 3, stack: [4, 2, 3], low: 1, high: 0, pos: 0 })17 })18 it('shall push items to stack and undo', function () {19 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })20 const r = s.undo()21 strictEqual(r, 2)22 assertStack(s, { max: 3, stack: [1, 2, 3], low: 0, high: 2, pos: 1 })23 })24 it('shall push items to stack and undo', function () {25 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })26 const r = s.push(4).undo()27 strictEqual(r, 3)28 assertStack(s, { max: 3, stack: [4, 2, 3], low: 1, high: 0, pos: 2 })29 })30 it('shall push items to stack do 2x undo', function () {31 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })32 s.push(4).undo()33 const r = s.undo()34 strictEqual(r, 2)35 assertStack(s, { max: 3, stack: [4, 2, 3], low: 1, high: 0, pos: 1 })36 })37 it('shall be undefined after 3x undo', function () {38 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })39 s.push(4).undo()40 s.undo()41 const r = s.undo()42 strictEqual(r, undefined)43 assertStack(s, { max: 3, stack: [4, 2, 3], low: 1, high: 0, pos: 1 })44 })45 it('shall be undefined on redo', function () {46 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })47 s.push(4)48 const r = s.redo()49 strictEqual(r, undefined)50 assertStack(s, { max: 3, stack: [4, 2, 3], low: 1, high: 0, pos: 0 })51 })52 it('shall overwrite after undo', function () {53 const s = new UndoStack({ max: 3, stack: [1, 2, 3] })54 s.push(4).undo()55 s.push(5)56 assertStack(s, { max: 3, stack: [5, 2, 3], low: 1, high: 0, pos: 0 })57 })58 it('shall be in same state after undo and redo', function () {59 const undoredo = 260 const s = new UndoStack({ max: 3 })61 s.push(1).push(2).push(3).push(4).push(5).push(6).push(7)62 for (let i = 0; i < undoredo; i++) {63 s.undo()64 }65 for (let i = 0; i < undoredo; i++) {66 s.redo()67 }68 assertStack(s, { max: 3, stack: [7, 5, 6], low: 1, high: 0, pos: 0 })69 })...
assert-runtime-error.js
Source:assert-runtime-error.js
...35 expect(err.message.indexOf(expected.message)).eql(0);36 else37 expect(err.message).eql(expected.message);38 expect(err.stack.indexOf(expected.message)).eql(0);39 assertStack(err, expected);40}41function assertAPIError (err, expected) {42 assertRuntimeError(err, expected);43 expect(expected.callsite).to.not.empty;44 expect(err.stack.indexOf(expected.message + '\n\n' + expected.callsite)).eql(0);45 expect(stripAnsi(err.coloredStack)).eql(err.stack);46}47// NOTE: chai's throws doesn't perform deep comparison of error objects48function assertThrow (fn, expectedErr) {49 let actualErr = null;50 try {51 fn();52 }53 catch (err) {...
assert-error.js
Source:assert-error.js
...31}32function assertError (err, expected) {33 expect(err.message).eql(expected.message);34 expect(err.stack.indexOf(expected.message)).eql(0);35 assertStack(err, expected);36}37function assertAPIError (err, expected) {38 assertError(err, expected);39 expect(expected.callsite).to.not.empty;40 expect(err.stack.indexOf(expected.message + '\n\n' + expected.callsite)).eql(0);41 expect(stripAnsi(err.coloredStack)).eql(err.stack);42}43// NOTE: chai's throws doesn't perform deep comparison of error objects44function assertThrow (fn, expectedErr) {45 let actualErr = null;46 try {47 fn();48 }49 catch (err) {...
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 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button')11 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#submit-button')17 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button')23 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');24});25import { Selector } from 'testcafe';
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 await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button');11 await t.expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');12});13import {Selector, t} from 'testcafe';14class Page {15 constructor () {16 this.nameInput = Selector('input').withAttribute('data-testid', 'free-plan-sign-up-name');17 this.emailInput = Selector('input').with
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 let headerHTML = await articleHeader.innerHTML;8 .expect(headerText).eql('Thank you, John Smith!')9 .expect(headerHTML).contains('John Smith');10});
Using AI Code Generation
1import { Selector } from 'testcafe';2test('My first test', async t => {3 .typeText('#developer-name', 'John Smith')4 .click('#tried-test-cafe')5 .click('#submit-button');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#tried-test-cafe')11 .click('#submit-button');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#tried-test-cafe')17 .click('#submit-button');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#tried-test-cafe')23 .click('#submit-button');24});25import { Selector } from 'testcafe';26test('My first test', async t => {27 .typeText('#developer-name', 'John Smith')28 .click('#tried-test-cafe')29 .click('#submit-button');30});31import { Selector } from 'testcafe';32test('
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 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');6});7import { Selector } from 'testcafe';8test('My first test', async t => {9 .typeText('#developer-name', 'John Smith')10 .click('#submit-button');11 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');12});13import { Selector } from 'testcafe';14test('My first test', async t => {15 .typeText('#developer-name', 'John Smith')16 .click('#submit-button');17 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');18});19import { Selector } from 'testcafe';20test('My first test', async t => {21 .typeText('#developer-name', 'John Smith')22 .click('#submit-button');23 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');24});25import { Selector } from 'testcafe';
Using AI Code Generation
1test('My first test', async t => {2 .typeText('#developer-name', 'John Smith')3 .click('#submit-button');4 assertStack(t, 'test')5 .click('#tried-test-cafe')6 .click('#tried-test-cafe')7 .click('#tried-test-cafe');8 assertStack(t, 'test')9 .click('#tried-test-cafe')10 .click('#tried-test-cafe')11 .click('#tried-test-cafe');12 assertStack(t, 'test')13 .click('#tried-test-cafe')14 .click('#tried-test-cafe')15 .click('#tried-test-cafe');16 assertStack(t, 'test')17 .click('#tried-test-cafe')18 .click('#tried-test-cafe')19 .click('#tried-test-cafe');20 assertStack(t, 'test')21 .click('#tried-test-cafe')22 .click('#tried-test-cafe')23 .click('#tried-test-cafe');24 assertStack(t, 'test')25 .click('#tried-test-cafe')26 .click('#tried-test-cafe')27 .click('#tried-test-cafe');28 assertStack(t, 'test')29 .click('#tried-test-cafe')30 .click('#tried-test-cafe')31 .click('#tried-test-cafe');32 assertStack(t, 'test')33 .click('#tried-test-cafe')34 .click('#tried-test-cafe');35});36test('My first test', async t => {37 .typeText('#developer-name', 'John Smith')38 .click('#submit-button');39 assertStack(t, 'test')40 .click('#tried-test-cafe')41 .click('#tried-test-cafe')42 .click('#tried-test-cafe');43 assertStack(t, 'test')44 .click('#tried-test-cafe')45 .click('#tried-test-cafe')46 .click('#tried-test-cafe');
Using AI Code Generation
1import { Selector } from 'testcafe';2test('Assertion with Selector', async t => {3 .expect(Selector('#developer-name').value).eql('', 'input is empty')4 .typeText('#developer-name', 'Peter')5 .expect(Selector('#developer-name').value).eql('Peter', 'input has text "Peter"');6});7 √ input is empty (1ms)81 passed (2s)9 √ input is empty (1ms)101 passed (2s)11### Additional information (optional)
Using AI Code Generation
1import { Selector } from 'testcafe';2import { assertStack } from 'testcafe-browser-tools';3test('My Test', async t => {4 await assertStack('Chrome', 2);5 .click('#populate')6 .click('#submit-button');7});8### assertStack(browserName, expectedStackCount)
Using AI Code Generation
1const { Selector } = require('testcafe');2fixture('Getting Started')3test('My first test', async t => {4});5test('My second test', async t => {6 .click('#populate')7 .click('#submit-button');8 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');9});10test('My third test', async t => {11 .click('#populate')12 .click('#submit-button');13 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');14});15test('My fourth test', async t => {16 .click('#populate')17 .click('#submit-button');18 .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');19});
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!!