Best JavaScript code snippet using chai
traits-core.test.js
Source:traits-core.test.js
1"use strict";2const ERR_CONFLICT = 'Remaining conflicting property: ',3 ERR_REQUIRED = 'Missing required property: ';4function assertSametrait(test, trait1, trait2) {5 let names1 = Object.getOwnPropertyNames(trait1),6 names2 = Object.getOwnPropertyNames(trait2);7 test.assertEqual(8 names1.length,9 names2.length,10 'equal traits must have same amount of properties'11 );12 for (let i = 0; i < names1.length; i++) {13 let name = names1[i];14 test.assertNotEqual(15 -1,16 names2.indexOf(name),17 'equal traits must contain same named properties: ' + name18 );19 assertSameDescriptor(test, name, trait1[name], trait2[name]);20 }21}22function assertSameDescriptor(test, name, desc1, desc2) {23 if (desc1.conflict || desc2.conflict) {24 test.assertEqual(25 desc1.conflict,26 desc2.conflict,27 'if one of same descriptors has `conflict` another must have it: '28 + name29 );30 } else if (desc1.required || desc2.required) {31 test.assertEqual(32 desc1.required,33 desc2.required,34 'if one of same descriptors is has `required` another must have it: '35 + name36 );37 } else {38 test.assertEqual(39 desc1.get,40 desc2.get,41 'get must be the same on both descriptors: ' + name42 );43 test.assertEqual(44 desc1.set,45 desc2.set,46 'set must be the same on both descriptors: ' + name47 );48 test.assertEqual(49 desc1.value,50 desc2.value,51 'value must be the same on both descriptors: ' + name52 );53 test.assertEqual(54 desc1.enumerable,55 desc2.enumerable,56 'enumerable must be the same on both descriptors: ' + name57 );58 test.assertEqual(59 desc1.required,60 desc2.required,61 'value must be the same on both descriptors: ' + name62 );63 }64}65function Data(value, enumerable, confligurable, writable) {66 return {67 value: value,68 enumerable: false !== enumerable,69 confligurable: false !== confligurable,70 writable: false !== writable71 };72}73function Method(method, enumerable, confligurable, writable) {74 return {75 value: method,76 enumerable: false !== enumerable,77 confligurable: false !== confligurable,78 writable: false !== writable79 };80}81function Accessor(get, set, enumerable, confligurable) {82 return {83 get: get,84 set: set,85 enumerable: false !== enumerable,86 confligurable: false !== confligurable,87 };88}89function Required(name) {90 function required() { throw new Error(ERR_REQUIRED + name) }91 return {92 get: required,93 set: required,94 required: true95 };96}97function Conflict(name) {98 function conflict() { throw new Error(ERR_CONFLICT + name) }99 return {100 get: conflict,101 set: conflict,102 conflict: true103 };104}105function testMethod() {};106const { trait, compose, resolve, required, override, create } =107 require('traits/core');108exports['test:empty trait'] = function(test) {109 assertSametrait(110 test,111 trait({}),112 {}113 );114};115exports['test:simple trait'] = function(test) {116 assertSametrait(117 test,118 trait({119 a: 0,120 b: testMethod121 }),122 {123 a: Data(0, true, true, true),124 b: Method(testMethod, true, true, true)125 }126 );127};128exports['test:simple trait with required prop'] = function(test) {129 assertSametrait(130 test,131 trait({132 a: required,133 b: 1134 }),135 {136 a: Required('a'),137 b: Data(1)138 }139 );140};141exports['test:ordering of trait properties is irrelevant'] = function(test) {142 assertSametrait(test,143 trait({ a: 0, b: 1, c: required }),144 trait({ b: 1, c: required, a: 0 })145 );146};147exports['test:trait with accessor property'] = function(test) {148 let record = { get a() {}, set a(v) {} };149 let get = Object.getOwnPropertyDescriptor(record,'a').get;150 let set = Object.getOwnPropertyDescriptor(record,'a').set;151 assertSametrait(test,152 trait(record),153 { a: Accessor(get, set ) }154 );155};156exports['test:simple composition'] = function(test) {157 assertSametrait(test,158 compose(159 trait({ a: 0, b: 1 }),160 trait({ c: 2, d: testMethod })161 ),162 {163 a: Data(0),164 b: Data(1),165 c: Data(2),166 d: Method(testMethod)167 }168 );169};170exports['test:composition with conflict'] = function(test) {171 assertSametrait(test,172 compose(173 trait({ a: 0, b: 1 }),174 trait({ a: 2, c: testMethod })175 ),176 {177 a: Conflict('a'),178 b: Data(1),179 c: Method(testMethod)180 }181 );182};183exports['test:composition of identical props does not cause conflict'] =184function(test) {185 assertSametrait(test,186 compose(187 trait({ a: 0, b: 1 }),188 trait({ a: 0, c: testMethod })189 ),190 {191 a: Data(0),192 b: Data(1),193 c: Method(testMethod) }194 )195};196exports['test:composition with identical required props'] =197function(test) {198 assertSametrait(test,199 compose(200 trait({ a: required, b: 1 }),201 trait({ a: required, c: testMethod })202 ),203 {204 a: Required(),205 b: Data(1),206 c: Method(testMethod)207 }208 );209};210exports['test:composition satisfying a required prop'] = function (test) {211 assertSametrait(test,212 compose(213 trait({ a: required, b: 1 }),214 trait({ a: testMethod })215 ),216 {217 a: Method(testMethod),218 b: Data(1)219 }220 );221};222exports['test:compose is neutral wrt conflicts'] = function (test) {223 assertSametrait(test,224 compose(225 compose(226 trait({ a: 1 }),227 trait({ a: 2 })228 ),229 trait({ b: 0 })230 ),231 {232 a: Conflict('a'),233 b: Data(0)234 }235 );236};237exports['test:conflicting prop overrides required prop'] = function (test) {238 assertSametrait(test,239 compose(240 compose(241 trait({ a: 1 }),242 trait({ a: 2 })243 ),244 trait({ a: required })245 ),246 {247 a: Conflict('a')248 }249 );250};251exports['test:compose is commutative'] = function (test) {252 assertSametrait(test,253 compose(254 trait({ a: 0, b: 1 }),255 trait({ c: 2, d: testMethod })256 ),257 compose(258 trait({ c: 2, d: testMethod }),259 trait({ a: 0, b: 1 })260 )261 );262};263exports['test:compose is commutative, also for required/conflicting props'] =264function (test) {265 assertSametrait(test,266 compose(267 trait({ a: 0, b: 1, c: 3, e: required }),268 trait({ c: 2, d: testMethod })269 ),270 compose(271 trait({ c: 2, d: testMethod }),272 trait({ a: 0, b: 1, c: 3, e: required })273 )274 );275};276exports['test:compose is associative'] = function (test) {277 assertSametrait(test,278 compose(279 trait({ a: 0, b: 1, c: 3, d: required }),280 compose(281 trait({ c: 3, d: required }),282 trait({ c: 2, d: testMethod, e: 'foo' })283 )284 ),285 compose(286 compose(287 trait({ a: 0, b: 1, c: 3, d: required }),288 trait({ c: 3, d: required })289 ),290 trait({ c: 2, d: testMethod, e: 'foo' })291 )292 );293};294exports['test:diamond import of same prop does not generate conflict'] =295function (test) {296 assertSametrait(test,297 compose(298 compose(299 trait({ b: 2 }),300 trait({ a: 1 })301 ),302 compose(303 trait({ c: 3 }),304 trait({ a: 1 })305 ),306 trait({ d: 4 })307 ),308 {309 a: Data(1),310 b: Data(2),311 c: Data(3),312 d: Data(4)313 }314 );315};316exports['test:resolve with empty resolutions has no effect'] =317function (test) {318 assertSametrait(test, resolve({}, trait({319 a: 1,320 b: required,321 c: testMethod322 })), {323 a: Data(1),324 b: Required(),325 c: Method(testMethod)326 });327};328exports['test:resolve: renaming'] = function (test) {329 assertSametrait(test,330 resolve(331 { a: 'A', c: 'C' },332 trait({ a: 1, b: required, c: testMethod })333 ),334 {335 A: Data(1),336 b: Required(),337 C: Method(testMethod),338 a: Required(),339 c: Required()340 }341 );342};343exports['test:resolve: renaming to conflicting name causes conflict, order 1']344= function (test) {345 assertSametrait(test,346 resolve(347 { a: 'b'},348 trait({ a: 1, b: 2 })349 ),350 {351 b: Conflict('b'),352 a: Required()353 }354 );355};356exports['test:resolve: renaming to conflicting name causes conflict, order 2']357= function (test) {358 assertSametrait(test,359 resolve(360 { a: 'b' },361 trait({ b: 2, a: 1 })362 ),363 {364 b: Conflict('b'),365 a: Required()366 }367 );368};369exports['test:resolve: simple exclusion'] = function (test) {370 assertSametrait(test,371 resolve(372 { a: undefined },373 trait({ a: 1, b: 2 })374 ),375 {376 a: Required(),377 b: Data(2)378 }379 );380};381exports['test:resolve: exclusion to "empty" trait'] = function (test) {382 assertSametrait(test,383 resolve(384 { a: undefined, b: undefined },385 trait({ a: 1, b: 2 })386 ),387 {388 a: Required(),389 b: Required()390 }391 );392};393exports['test:resolve: exclusion and renaming of disjoint props'] =394function (test) {395 assertSametrait(test,396 resolve(397 { a: undefined, b: 'c' },398 trait({ a: 1, b: 2 })399 ),400 {401 a: Required(),402 c: Data(2),403 b: Required()404 }405 );406};407exports['test:resolve: exclusion and renaming of overlapping props'] =408function (test) {409 assertSametrait(test,410 resolve(411 { a: undefined, b: 'a' },412 trait({ a: 1, b: 2 })413 ),414 {415 a: Data(2),416 b: Required()417 }418 );419};420exports['test:resolve: renaming to a common alias causes conflict'] =421function (test) {422 assertSametrait(test,423 resolve(424 { a: 'c', b: 'c' },425 trait({ a: 1, b: 2 })426 ),427 {428 c: Conflict('c'),429 a: Required(),430 b: Required()431 }432 );433};434exports['test:resolve: renaming overrides required target'] =435function (test) {436 assertSametrait(test,437 resolve(438 { b: 'a' },439 trait({ a: required, b: 2 })440 ),441 {442 a: Data(2),443 b: Required()444 }445 );446};447exports['test:resolve: renaming required properties has no effect'] =448function (test) {449 assertSametrait(test,450 resolve(451 { b: 'a' },452 trait({ a: 2, b: required })453 ),454 {455 a: Data(2),456 b: Required()457 }458 );459};460exports['test:resolve: renaming of non-existent props has no effect'] =461function (test) {462 assertSametrait(test,463 resolve(464 { a: 'c', d: 'c' },465 trait({ a: 1, b: 2 })466 ),467 {468 c: Data(1),469 b: Data(2),470 a: Required()471 }472 );473};474exports['test:resolve: exclusion of non-existent props has no effect'] =475function (test) {476 assertSametrait(test,477 resolve(478 { b: undefined },479 trait({ a: 1 })480 ),481 {482 a: Data(1)483 }484 );485};486exports['test:resolve is neutral w.r.t. required properties'] =487function (test) {488 assertSametrait(test,489 resolve(490 { a: 'c', b: undefined },491 trait({ a: required, b: required, c: 'foo', d: 1 })492 ),493 {494 a: Required(),495 b: Required(),496 c: Data('foo'),497 d: Data(1)498 }499 );500};501exports['test:resolve supports swapping of property names, ordering 1'] =502function (test) {503 assertSametrait(test,504 resolve(505 { a: 'b', b: 'a' },506 trait({ a: 1, b: 2 })507 ),508 {509 a: Data(2),510 b: Data(1)511 }512 );513};514exports['test:resolve supports swapping of property names, ordering 2'] =515function (test) {516 assertSametrait(test,517 resolve(518 { b: 'a', a: 'b' },519 trait({ a: 1, b: 2 })520 ),521 {522 a: Data(2),523 b: Data(1)524 }525 );526};527exports['test:resolve supports swapping of property names, ordering 3'] =528function (test) {529 assertSametrait(test,530 resolve(531 { b: 'a', a: 'b' },532 trait({ b: 2, a: 1 })533 ),534 {535 a: Data(2),536 b: Data(1)537 }538 );539};540exports['test:resolve supports swapping of property names, ordering 4'] =541function (test) {542 assertSametrait(test,543 resolve(544 { a: 'b', b: 'a' },545 trait({ b: 2, a: 1 })546 ),547 {548 a: Data(2),549 b: Data(1)550 }551 );552};553exports['test:override of mutually exclusive traits'] = function (test) {554 assertSametrait(test,555 override(556 trait({ a: 1, b: 2 }),557 trait({ c: 3, d: testMethod })558 ),559 {560 a: Data(1),561 b: Data(2),562 c: Data(3),563 d: Method(testMethod)564 }565 );566};567exports['test:override of mutually exclusive traits is compose'] =568function (test) {569 assertSametrait(test,570 override(571 trait({ a: 1, b: 2 }),572 trait({ c: 3, d: testMethod })573 ),574 compose(575 trait({ d: testMethod, c: 3 }),576 trait({ b: 2, a: 1 })577 )578 );579};580exports['test:override of overlapping traits'] = function (test) {581 assertSametrait(test,582 override(583 trait({ a: 1, b: 2 }),584 trait({ a: 3, c: testMethod })585 ),586 {587 a: Data(1),588 b: Data(2),589 c: Method(testMethod)590 }591 );592};593exports['test:three-way override of overlapping traits'] = function (test) {594 assertSametrait(test,595 override(596 trait({ a: 1, b: 2 }),597 trait({ b: 4, c: 3 }),598 trait({ a: 3, c: testMethod, d: 5 })599 ),600 {601 a: Data(1),602 b: Data(2),603 c: Data(3),604 d: Data(5)605 }606 );607};608exports['test:override replaces required properties'] = function (test) {609 assertSametrait(test,610 override(611 trait({ a: required, b: 2 }),612 trait({ a: 1, c: testMethod })613 ),614 {615 a: Data(1),616 b: Data(2),617 c: Method(testMethod)618 }619 );620};621exports['test:override is not commutative'] = function (test) {622 assertSametrait(test,623 override(624 trait({ a: 1, b: 2 }),625 trait({ a: 3, c: 4 })626 ),627 {628 a: Data(1),629 b: Data(2),630 c: Data(4)631 }632 );633 assertSametrait(test,634 override(635 trait({ a: 3, c: 4 }),636 trait({ a: 1, b: 2 })637 ),638 {639 a: Data(3),640 b: Data(2),641 c: Data(4)642 }643 );644};645exports['test:override is associative'] = function (test) {646 assertSametrait(test,647 override(648 override(649 trait({ a: 1, b: 2 }),650 trait({ a: 3, c: 4, d: 5 })651 ),652 trait({ a: 6, c: 7, e: 8 })653 ),654 override(655 trait({ a: 1, b: 2 }),656 override(657 trait({ a: 3, c: 4, d: 5 }),658 trait({ a: 6, c: 7, e: 8 })659 )660 )661 );662};663exports['test:create simple'] = function(test) {664 let o1 = create(665 Object.prototype,666 trait({ a: 1, b: function() { return this.a; } })667 );668 test.assertEqual(669 Object.prototype,670 Object.getPrototypeOf(o1),671 'o1 prototype'672 );673 test.assertEqual(1, o1.a, 'o1.a');674 test.assertEqual(1, o1.b(), 'o1.b()');675 test.assertEqual(676 2,677 Object.getOwnPropertyNames(o1).length,678 'Object.keys(o1).length === 2'679 );680};681exports['test:create with Array.prototype'] = function(test) {682 let o2 = create(Array.prototype, trait({}));683 test.assertEqual(684 Array.prototype,685 Object.getPrototypeOf(o2),686 "o2 prototype"687 );688};689exports['test:exception for incomplete required properties'] =690function(test) {691 try {692 create(Object.prototype, trait({ foo: required }));693 test.fail('expected create to complain about missing required props');694 } catch(e) {695 test.assertEqual(696 'Error: Missing required property: foo',697 e.toString(),698 'required prop error'699 );700 }701};702exports['test:exception for unresolved conflicts'] = function(test) {703 try {704 create({}, compose(trait({ a: 0 }), trait({ a: 1 })));705 test.fail('expected create to complain about unresolved conflicts');706 } catch(e) {707 test.assertEqual(708 'Error: Remaining conflicting property: a',709 e.toString(),710 'conflicting prop error'711 );712 }713};714exports['test:verify that required properties are present but undefined'] =715function(test) {716 try {717 let o4 = Object.create(Object.prototype, trait({ foo: required }));718 test.assertEqual(true, 'foo' in o4, 'required property present');719 try {720 let foo = o4.foo;721 test.fail('access to required property must throw');722 } catch(e) {723 test.assertEqual(724 'Error: Missing required property: foo',725 e.toString(),726 'required prop error'727 )728 }729 } catch(e) {730 test.fail('did not expect create to complain about required props');731 }732};733exports['test:verify that conflicting properties are present'] =734function(test) {735 try {736 let o5 = Object.create(737 Object.prototype,738 compose(trait({ a: 0 }), trait({ a: 1 }))739 );740 test.assertEqual(true, 'a' in o5, 'conflicting property present');741 try {742 let a = o5.a; // accessors or data prop743 test.fail('expected conflicting prop to cause exception');744 } catch (e) {745 test.assertEqual(746 'Error: Remaining conflicting property: a',747 e.toString(),748 'conflicting prop access error'749 );750 }751 } catch(e) {752 test.fail('did not expect create to complain about conflicting props');753 }754};755exports['test diamond with conflicts'] = function(test) {756 function makeT1(x) trait({ m: function() { return x; } })757 function makeT2(x) compose(trait({ t2: 'foo' }), makeT1(x))758 function makeT3(x) compose(trait({ t3: 'bar' }), makeT1(x))759 let T4 = compose(makeT2(5), makeT3(5));760 try {761 let o = create(Object.prototype, T4);762 test.fail('expected diamond prop to cause exception');763 } catch(e) {764 test.assertEqual(765 'Error: Remaining conflicting property: m',766 e.toString(),767 'diamond prop conflict'768 );769 }...
EventDispatcherTests.js
Source:EventDispatcherTests.js
...38 "Assert dispatcher target is set to the target passed in during instantiation");39 }40};41annotate(eventDispatcherInstantiationTest).with(42 test().name("EventDispatcher instantiation test")43);44/**45 * This tests46 * 1) Adding and event listener47 * 2) Dispatching a simple event48 */49var eventDispatcherSimpleAddEventListenerDispatchEventTest = {50 // Setup Test51 //-------------------------------------------------------------------------------52 setup: function() {53 this.eventDispatcher = new EventDispatcher();54 this.testEventType = "testEventType";55 this.testEventData = "testEventData";56 this.testEvent = new Event(this.testEventType, this.testEventData);57 this.calledVar = false;58 this.testContextVar = "some value";59 this.testListenerContext = {60 testContextVar: this.testContextVar61 };62 },63 // Run Test64 //-------------------------------------------------------------------------------65 test: function(test) {66 var _this = this;67 this.testListenerFunction = function(event) {68 _this.calledVar = true;69 test.assertEqual(this.testContextVar, _this.testContextVar,70 "Assert the listener function was called in the listener context");71 test.assertEqual(event.getType(), _this.testEventType,72 "Assert event type received was the event type published");73 test.assertEqual(event.getData(), _this.testEventData,74 "Assert event data received was the event data published");75 test.assertEqual(event.getTarget(), _this.eventDispatcher,76 "Assert event target is the dispatcher that dispatched the event");77 };78 this.eventDispatcher.addEventListener(this.testEventType, this.testListenerFunction, this.testListenerContext);79 this.eventDispatcher.dispatchEvent(this.testEvent);80 test.assertTrue(this.calledVar, "Assert listener function was called.");81 }82};83annotate(eventDispatcherSimpleAddEventListenerDispatchEventTest).with(84 test().name("EventDispatcher simple add event listener and dispatch event test")85);86/**87 * This tests88 * 1) Adding an anonymous event listener89 * 2) Dispatching a simple event with anonymous listeners90 */91var eventDispatcherAddAnonymousEventListenerDispatchEventTest = {92 // Setup Test93 //-------------------------------------------------------------------------------94 setup: function() {95 this.eventDispatcher = new EventDispatcher();96 this.testEventType = "testEventType";97 this.testEventData = "testEventData";98 this.testEvent = new Event(this.testEventType, this.testEventData);99 this.calledVar = false;100 },101 // Run Test102 //-------------------------------------------------------------------------------103 test: function(test) {104 var _this = this;105 this.testListenerFunction = function(event) {106 _this.calledVar = true;107 test.assertEqual(event.getType(), _this.testEventType,108 "Assert event type received was the event type published");109 test.assertEqual(event.getData(), _this.testEventData,110 "Assert event data received was the event data published");111 test.assertEqual(event.getTarget(), _this.eventDispatcher,112 "Assert event target is the dispatcher that dispatched the event");113 };114 this.eventDispatcher.addEventListener(this.testEventType, this.testListenerFunction);115 this.eventDispatcher.dispatchEvent(this.testEvent);116 test.assertTrue(this.calledVar, "Assert listener function was called.");117 }118};119annotate(eventDispatcherAddAnonymousEventListenerDispatchEventTest).with(120 test().name("EventDispatcher add anonymous event listener and dispatch event test")121);122/**123 * This tests124 * 1) That an event does not bubble when bubbles is false on dispatchEvent125 */126var eventDispatcherDispatchEventBubblesFalseTest = {127 // Setup Test128 //-------------------------------------------------------------------------------129 setup: function() {130 this.testChildEventDispatcher = new EventDispatcher();131 this.testParentEventDispatcher = new EventDispatcher();132 this.testEventType = "testEventType";133 this.testEventData = "testEventData";134 this.testEvent = new Event(this.testEventType, this.testEventData);135 this.testBubbles = false;136 this.childCalledVar = false;137 var _this = this;138 this.testChildListenerFunction = function(event) {139 _this.childCalledVar = true;140 };141 this.parentCalledVar = false;142 this.testParentListenerFunction = function(event) {143 _this.parentCalledVar = true;144 };145 },146 // Run Test147 //-------------------------------------------------------------------------------148 test: function(test) {149 this.testChildEventDispatcher.setParentDispatcher(this.testParentEventDispatcher);150 this.testChildEventDispatcher.addEventListener(this.testEventType, this.testChildListenerFunction);151 this.testParentEventDispatcher.addEventListener(this.testEventType, this.testParentListenerFunction);152 this.testChildEventDispatcher.dispatchEvent(this.testEvent, this.testBubbles);153 test.assertTrue(this.childCalledVar,154 "Assert listener function on child dispatcher was called when bubbles is false.");155 test.assertFalse(this.parentCalledVar,156 "Assert listener function on parent dispatcher was not called when bubbles is false.");157 }158};159annotate(eventDispatcherDispatchEventBubblesFalseTest).with(160 test().name("EventDispatcher dispatch event with bubbles false test")161);162/**163 * This tests164 * 1) That an event does bubble when bubbles is true on dispatchEvent165 */166var eventDispatcherDispatchEventBubblesTrueTest = {167 // Setup Test168 //-------------------------------------------------------------------------------169 setup: function() {170 var _this = this;171 this.testChildEventDispatcher = new EventDispatcher();172 this.testParentEventDispatcher = new EventDispatcher();173 this.testEventType = "testEventType";174 this.testEventData = "testEventData";175 this.testEvent = new Event(this.testEventType, this.testEventData);176 this.testBubbles = true;177 this.childCalledVar = false;178 this.testChildListenerFunction = function(event) {179 _this.childCalledVar = true;180 };181 this.parentCalledVar = false;182 this.testParentListenerFunction = function(event) {183 _this.parentCalledVar = true;184 };185 },186 // Run Test187 //-------------------------------------------------------------------------------188 test: function(test) {189 this.testChildEventDispatcher.setParentDispatcher(this.testParentEventDispatcher);190 this.testChildEventDispatcher.addEventListener(this.testEventType, this.testChildListenerFunction);191 this.testParentEventDispatcher.addEventListener(this.testEventType, this.testParentListenerFunction);192 this.testChildEventDispatcher.dispatchEvent(this.testEvent, this.testBubbles);193 test.assertTrue(this.childCalledVar,194 "Assert listener function on child dispatcher was called when bubbles is true.");195 test.assertTrue(this.parentCalledVar,196 "Assert listener function on parent dispatcher was called when bubbles is true.");197 }198};199annotate(eventDispatcherDispatchEventBubblesTrueTest).with(200 test().name("EventDispatcher dispatch event with bubbles true test")201);202/**203 * This tests204 * 1) That an event does not bubble on dispatchEvent when stopPropagation is called205 */206var eventDispatcherDispatchEventStopPropagationTest = {207 // Setup Test208 //-------------------------------------------------------------------------------209 setup: function() {210 var _this = this;211 this.testChildEventDispatcher = new EventDispatcher();212 this.testParentEventDispatcher = new EventDispatcher();213 this.testEventType = "testEventType";214 this.testEventData = "testEventData";215 this.testEvent = new Event(this.testEventType, this.testEventData);216 this.testBubbles = true;217 this.childCalledVar = false;218 this.testChildListenerFunction = function(event) {219 _this.childCalledVar = true;220 event.stopPropagation();221 };222 this.parentCalledVar = false;223 this.testParentListenerFunction = function(event) {224 _this.parentCalledVar = true;225 };226 },227 // Run Test228 //-------------------------------------------------------------------------------229 test: function(test) {230 this.testChildEventDispatcher.setParentDispatcher(this.testParentEventDispatcher);231 this.testChildEventDispatcher.addEventListener(this.testEventType, this.testChildListenerFunction);232 this.testParentEventDispatcher.addEventListener(this.testEventType, this.testParentListenerFunction);233 this.testChildEventDispatcher.dispatchEvent(this.testEvent, this.testBubbles);234 test.assertTrue(this.childCalledVar,235 "Assert listener function on child dispatcher was called");236 test.assertFalse(this.parentCalledVar,237 "Assert listener function on parent dispatcher was not called when stopPropagation was called on a child " +238 "EventDispatcher");239 }240};241annotate(eventDispatcherDispatchEventStopPropagationTest).with(242 test().name("EventDispatcher dispatch event stopPropagation test")243);244/**245 * This tests246 * 1) Adding an event listener247 * 2) That hasEventListener returns true after adding an event listener248 * 3) Removing the event listener249 * 4) That hasEventListener returns false after removing the event listener250 */251var eventDispatcherSimpleAddAndRemoveEventListenerTest = {252 // Setup Test253 //-------------------------------------------------------------------------------254 setup: function() {255 this.eventDispatcher = new EventDispatcher();256 this.testEventType = "testEventType";257 this.testListenerContext = {};258 this.testListenerFunction = function(event) {};259 },260 // Run Test261 //-------------------------------------------------------------------------------262 test: function(test) {263 this.eventDispatcher.addEventListener(this.testEventType, this.testListenerFunction, this.testListenerContext);264 var hasListenerAfterAdd = this.eventDispatcher.hasEventListener(this.testEventType, this.testListenerFunction,265 this.testListenerContext);266 test.assertTrue(hasListenerAfterAdd,267 "Assert hasEventListener returns true after adding an event listener.");268 this.eventDispatcher.removeEventListener(this.testEventType, this.testListenerFunction,269 this.testListenerContext);270 var hasListenerAfterRemove = this.eventDispatcher.hasEventListener(this.testEventType,271 this.testListenerFunction, this.testListenerContext);272 test.assertFalse(hasListenerAfterRemove,273 "Assert hasEventListener returns false after removing the event listener.");274 }275};276annotate(eventDispatcherSimpleAddAndRemoveEventListenerTest).with(277 test().name("EventDispatcher simple add and remove event listener test")...
SVGMarkerTests.js
Source:SVGMarkerTests.js
1//mocks2/**3 * Init package4 */5if(!ORYX) {var ORYX = {};}6if(!ORYX.Core) {ORYX.Core = {};}7if(!ORYX.Core.SVG) {ORYX.Core.SVG = {};}89// mocking ORYX.Editor object10if(!ORYX) {var ORYX = {};}11if(!ORYX.Editor) {ORYX.Editor = {};}1213//stubs1415// stubbing ORYX.Editor.checkClassType16ORYX.Editor.checkClassType = function( classInst, classType ) {17 return classInst instanceof classType18}1920//tests2122function setUp() {23 // set oryx namespace24 NAMESPACE_ORYX_TEST = "http://www.b3mn.org/oryx";25 testChild1 = document.createElementNS('http://www.w3.org/2000/svg', 'svg' )26 testChild2 = document.createElementNS('http://www.w3.org/2000/svg', 'rect' )27 testChildChild1 = document.createElementNS('http://www.w3.org/2000/svg', 'path' )28 testSVGMarkerElement = document.createElementNS('http://www.w3.org/2000/svg', 'marker')29}3031/**32 * Tests if an exception is thrown if no valid SVGMarkerElement is passed to the constructor.33 */34function testFailForAnInvalidSVGMarkerElement() {35 try {36 testSVGMarker = new ORYX.Core.SVG.SVGMarker(5);37 fail("SVGMarker test should fail yet.")38 } catch (e) {39 if ((e instanceof JsUnitException)) {40 throw e;41 }42 }43}4445/**46 * Creates a SVGMarker instance, from an empty SVGMarkerElement.47 */48function testCreateSVGMarkerFromDOMElement() {49 try {50 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);51 fail(" ")52 } catch (e) {53 if (!(e instanceof JsUnitException)) {54 throw e;55 }56 }57}5859/**60 * No further attributes specified. So check if default values are set.61 */62function testDefaultValues() {63 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);64 assertNotNaN("Is oldRefX a Number?",Number(testSVGMarker.oldRefX))65 assertNotNaN("Is oldRefY a Number?",Number(testSVGMarker.oldRefY))66 assertNotNaN("Is oldMarkerWidth a Number?",Number(testSVGMarker.oldMarkerWidth))67 assertNotNaN("Is oldMarkerHeight a Number?",Number(testSVGMarker.oldMarkerHeight))68 assertFalse("Not optional",testSVGMarker.optional)69 assertTrue("Enabled",testSVGMarker.enabled)70 assertFalse("Should not be resizable",testSVGMarker.resize)71}7273/**74 * Test parsing of id attribute75 */76function testIDValue() {77 testSVGMarkerElement.setAttributeNS(null, "id", "myMarker")78 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);79 assertEquals("ID value should be 'myMarker'", testSVGMarker.id, "myMarker")80}8182/**83 * Test parsing of refX attribute84 */85function testRefXValue() {86 testSVGMarkerElement.setAttributeNS(null, "refX", 89.45)87 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);88 assertEquals("Checks RefX value.", testSVGMarker.refX, 89.45)89 assertEquals("Checks oldRefX value.", testSVGMarker.oldRefX, 89.45)90}9192/**93 * Test parsing of refX as String attribute94 */95function testRefXStringValue() {96 testSVGMarkerElement.setAttributeNS(null, "refX", "89.45")97 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);98 assertEquals("Checks RefX value.", testSVGMarker.refX, 89.45)99 assertEquals("Checks oldRefX value.", testSVGMarker.oldRefX, 89.45)100}101102/**103 * If RefX is not a number, it should throw an Exception.104 */105function testFailForNaNRefXValue() {106 try {107 testSVGMarkerElement.setAttributeNS(null, "refX", "two")108 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);109 fail("Test should fail yet.")110 } catch (e) {111 if ((e instanceof JsUnitException)) {112 throw e;113 }114 }115}116117/**118 * Test parsing of refY attribute119 */120function testRefYValue() {121 testSVGMarkerElement.setAttributeNS(null, "refY", 89.45)122 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);123 assertEquals("Checks RefY value.", testSVGMarker.refY, 89.45)124 assertEquals("Checks oldRefX value.", testSVGMarker.oldRefY, 89.45)125}126127/**128 * Test parsing of refY as String attribute129 */130function testRefYStringValue() {131 testSVGMarkerElement.setAttributeNS(null, "refY", "89.45")132 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);133 assertEquals("Checks RefY value.", testSVGMarker.refY, 89.45)134 assertEquals("Checks oldRefY value.", testSVGMarker.oldRefY, 89.45)135}136137/**138 * If RefY is not a number, it should throw an Exception.139 */140function testFailForNaNRefYValue() {141 try {142 testSVGMarkerElement.setAttributeNS(null, "refY", "two")143 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);144 fail("Test should fail yet.")145 } catch (e) {146 if ((e instanceof JsUnitException)) {147 throw e;148 }149 }150}151152/**153 * Test parsing of markerWidth attribute154 */155function testMarkerWidthValue() {156 testSVGMarkerElement.setAttributeNS(null, "markerWidth", 4.45)157 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);158 assertEquals("Checks MarkerWidth value.", testSVGMarker.markerWidth, 4.45)159}160161/**162 * Test parsing of markerWidth as String attribute163 */164function testMarkerWidthStringValue() {165 testSVGMarkerElement.setAttributeNS(null, "markerWidth", "4.45")166 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);167 assertEquals("Checks markerWidth value.", testSVGMarker.markerWidth, 4.45)168}169170/**171 * If markerWidth is not a number, it should throw an Exception.172 */173function testFailForNaNMarkerWidthValue() {174 try {175 testSVGMarkerElement.setAttributeNS(null, "markerWidth", "two")176 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);177 fail("Test should fail yet.")178 } catch (e) {179 if ((e instanceof JsUnitException)) {180 throw e;181 }182 }183}184185/**186 * Test parsing of markerHeight attribute187 */188function testMarkerHeightValue() {189 testSVGMarkerElement.setAttributeNS(null, "markerHeight", 4.45)190 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);191 assertEquals("Checks MarkerHeight value.", testSVGMarker.markerHeight, 4.45)192}193194/**195 * Test parsing of markerHeight as String attribute196 */197function testMarkerHeightStringValue() {198 testSVGMarkerElement.setAttributeNS(null, "markerHeight", "4.45")199 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);200 assertEquals("Checks markerHeight value.", testSVGMarker.markerHeight, 4.45)201}202203/**204 * If markerHeight is not a number, it should throw an Exception.205 */206function testFailForNaNMarkerHeightValue() {207 try {208 testSVGMarkerElement.setAttributeNS(null, "markerHeight", "two")209 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);210 fail("Test should fail yet.")211 } catch (e) {212 if ((e instanceof JsUnitException)) {213 throw e;214 }215 }216}217218/**219 * Test parsing of oryx:optional attribute220 */221function testMarkerOryxOptionalValue() {222 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "optional", "yes")223 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);224 assertTrue("Checks oryx:optional value.", testSVGMarker.optional)225}226227/**228 * Test parsing of oryx:optional with a "no" value229 */230function testMarkerOryxOptionalNoValue() {231 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "optional", "")232 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);233 assertFalse("Checks oryx:optional value.", testSVGMarker.optional)234}235236/**237 * Test parsing of oryx:enabled attribute238 */239function testMarkerOryxEnabledValue() {240 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "enabled", "yes")241 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);242 assertTrue("Checks oryx:enabled value.", testSVGMarker.enabled)243}244245/**246 * Test parsing of oryx:optional with a "no" value247 */248function testMarkerOryxEnabledNoValue() {249 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "enabled", "nO")250 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);251 assertFalse("Checks oryx:enabled value.", testSVGMarker.optional)252}253254/**255 * Test parsing of oryx:resize attribute256 */257function testMarkerOryxResizeValue() {258 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "resize", "yes")259 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);260 assertTrue("Checks oryx:resize value.", testSVGMarker.resize)261}262263/**264 * Test parsing of oryx:resize with a "no" value265 */266function testMarkerOryxOptionalNoValue() {267 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "resize", "")268 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);269 assertFalse("Checks oryx:resize value.", testSVGMarker.resize)270}271272/**273 * Test parsing of oryx:minimumLength attribute as string274 */275function testMarkerOryxMinimumLengthAsStringValue() {276 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "minimumLength", "51.8")277 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);278 assertEquals("Checks oryx:minimumLength value.", testSVGMarker.minimumLength, 51.8)279}280281/**282 * Test parsing of oryx:minimumLength attribute283 */284function testMarkerOryxMinimumLengthValue() {285 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "minimumLength", 51.8)286 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);287 assertEquals("Checks oryx:minimumLength value.", testSVGMarker.minimumLength, 51.8)288}289290/**291 * If oryx:minimumLength is not a number, it should throw an Exception.292 */293function testFailForNaNMarkerOryxMinimumLengthtValue() {294 try {295 testSVGMarkerElement.setAttributeNS(NAMESPACE_ORYX_TEST, "minimumLength", "two")296 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);297 fail("Test should fail yet.")298 } catch (e) {299 if ((e instanceof JsUnitException)) {300 throw e;301 }302 }303}304305// test _getSVGShape method306307/**308 * 309 */310function testReturnEmptyArrayForNonNestedElement() {311 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);312 assertEquals("_getSVGShape() without child nodes should return an empty array.", testSVGMarker._getSVGShapes(testSVGMarkerElement), [])313}314315/**316 * There are two rectagle shape added to the SVGMarker. So you should retrieve two ORYX.Core.SVG.SVGShape 317 * instances from the _getSVGShapes method318 */319function testGetSVGShapes() {320 testSVGRectElement1 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');321 testSVGRectElement1.setAttributeNS(null, "x", 2);322 testSVGRectElement1.setAttributeNS(null, "y", 2);323 testSVGRectElement1.setAttributeNS(null, "height", 3);324 testSVGRectElement1.setAttributeNS(null, "width", 4);325 326 testSVGRectElement2 = document.createElementNS('http://www.w3.org/2000/svg', 'rect');327 testSVGRectElement2.setAttributeNS(null, "x", 2);328 testSVGRectElement2.setAttributeNS(null, "y", 2);329 testSVGRectElement2.setAttributeNS(null, "height", 5);330 testSVGRectElement2.setAttributeNS(null, "width", 4);331 332 testSVGMarkerElement.appendChild(testSVGRectElement1)333 testSVGMarkerElement.appendChild(testSVGRectElement2)334 335 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);336 var childShapes = testSVGMarker._getSVGShapes(testSVGMarkerElement)337 338 assertTrue("SVGShape instance in array", childShapes[0] instanceof ORYX.Core.SVG.SVGShape)339 assertTrue("SVGShape instance in array", childShapes[1] instanceof ORYX.Core.SVG.SVGShape)340}341342/**343 * Test the update method344 */345function testUpdate() {346 testSVGMarker = new ORYX.Core.SVG.SVGMarker(testSVGMarkerElement);347 testSVGMarker.refX = 66348 testSVGMarker.refY = 88349 testSVGMarker.markerWidth = 9350 testSVGMarker.markerHeight = 22351 testSVGMarker.update();352 353 assertEquals("Check oldRefX value", testSVGMarker.oldRefX, 66 ) 354 assertEquals("Check oldRefY value", testSVGMarker.oldRefY, 88 )355 assertEquals("Check oldMarkerWidth value", testSVGMarker.oldMarkerWidth, 9 )356 assertEquals("Check oldMarkerHeight value", testSVGMarker.oldMarkerHeight, 22)
...
tests.js
Source:tests.js
1var EntryPool = require('../pool.js');2exports.poolGetEmpty = function(test) {3 var pool = new EntryPool(0, 1);4 test.strictEqual(pool.size, 0);5 test.throws(function() {6 pool.get();7 });8 test.done();9};10exports.poolGetEmptyStep = function(test) {11 var pool = new EntryPool(0, 1, 1);12 test.strictEqual(pool.size, 0);13 test.notStrictEqual(pool.get(), undefined);14 test.strictEqual(pool.size, 1);15 test.strictEqual(pool.size, pool.pool.length);16 test.done();17};18exports.poolAddGet = function(test) {19 var pool = new EntryPool(0, 1);20 test.strictEqual(pool.size, 0);21 pool.add(1);22 test.strictEqual(pool.size, 1);23 test.strictEqual(pool.size, pool.pool.length);24 test.notStrictEqual(pool.get(), undefined);25 test.done();26};27exports.poolGetNoneLeft = function(test) {28 var pool = new EntryPool(1, 1);29 test.notStrictEqual(pool.get(), undefined);30 test.strictEqual(pool.size, 1);31 test.notStrictEqual(pool.get(), undefined);32 test.strictEqual(pool.size, 2);33 test.strictEqual(pool.size, pool.pool.length);34 test.done();35};36exports.poolGetNoneLeftCustomStep = function(test) {37 var pool = new EntryPool(1, 1, 3);38 test.notStrictEqual(pool.get(), undefined);39 test.strictEqual(pool.size, 1);40 test.notStrictEqual(pool.get(), undefined);41 //since we didn't put the original one back the size should be only 3 (step size)42 test.strictEqual(pool.size, 4);43 test.strictEqual(pool.size, pool.pool.length);44 test.done();45};46exports.poolPutGet = function(test) {47 var pool = new EntryPool(1, 1),48 arr = pool.get();49 pool.put(arr);50 test.strictEqual(pool.get(), arr);51 test.strictEqual(pool.size, 1);52 test.done();53};54exports.arrAdd = function(test) {55 var pool = new EntryPool(1, 2),56 arr = pool.get();57 test.strictEqual(arr.add(1), 0);58 test.strictEqual(arr.add(2), 1);59 test.strictEqual(arr.at(0), 1);60 test.strictEqual(arr.at(1), 2);61 test.done();62};63exports.arrAddValue = function(test) {64 var pool = new EntryPool(1, 2),65 arr = pool.get();66 test.strictEqual(arr.add(1, 1), 0);67 test.strictEqual(arr.add(2, 2), 1);68 test.strictEqual(arr.at(0), 1);69 test.strictEqual(arr.at(1), 2);70 test.done();71};72exports.arrAddUndefined = function(test) {73 var pool = new EntryPool(1, 2),74 arr = pool.get();75 test.throws(function() {76 EntryPool.addEntry(arr, undefined);77 });78 test.throws(function() {79 arr.add(undefined);80 });81 test.done();82};83exports.arrRemove = function(test) {84 var pool = new EntryPool(1, 1),85 arr = pool.get();86 EntryPool.addEntry(arr, 1);87 test.strictEqual(arr.remove(2), false);88 test.strictEqual(arr.remove(1), true);89 test.strictEqual(arr.numEntries(arr), 0);90 test.strictEqual(arr.remove(undefined), true);91 test.done();92};93exports.arrRemoveValues = function(test) {94 var pool = new EntryPool(1, 3),95 arr = pool.get();96 arr.add(999, 1);97 arr.add(2, 8);98 arr.add(3, 9);99 test.strictEqual(arr.remove(5), false); //matches nothing100 test.strictEqual(arr.numEntries(), 3);101 test.strictEqual(arr.remove(1), false); //matches nothing unless mismatch value/timestamp102 test.strictEqual(arr.numEntries(), 3);103 test.strictEqual(arr.remove(undefined, 1), false); //matches on value104 test.strictEqual(arr.numEntries(), 2);105 test.strictEqual(arr.remove(2), false); //matches on timestamp106 test.strictEqual(arr.numEntries(), 1);107 test.strictEqual(arr.remove(3, 3), false); //matches nothing unless value ignored108 test.strictEqual(arr.numEntries(), 1);109 test.strictEqual(arr.remove(3, 9), true); //matches on value and timestamp110 test.strictEqual(arr.numEntries(), 0);111 test.done();112};113exports.arrRemoveShifts = function(test) {114 var pool = new EntryPool(1, 3),115 arr = pool.get();116 arr.add(1);117 arr.add(2);118 arr.add(3);119 arr.remove(1);120 test.strictEqual(arr.numEntries(), 2);121 test.strictEqual(arr.at(0), 2);122 test.strictEqual(arr.at(1), 3);123 test.strictEqual(arr.at(2), undefined);124 test.done();125};126exports.arrAddOverLimit = function(test) {127 var pool = new EntryPool(1, 1),128 arr = pool.get();129 arr.add(arr, 1);130 test.strictEqual(arr.add(2), -1);131 test.strictEqual(arr.at(0), 1);132 test.strictEqual(arr.at(1), undefined);133 test.done();134};135exports.arrNumEntries = function(test) {136 var pool = new EntryPool(1, 1),137 arr = pool.get();138 arr.add(1);139 test.strictEqual(arr.numEntries(), 1);140 test.done();141};142exports.arrCleanup = function(test) {143 var pool = new EntryPool(1, 3),144 arr = pool.get();145 arr.add(1);146 arr.add(2);147 arr.add(3);148 test.strictEqual(arr.cleanup(3), 1);149 test.strictEqual(arr.numEntries(), 1);150 test.strictEqual(arr.at(0), 3);151 test.strictEqual(arr.at(1), undefined);152 test.strictEqual(arr.at(2), undefined);153 test.strictEqual(arr.cleanup(4), 0);154 test.strictEqual(arr.numEntries(), 0);155 test.strictEqual(arr.at(0), undefined);156 test.done();157};158exports.arrCleanupUndefined = function(test) {159 var pool = new EntryPool(1, 1),160 arr = pool.get();161 arr.add(1);162 test.strictEqual(arr.cleanup(undefined), 0);163 test.strictEqual(arr.numEntries(), 0);164 test.done();165};166exports.poolPutEmpties = function(test) {167 var pool = new EntryPool(1, 1),168 arr = pool.get();169 arr.add(1);170 pool.put(arr);171 test.strictEqual(arr.numEntries(), 0);172 test.done();173};174exports.poolPutEmpties = function(test) {175 var pool = new EntryPool(1, 1),176 arr = pool.get();177 arr.add(1);178 pool.put(arr);179 test.strictEqual(arr.numEntries(), 0);180 test.done();181};182exports.poolPutInvalid = function(test) {183 var pool = new EntryPool(0, 1);184 test.throws(function() {185 pool.put('test');186 });187 test.done();188};189exports.poolPutInvalidSize = function(test) {190 var pool = new EntryPool(0, 1);191 test.throws(function() {192 pool.put(new Array(3));193 });194 test.done();195};196exports.poolPutArrayThrows = function(test) {197 var pool = new EntryPool(0, 1);198 test.throws(function() {199 pool.put(new Array(1));200 });201 test.strictEqual(pool.size, 0);202 test.done();203};204exports.poolPutPastEnd = function(test) {205 var pool = new EntryPool(0, 1),206 pool2 = new EntryPool(1, 1);207 pool.put(pool2.get());208 test.strictEqual(pool.size, 1);209 test.done();210};211exports.poolTrimAll = function(test) {212 var pool = new EntryPool(5, 1),213 arr = pool.get();214 pool.trim();215 test.strictEqual(pool.size, 1);216 test.strictEqual(pool.size, pool.pool.length);217 pool.put(arr);218 test.strictEqual(pool.size, 1);219 test.done();220};221exports.poolTrimAllButOne = function(test) {222 var pool = new EntryPool(5, 1),223 arr = pool.get();224 pool.trim(1);225 test.strictEqual(pool.size, 1);226 test.strictEqual(pool.size, pool.pool.length);227 pool.put(arr);228 test.strictEqual(pool.size, 1);229 test.done();230};231exports.poolTrimSome = function(test) {232 var pool = new EntryPool(5, 1),233 arr = pool.get();234 pool.trim(3);235 test.strictEqual(pool.size, 3);236 test.strictEqual(pool.size, pool.pool.length);237 pool.put(arr);238 test.strictEqual(pool.size, 3);239 test.done();240};241exports.poolTrimNone = function(test) {242 var pool = new EntryPool(1, 1);243 pool.trim(3);244 test.strictEqual(pool.size, 1);245 test.strictEqual(pool.size, pool.pool.length);246 test.done();247};248exports.poolTrimNoneAvailable = function(test) {249 var pool = new EntryPool(4, 1),250 arr1 = pool.get(),251 arr2 = pool.get();252 pool.get();253 pool.get();254 pool.trim();255 test.strictEqual(pool.size, 4);256 test.strictEqual(pool.size, pool.pool.length);257 //now put 2 back and try trimming again258 pool.put(arr1);259 pool.put(arr2);260 pool.trim();261 test.strictEqual(pool.size, 2);262 test.strictEqual(pool.size, pool.pool.length);263 test.done();264};265exports.poolTrimDoesntChangeOrder = function(test) {266 var pool = new EntryPool(3, 1),267 arr1 = pool.get(),268 arr2 = pool.get();269 pool.get();270 pool.trim();271 //now put 2 back and try trimming again272 pool.put(arr1);273 pool.put(arr2);274 pool.trim(2);275 test.strictEqual(pool.size, 2);276 test.strictEqual(pool.size, pool.pool.length);277 test.strictEqual(pool.get(), arr1);278 test.done();...
_getDataFunctions.js
Source:_getDataFunctions.js
1// DATA_TEMPLATE: dom_data2oTest.fnStart( "Check behaviour of the data get functions that DataTables uses" );3$(document).ready( function () {4 // Slightly unusual test set this one, in that we don't really care about the DOM5 // but want to test the internal data handling functions but we do need a table to6 // get at the functions!7 var table = $('#example').dataTable();8 var fn, test;9 10 // Object property access11 oTest.fnTest(12 "Single object, single property",13 function () {14 fn = table.oApi._fnGetObjectDataFn('test');15 test = fn( { "test": true } );16 },17 function () { return test }18 );19 20 oTest.fnTest(21 "Single property from object",22 function () {23 fn = table.oApi._fnGetObjectDataFn('test');24 test = fn( { "test": true, "test2": false } );25 },26 function () { return test }27 );28 29 oTest.fnTest(30 "Single property from object - different property",31 function () {32 fn = table.oApi._fnGetObjectDataFn('test2');33 test = fn( { "test": true, "test2": false } );34 },35 function () { return test===false }36 );37 38 oTest.fnTest(39 "Undefined property from object",40 function () {41 fn = table.oApi._fnGetObjectDataFn('test3');42 test = fn( { "test": true, "test2": false } );43 },44 function () { return test===undefined }45 );46 47 // Array index access48 oTest.fnTest(49 "Array access - index 0",50 function () {51 fn = table.oApi._fnGetObjectDataFn(0);52 test = fn( [true, false, false, false] );53 },54 function () { return test }55 );56 57 oTest.fnTest(58 "Array access - index 1",59 function () {60 fn = table.oApi._fnGetObjectDataFn(2);61 test = fn( [false, false, true, false] );62 },63 function () { return test }64 );65 66 oTest.fnTest(67 "Array access - undefined",68 function () {69 fn = table.oApi._fnGetObjectDataFn(7);70 test = fn( [false, false, true, false] );71 },72 function () { return test===undefined }73 );74 // null source75 oTest.fnTest(76 "null source",77 function () {78 fn = table.oApi._fnGetObjectDataFn( null );79 test = fn( [false, false, true, false] );80 },81 function () { return test===null }82 );83 // nested objects84 oTest.fnTest(85 "Nested object property",86 function () {87 fn = table.oApi._fnGetObjectDataFn( 'a.b' );88 test = fn( {89 "a":{90 "b": true,91 "c": false,92 "d": 193 }94 } );95 },96 function () { return test }97 );98 oTest.fnTest(99 "Nested object property - different prop",100 function () {101 fn = table.oApi._fnGetObjectDataFn( 'a.d' );102 test = fn( {103 "a":{104 "b": true,105 "c": false,106 "d": 1107 }108 } );109 },110 function () { return test===1 }111 );112 113 oTest.fnTest(114 "Nested object property - undefined prop",115 function () {116 fn = table.oApi._fnGetObjectDataFn( 'a.z' );117 test = fn( {118 "a":{119 "b": true,120 "c": false,121 "d": 1122 }123 } );124 },125 function () { return test===undefined }126 );127 // Nested array128 oTest.fnTest(129 "Nested array index property",130 function () {131 fn = table.oApi._fnGetObjectDataFn( 'a.0' );132 test = fn( {133 "a": [134 true,135 false,136 1137 ]138 } );139 },140 function () { return test }141 );142 oTest.fnTest(143 "Nested array index property - different index",144 function () {145 fn = table.oApi._fnGetObjectDataFn( 'a.2' );146 test = fn( {147 "a": [148 true,149 false,150 1151 ]152 } );153 },154 function () { return test===1 }155 );156 oTest.fnTest(157 "Nested array index property - undefined index",158 function () {159 fn = table.oApi._fnGetObjectDataFn( 'a.10' );160 test = fn( {161 "a": [162 true,163 false,164 1165 ]166 } );167 },168 function () { return test===undefined }169 );170 // Nested array object property171 oTest.fnTest(172 "Nested array index object property",173 function () {174 fn = table.oApi._fnGetObjectDataFn( 'a.0.m' );175 test = fn( {176 "a": [177 { "m": true, "n": 1 },178 { "m": false, "n": 2 },179 { "m": false, "n": 3 }180 ]181 } );182 },183 function () { return test }184 );185 oTest.fnTest(186 "Nested array index object property - different index",187 function () {188 fn = table.oApi._fnGetObjectDataFn( 'a.2.n' );189 test = fn( {190 "a": [191 { "m": true, "n": 1 },192 { "m": false, "n": 2 },193 { "m": false, "n": 3 }194 ]195 } );196 },197 function () { return test===3 }198 );199 oTest.fnTest(200 "Nested array index object property - undefined index",201 function () {202 fn = table.oApi._fnGetObjectDataFn( 'a.0.z' );203 test = fn( {204 "a": [205 { "m": true, "n": 1 },206 { "m": false, "n": 2 },207 { "m": false, "n": 3 }208 ]209 } );210 },211 function () { return test===undefined }212 );213 // Array notation - no join214 oTest.fnTest(215 "Array notation - no join - property",216 function () {217 fn = table.oApi._fnGetObjectDataFn( 'a[].n' );218 test = fn( {219 "a": [220 { "m": true, "n": 1 },221 { "m": false, "n": 2 },222 { "m": false, "n": 3 }223 ]224 } );225 },226 function () {227 return test.length===3 && test[0]===1228 && test[1]===2 && test[2]===3;229 }230 );231 oTest.fnTest(232 "Array notation - no join - property (2)",233 function () {234 fn = table.oApi._fnGetObjectDataFn( 'a[].m' );235 test = fn( {236 "a": [237 { "m": true, "n": 1 },238 { "m": false, "n": 2 }239 ]240 } );241 },242 function () {243 return test.length===2 && test[0]===true244 && test[1]===false;245 }246 );247 oTest.fnTest(248 "Array notation - no join - undefined property",249 function () {250 fn = table.oApi._fnGetObjectDataFn( 'a[].z' );251 test = fn( {252 "a": [253 { "m": true, "n": 1 },254 { "m": false, "n": 2 }255 ]256 } );257 },258 function () {259 return test.length===2 && test[0]===undefined260 && test[1]===undefined;261 }262 );263 // Array notation - join264 oTest.fnTest(265 "Array notation - space join - property",266 function () {267 fn = table.oApi._fnGetObjectDataFn( 'a[ ].n' );268 test = fn( {269 "a": [270 { "m": true, "n": 1 },271 { "m": false, "n": 2 },272 { "m": false, "n": 3 }273 ]274 } );275 },276 function () { return test === '1 2 3'; }277 );278 oTest.fnTest(279 "Array notation - space join - property (2)",280 function () {281 fn = table.oApi._fnGetObjectDataFn( 'a[ ].m' );282 test = fn( {283 "a": [284 { "m": true, "n": 1 },285 { "m": false, "n": 2 }286 ]287 } );288 },289 function () { return test === 'true false'; }290 );291 oTest.fnTest(292 "Array notation - sapce join - undefined property",293 function () {294 fn = table.oApi._fnGetObjectDataFn( 'a[ ].z' );295 test = fn( {296 "a": [297 { "m": true, "n": 1 },298 { "m": false, "n": 2 }299 ]300 } );301 },302 function () { return test === ' '; }303 );304 oTest.fnTest(305 "Array notation - string join - property",306 function () {307 fn = table.oApi._fnGetObjectDataFn( 'a[qwerty].n' );308 test = fn( {309 "a": [310 { "m": true, "n": 1 },311 { "m": false, "n": 2 },312 { "m": false, "n": 3 }313 ]314 } );315 },316 function () { return test === '1qwerty2qwerty3'; }317 );318 oTest.fnTest(319 "Array notation - string join - property (2)",320 function () {321 fn = table.oApi._fnGetObjectDataFn( 'a[qwerty].m' );322 test = fn( {323 "a": [324 { "m": true, "n": 1 },325 { "m": false, "n": 2 }326 ]327 } );328 },329 function () { return test === 'trueqwertyfalse'; }330 );331 332 // Array alone join333 oTest.fnTest(334 "Flat array join",335 function () {336 fn = table.oApi._fnGetObjectDataFn( 'a[ ]' );337 test = fn( {338 "a": [339 true,340 false,341 1342 ]343 } );344 },345 function () { return test==="true false 1"; }346 );347 oTest.fnTest(348 "Flat array string join",349 function () {350 fn = table.oApi._fnGetObjectDataFn( 'a[qwerty]' );351 test = fn( {352 "a": [353 true,354 false,355 1356 ]357 } );358 },359 function () { return test==="trueqwertyfalseqwerty1"; }360 );361 oTest.fnTest(362 "Flat array no join",363 function () {364 fn = table.oApi._fnGetObjectDataFn( 'a[]' );365 test = fn( {366 "a": [367 true,368 false,369 1370 ]371 } );372 },373 function () { return test.length===3 && test[0]===true &&374 test[1]===false && test[2]===1; }375 );376 377 378 379 oTest.fnComplete();...
test-test-case.js
Source:test-test-case.js
...3var assert = require('assert');4var Sandbox = common.sandbox('test_case');5var TestCase = Sandbox.exports;6var testCase;7function test(fn) {8 testCase = new TestCase();9 fn();10}11test(function createFactory() {12 var testCase = TestCase.create(10);13 assert.strictEqual(testCase.testTimeout, 10);14});15test(function sugarAddTestFunction() {16 var sugarAddTest = testCase.sugarAddTest();17 Object18 .keys(TestCase.prototype)19 .concat(Object.keys(testCase))20 .forEach(function(property) {21 if (typeof testCase[property] !== 'function') {22 assert.strictEqual(sugarAddTest[property], testCase[property]);23 return;24 }25 var returns = 'the answer';26 var args = [1, 2, 3];27 testCase[property] = sinon.stub().returns(returns);28 var r = sugarAddTest[property].apply(null, args);29 assert.strictEqual(returns, r);30 assert.ok(testCase[property].calledOn(testCase));31 assert.ok(testCase[property].calledWith(1, 2, 3));32 assert.ok(testCase[property].callCount, 1);33 });34 var returns = 'another answer';35 var args = [1, 2];36 testCase.addTest = sinon.stub().returns(returns);37 var r = sugarAddTest.apply(null, args);38 assert.strictEqual(r, returns);39 assert.ok(testCase.addTest.calledOn(testCase));40 assert.ok(testCase.addTest.calledWith(1, 2));41 assert.ok(testCase.addTest.callCount, 1);42});43test(function addTestWithNameAndFn() {44 var testName = 'my test';45 var testFn = function() {};46 testCase.addTest(testName, testFn);47 assert.equal(testCase.tests.length, 1);48 assert.equal(testCase.tests[0].name, testName);49 assert.equal(testCase.tests[0].testFn, testFn);50 assert.equal(testCase.tests[0].timeout, null);51});52test(function addTestWithOptions() {53 var testName = 'my test';54 var testFn = function() {};55 var options = {foo: 'bar'};56 testCase.addTest(testName, options, testFn);57 assert.equal(testCase.tests[0].name, testName);58 assert.equal(testCase.tests[0].testFn, testFn);59 assert.equal(testCase.tests[0].foo, options.foo);60});61test(function addTestWithTestTimeout() {62 testCase.testTimeout = 20;63 var testName = 'my test';64 var testFn = function() {};65 testCase.addTest(testName, testFn);66 assert.equal(testCase.tests[0].timeout, 20);67});68test(function addTestWithTestTimeoutAndOptions() {69 testCase.testTimeout = 20;70 var testName = 'my test';71 var testFn = function() {};72 var testOptions = {};73 testCase.addTest(testName, testOptions, testFn);74 assert.equal(testCase.tests[0].timeout, 20);75});76test(function addTestWithTestTimeoutAndTimeoutOption() {77 testCase.testTimeout = 20;78 var testName = 'my test';79 var testFn = function() {};80 var testOptions = {timeout: 50};81 testCase.addTest(testName, testOptions, testFn);82 assert.equal(testCase.tests[0].timeout, 50);83});84test(function addTestCaseWithBeforeAndAfterFn() {85 var before = function() {};86 var after = function() {};87 testCase.before(before);88 testCase.after(after);89 var testName = 'my test';90 var testFn = function() {};91 testCase.addTest(testName, testFn);92 assert.strictEqual(testCase.tests[0].beforeFn, before);93 assert.strictEqual(testCase.tests[0].afterFn, after);94});95test(function runNoTestCases() {96 var runCb = sinon.spy();97 testCase.run(runCb);98 assert.ok(runCb.called);99 assert.ok(runCb.calledWith(null));100 assert.ok(testCase._started);101 assert.ok(testCase._ended);102});103test(function runOneSuccessTest() {104 var testInstance = {};105 testInstance.run = sinon.stub().yields(null);106 sinon.stub(testCase, 'selectedCount');107 testCase.tests.push(testInstance);108 var runCb = sinon.spy();109 testCase.run(runCb);110 assert.ok(runCb.calledWith(null));111});112test(function runOneErrorTest() {113 var err = new Error('something went wrong');114 var testInstance = {};115 testInstance.run = sinon.stub().yields(err);116 testCase.tests.push(testInstance);117 sinon.stub(testCase, 'selectedCount');118 var runCb = sinon.spy();119 testCase.run(runCb);120 assert.ok(runCb.calledWith([err]));121});122test(function runOneSuccessAndOneErrorTest() {123 var err = new Error('something went wrong');124 sinon.stub(testCase, 'selectedCount');125 var errorTest = {my: 'error test'};126 errorTest.run = sinon.stub().yields(err);127 testCase.tests.push(errorTest);128 var successTest = {my: 'success test'};129 successTest.run = sinon.stub().yields(null);130 testCase.tests.push(successTest);131 var emitTestEnd = sinon.spy();132 testCase.on('test.end', emitTestEnd);133 var runCb = sinon.spy();134 testCase.run(runCb);135 assert.ok(runCb.calledWith([err]));136 assert.ok(emitTestEnd.calledWith(errorTest));137 assert.ok(emitTestEnd.calledWith(successTest));138});139test(function runWithSelected() {140 testCase.tests = [141 {selected: sinon.stub().returns(false), run: sinon.stub().yields(null)},142 {selected: sinon.stub().returns(true), run: sinon.stub().yields(null)},143 ];144 var runCb = sinon.spy();145 testCase.run(runCb);146 assert.ok(runCb.calledWith(null));147 assert.equal(testCase.tests[0].run.called, false);148 assert.equal(testCase.tests[1].run.called, true);149 var stats = testCase.stats();150 assert.equal(stats.index, 2);151 assert.equal(stats.pass, 1);152 assert.equal(stats.skip, 1);153 assert.equal(stats.fail, 0);154 assert.equal(stats.total, 2);155});156test(function selectedCount() {157 testCase.tests = [158 {selected: sinon.stub().returns(false)},159 {selected: sinon.stub().returns(false)},160 ];161 assert.equal(testCase.selectedCount(), 0);162 testCase.tests.push({selected: sinon.stub().returns(true)});163 assert.equal(testCase.selectedCount(), 1);164});165test(function duration() {166 testCase._started = 20;167 testCase._ended = 30;168 assert.equal(testCase.duration(), 10);169});170test(function durationBeforeEnded() {171 testCase._started = +new Date;172 assert.ok(testCase.duration() >= 0);173 assert.ok(testCase.duration() < 10);174});175test(function statsNumbers() {176 testCase.tests = {length: 5};177 testCase.errors = {length: 3};178 testCase.index = 4;179 var stats = testCase.stats();180 assert.strictEqual(stats.pass, 1);181 assert.strictEqual(stats.fail, 3);182 assert.strictEqual(stats.index, testCase.index);183 assert.strictEqual(stats.total, 5);184});185test(function endWithoutCb() {186 testCase.end();187});188test(function endEmitsEvent() {189 var endCb = sinon.spy();190 testCase.on('end', endCb);191 testCase.end();192 assert.ok(endCb.called);...
read-blob-test-cases.js
Source:read-blob-test-cases.js
1var testCases = [2 "testReadingNonExistentFileBlob",3 "testReadingNonExistentFileBlob2",4 "testReadingEmptyFileBlob",5 "testReadingEmptyTextBlob",6 "testReadingEmptyFileAndTextBlob",7 "testReadingSingleFileBlob",8 "testReadingSingleTextBlob",9 "testReadingSingleTextBlobAsDataURL",10 "testReadingSingleTextBlobAsDataURL2",11 "testReadingSingleArrayBufferBlob",12 "testReadingSlicedFileBlob",13 "testReadingSlicedTextBlob",14 "testReadingSlicedArrayBufferBlob",15 "testReadingMultipleFileBlob",16 "testReadingMultipleTextBlob",17 "testReadingMultipleArrayBufferBlob",18 "testReadingHybridBlob",19 "testReadingSlicedHybridBlob",20 "testReadingTripleSlicedHybridBlob",21];22var testIndex = 0;23function runNextTest(testFiles)24{25 if (testIndex < testCases.length) {26 testIndex++;27 self[testCases[testIndex - 1]](testFiles);28 } else {29 log("DONE");30 }31}32function testReadingNonExistentFileBlob(testFiles)33{34 log("Test reading a blob containing non-existent file");35 var blob = buildBlob([testFiles['non-existent']]);36 readBlobAsBinaryString(testFiles, blob);37}38function testReadingNonExistentFileBlob2(testFiles)39{40 log("Test reading a blob containing existent and non-existent file");41 var blob = buildBlob([testFiles['file1'], testFiles['non-existent'], testFiles['empty-file']]);42 readBlobAsBinaryString(testFiles, blob);43}44function testReadingEmptyFileBlob(testFiles)45{46 log("Test reading a blob containing empty file");47 var blob = buildBlob([testFiles['empty-file']]);48 readBlobAsBinaryString(testFiles, blob);49}50function testReadingEmptyTextBlob(testFiles)51{52 log("Test reading a blob containing empty text");53 var blob = buildBlob(['']);54 readBlobAsBinaryString(testFiles, blob);55}56function testReadingEmptyFileAndTextBlob(testFiles)57{58 log("Test reading a blob containing empty files and empty texts");59 var blob = buildBlob(['', testFiles['empty-file'], '', testFiles['empty-file']]);60 readBlobAsBinaryString(testFiles, blob);61}62function testReadingSingleFileBlob(testFiles)63{64 log("Test reading a blob containing single file");65 var blob = buildBlob([testFiles['file1']]);66 readBlobAsBinaryString(testFiles, blob);67}68function testReadingSingleTextBlob(testFiles)69{70 log("Test reading a blob containing single text");71 var blob = buildBlob(['First']);72 readBlobAsBinaryString(testFiles, blob);73}74function testReadingSingleTextBlobAsDataURL(testFiles)75{76 log("Test reading a blob containing single text as data URL");77 var blob = buildBlob(['First']);78 readBlobAsDataURL(testFiles, blob);79}80function testReadingSingleTextBlobAsDataURL2(testFiles)81{82 log("Test reading a blob containing single text as data URL (optional content type provided)");83 var blob = buildBlob(['First'], 'type/foo');84 readBlobAsDataURL(testFiles, blob);85}86function testReadingSingleArrayBufferBlob(testFiles)87{88 log("Test reading a blob containing single ArrayBuffer");89 var array = new Uint8Array([0, 1, 2, 128, 129, 130, 253, 254, 255]);90 var blob = buildBlob([array.buffer]);91 readBlobAsBinaryString(testFiles, blob);92}93function testReadingSlicedFileBlob(testFiles)94{95 log("Test reading a blob containing sliced file");96 var blob = buildBlob([testFiles['file2'].webkitSlice(1, 6)]);97 readBlobAsBinaryString(testFiles, blob);98}99function testReadingSlicedTextBlob(testFiles)100{101 log("Test reading a blob containing sliced text");102 var blob = buildBlob(['First'])103 blob = blob.webkitSlice(1, 11);104 readBlobAsBinaryString(testFiles, blob);105}106function testReadingSlicedArrayBufferBlob(testFiles)107{108 log("Test reading a blob containing sliced ArrayBuffer");109 var array = new Uint8Array([0, 1, 2, 128, 129, 130, 253, 254, 255]);110 var blob = buildBlob([array.buffer])111 blob = blob.webkitSlice(1, 11);112 readBlobAsBinaryString(testFiles, blob);113}114function testReadingMultipleFileBlob(testFiles)115{116 log("Test reading a blob containing multiple files");117 var blob = buildBlob([testFiles['file1'], testFiles['file2'], testFiles['file3']]);118 readBlobAsBinaryString(testFiles, blob);119}120function testReadingMultipleTextBlob(testFiles)121{122 log("Test reading a blob containing multiple texts");123 var blob = buildBlob(['First', 'Second', 'Third']);124 readBlobAsBinaryString(testFiles, blob);125}126function testReadingMultipleArrayBufferBlob(testFiles)127{128 log("Test reading a blob containing multiple ArrayBuffer");129 var array1 = new Uint8Array([0, 1, 2]);130 var array2 = new Uint8Array([128, 129, 130]);131 var array3 = new Uint8Array([253, 254, 255]);132 var blob = buildBlob([array1.buffer, array2.buffer, array3.buffer]);133 readBlobAsBinaryString(testFiles, blob);134}135function testReadingHybridBlob(testFiles)136{137 log("Test reading a hybrid blob");138 var array = new Uint8Array([48, 49, 50]);139 var blob = buildBlob(['First', testFiles['file1'], 'Second', testFiles['file2'], testFiles['file3'], 'Third', array.buffer]);140 readBlobAsBinaryString(testFiles, blob);141}142function testReadingSlicedHybridBlob(testFiles)143{144 log("Test reading a sliced hybrid blob");145 var array = new Uint8Array([48, 49, 50]);146 var blob = buildBlob(['First', testFiles['file1'], 'Second', testFiles['file2'], testFiles['file3'], 'Third', array.buffer]);147 var blob = blob.webkitSlice(7, 19);148 readBlobAsBinaryString(testFiles, blob);149}150function testReadingTripleSlicedHybridBlob(testFiles)151{152 log("Test reading a triple-sliced hybrid blob");153 var builder = new WebKitBlobBuilder();154 var array = new Uint8Array([48, 49, 50]);155 var blob = buildBlob(['First', testFiles['file1'].webkitSlice(1, 11), testFiles['empty-file'], 'Second', testFiles['file2'], testFiles['file3'], 'Third', array.buffer], undefined, builder);156 var blob = blob.webkitSlice(7, 19);157 var blob2 = buildBlob(['Foo', blob, 'Bar'], undefined, builder);158 var blob2 = blob2.webkitSlice(12, 42);159 readBlobAsBinaryString(testFiles, blob2);...
read-file-test-cases.js
Source:read-file-test-cases.js
1var testCases = [2 "testReadingNonExistentFileAsArrayBuffer",3 "testReadingNonExistentFileAsBinaryString",4 "testReadingNonExistentFileAsText",5 "testReadingNonExistentFileAsDataURL",6 "testReadingEmptyFileAsArrayBuffer",7 "testReadingEmptyFileAsBinaryString",8 "testReadingEmptyFileAsText",9 "testReadingEmptyFileAsDataURL",10 "testReadingUTF8EncodedFileAsArrayBuffer",11 "testReadingUTF8EncodedFileAsBinaryString",12 "testReadingBinaryFileAsArrayBuffer",13 "testReadingBinaryFileAsBinaryString",14 "testReadingUTF8EncodedFileAsText",15 "testReadingUTF16BEBOMEncodedFileAsText",16 "testReadingUTF16LEBOMEncodedFileAsText",17 "testReadingUTF8BOMEncodedFileAsText",18 "testReadingUTF16BEEncodedFileAsTextWithUTF16Encoding",19 "testReadingUTF16BEBOMEncodedFileAsTextWithUTF8Encoding",20 "testReadingUTF16BEBOMEncodedFileAsTextWithInvalidEncoding",21 "testReadingUTF8EncodedFileAsDataURL",22 "testMultipleReads",23];24var testIndex = 0;25function runNextTest(testFiles)26{27 if (testIndex < testCases.length) {28 testIndex++;29 self[testCases[testIndex - 1]](testFiles);30 } else {31 log("DONE");32 }33}34function testReadingNonExistentFileAsArrayBuffer(testFiles)35{36 log("Test reading a non-existent file as array buffer");37 readBlobAsArrayBuffer(testFiles, testFiles['non-existent']);38}39function testReadingNonExistentFileAsBinaryString(testFiles)40{41 log("Test reading a non-existent file as binary string");42 readBlobAsBinaryString(testFiles, testFiles['non-existent']);43}44function testReadingNonExistentFileAsText(testFiles)45{46 log("Test reading a non-existent file as text");47 readBlobAsText(testFiles, testFiles['non-existent']);48}49function testReadingNonExistentFileAsDataURL(testFiles)50{51 log("Test reading a non-existent file as data URL");52 readBlobAsDataURL(testFiles, testFiles['non-existent']);53}54function testReadingEmptyFileAsArrayBuffer(testFiles)55{56 log("Test reading an empty file as array buffer");57 readBlobAsArrayBuffer(testFiles, testFiles['empty-file']);58}59function testReadingEmptyFileAsBinaryString(testFiles)60{61 log("Test reading an empty file as binary string");62 readBlobAsBinaryString(testFiles, testFiles['empty-file']);63}64function testReadingEmptyFileAsText(testFiles)65{66 log("Test reading an empty file as text");67 readBlobAsText(testFiles, testFiles['empty-file']);68}69function testReadingEmptyFileAsDataURL(testFiles)70{71 log("Test reading an empty file as data URL");72 readBlobAsDataURL(testFiles, testFiles['empty-file']);73}74function testReadingUTF8EncodedFileAsArrayBuffer(testFiles)75{76 log("Test reading a UTF-8 file as array buffer");77 readBlobAsArrayBuffer(testFiles, testFiles['UTF8-file']);78}79function testReadingUTF8EncodedFileAsBinaryString(testFiles)80{81 log("Test reading a UTF-8 file as binary string");82 readBlobAsBinaryString(testFiles, testFiles['UTF8-file']);83}84function testReadingBinaryFileAsArrayBuffer(testFiles)85{86 log("Test reading a binary file as array buffer");87 readBlobAsArrayBuffer(testFiles, testFiles['binary-file']);88}89function testReadingBinaryFileAsBinaryString(testFiles)90{91 log("Test reading a binary file as binary string");92 readBlobAsBinaryString(testFiles, testFiles['binary-file']);93}94function testReadingUTF8EncodedFileAsText(testFiles)95{96 log("Test reading a UTF-8 file as text");97 readBlobAsText(testFiles, testFiles['UTF8-file']);98}99function testReadingUTF16BEBOMEncodedFileAsText(testFiles)100{101 log("Test reading a UTF-16BE BOM file as text");102 readBlobAsText(testFiles, testFiles['UTF16BE-BOM-file']);103}104function testReadingUTF16LEBOMEncodedFileAsText(testFiles)105{106 log("Test reading a UTF-16LE BOM file as text");107 readBlobAsText(testFiles, testFiles['UTF16LE-BOM-file']);108}109function testReadingUTF8BOMEncodedFileAsText(testFiles)110{111 log("Test reading a UTF-8 BOM file as text");112 readBlobAsText(testFiles, testFiles['UTF8-BOM-file']);113}114function testReadingUTF16BEEncodedFileAsTextWithUTF16Encoding(testFiles)115{116 log("Test reading a UTF-16BE file as text with UTF-16BE encoding");117 readBlobAsText(testFiles, testFiles['UTF16BE-file'], "UTF-16BE");118}119function testReadingUTF16BEBOMEncodedFileAsTextWithUTF8Encoding(testFiles)120{121 log("Test reading a UTF-16BE BOM file as text with UTF8 encoding");122 readBlobAsText(testFiles, testFiles['UTF16BE-BOM-file'], "UTF-8");123}124function testReadingUTF16BEBOMEncodedFileAsTextWithInvalidEncoding(testFiles)125{126 log("Test reading a UTF-16BE BOM file as text with invalid encoding");127 readBlobAsText(testFiles, testFiles['UTF16BE-BOM-file'], "AnyInvalidEncoding");128}129function testReadingUTF8EncodedFileAsDataURL(testFiles)130{131 log("Test reading a UTF-8 file as data URL");132 readBlobAsDataURL(testFiles, testFiles['UTF8-file']);133}134function testMultipleReads(testFiles)135{136 // This test case is only available for async reading.137 if (!isReadAsAsync()) {138 runNextTest(testFiles);139 return;140 }141 log("Test calling multiple read methods and only last one is processed");142 var reader = createReaderAsync();143 reader.readAsArrayBuffer(testFiles['UTF8-file']);144 reader.readAsBinaryString(testFiles['UTF8-file']);145 reader.readAsText(testFiles['UTF8-file']);146 reader.readAsDataURL(testFiles['UTF8-file']);...
Using AI Code Generation
1const assert = require('chai').assert;2const head = require('../head');3describe("#head", () => {4 it("returns 1 for [1, 2, 3]", () => {5 assert.strictEqual(head([1, 2, 3]), 1);6 });7 it("returns '5' for ['5']", () => {8 assert.strictEqual(head(['5']), '5'); 9 });10 it("returns '5' for [5,6,7]", () => {11 assert.strictEqual(head([5,6,7]), 5); 12 });13 it("returns 'Hello' for ['Hello', 'Lighthouse', 'Labs']", () => {14 assert.strictEqual(head(['Hello', 'Lighthouse', 'Labs']), 'Hello'); 15 });16 it("returns undefined for []", () => {17 assert.strictEqual(head([]), undefined); 18 });19});
Using AI Code Generation
1var chai = require('chai');2var assert = chai.assert;3var expect = chai.expect;4var should = chai.should();5var mocha = require('mocha');6var describe = mocha.describe;7var it = mocha.it;8var supertest = require('supertest');9var should = require('should');10var request = require('request');11describe('Test /api/v1/employees', function() {12 it('should return 200 response', function(done) {13 api.get('/api/v1/employees')14 .set('Accept', 'application/json')15 .expect(200, done);16 });17});18describe('Test /api/v1/employees', function() {19 it('should return 200 response', function(done) {20 api.get('/api/v1/employees')21 .set('Accept', 'application/json')22 .expect(200, done);23 });24});25describe('Test /api/v1/employees', function() {26 it('should return 200 response', function(done) {27 api.get('/api/v1/employees')28 .set('Accept', 'application/json')29 .expect(200, done);30 });31});32describe('Test /api/v1/employees', function() {33 it('should return 200 response', function(done) {34 api.get('/api/v1/employees')35 .set('Accept', 'application/json')36 .expect(200, done);37 });38});39describe('Test /api/v1/employees', function() {40 it('should return 200 response', function(done) {41 api.get('/api/v1/employees')42 .set('Accept', 'application/json')43 .expect(200, done);44 });45});46describe('Test /api/v1/employees', function() {47 it('should return 200 response', function(done) {48 api.get('/api/v1/employees')49 .set('Accept', 'application/json')50 .expect(200, done);51 });52});
Using AI Code Generation
1const chai = require('chai');2const expect = chai.expect;3const assert = chai.assert;4const chai = require('chai');5const expect = chai.expect;6const assert = chai.assert;7describe('Test', function () {8 it('should return -1 when the value is not present', function () {9 assert.equal([1, 2, 3].indexOf(4), -1);10 });11});
Using AI Code Generation
1var expect = require('chai').expect;2var add = require('../add.js');3describe('add()', function() {4 it('should add two numbers together', function() {5 var result = add(2, 3);6 expect(result).to.equal(5);7 });8});9module.exports = function(a, b) {10 return a + b;11};
Using AI Code Generation
1const assert = require('chai').assert;2const expect = require('chai').expect;3const should = require('chai').should();4const add = require('../app').add;5describe('Array', function() {6 it('should return -1 when the value is not present', function() {7 assert.equal([1,2,3].indexOf(4), -1);8 });9});10describe('Addition', function() {11 it('should return 5 when 2 and 3 are passed', function() {12 assert.equal(add(2,3), 5);13 });14});15describe('Addition', function() {16 it('should return 5 when 2 and 3 are passed', function() {17 expect(add(2,3)).to.equal(5);18 });19});20describe('Addition', function() {21 it('should return 5 when 2 and 3 are passed', function() {22 add(2,3).should.equal(5);23 });24});25module.exports.add = (a,b) => {26 return a+b;27};28{29 "scripts": {30 },31 "dependencies": {32 }33}
Using AI Code Generation
1var chai = require('chai');2var expect = chai.expect;3var add = function(a,b){4return a+b;5}6describe('Addition', function(){7it('should return 5 when 2 and 3 are added', function(){8expect(add(2,3)).to.equal(5);9});10});11var chai = require('chai');12var chaiHttp = require('chai-http');13var server = require('../server');14var should = chai.should();15chai.use(chaiHttp);16describe('Test', function() {17 it('should return 200', function(done) {18 chai.request(server)19 .get('/test')20 .end(function(err, res) {21 res.should.have.status(200);22 done();23 });24 });25});26app.get('/test', function (req, res) {27 res.send('Hello World!');28});29var chai = require('chai');30var chaiHttp = require('chai-http');31var server = require('../server');32var should = chai.should();33chai.use(chaiHttp);34describe('Test', function() {35 it('should return 200', function(done) {36 chai.request(server)37 .get('/test')38 .end(function(err, res) {39 res.should.have.status(200);40 done();41 });42 });43});44app.get('/test', function (req, res) {45 res.send('Hello World!');46});
Using AI Code Generation
1const chai = require("chai");2const expect = chai.expect;3const assert = chai.assert;4const should = chai.should();5describe("test suite", function(){6 it("test case", function(){7 })8})9describe("test suite", function(){10 it("test case", function(){11 })12})13describe("test suite", function(){14 it("test case", function(){15 })16})17describe("test suite", function(){18 it("test case", function(){19 })20})21describe("test suite", function(){22 it("test case", function(){23 })24})25describe("test suite", function(){26 it("test case", function(){27 })28})29describe("test suite", function(){30 it("test case", function(){31 })32})33describe("test suite", function(){34 it("test case", function(){35 })36})37describe("test suite", function(){38 it("test case", function(){39 })40})41describe("test suite", function(){42 it("test case", function(){43 })44})45describe("test suite", function(){46 it("test case", function(){47 })48})
Using AI Code Generation
1var assert = require('chai').assert;2var expect = require('chai').expect;3var should = require('chai').should();4var myapp = require('../app.js');5describe("Test the app.js", function(){6 describe("Test the getSum function", function(){7 it("should return 5", function(){8 var result = myapp.getSum(2,3);9 assert.equal(result, 5);10 });11 it("should return type number", function(){12 var result = myapp.getSum(2,3);13 expect(result).to.be.a('number');14 });15 it("should return type number", function(){16 var result = myapp.getSum(2,3);17 result.should.be.a('number');18 });19 });20});21var myapp = {};22myapp.getSum = function(num1, num2){23 return num1 + num2;24}25module.exports = myapp;26{27 "scripts": {28 },29 "dependencies": {30 }31}
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!!