Best JavaScript code snippet using playwright-internal
Manager.js
Source:Manager.js
...10 'Ext.layout.Form'11 ],12 function() {13 var ct;14 function createContainer(cfg) {15 if (Ext.isArray(cfg)) {16 cfg = {17 items: cfg18 };19 }20 return ct = new MyContainer(cfg);21 }22 function sortById(A, B) {23 if (A.id < B.id) {24 return -1;25 }26 if (A.id > B.id) {27 return 1;28 }29 return 0;30 }31 beforeAll(function() {32 Ext.define('MyContainer', {33 extend: 'Ext.Container',34 xtype: 'mycontainer',35 mixins: [36 'Ext.field.Manager'37 ],38 nameHolder: true,39 defaultType: 'textfield',40 updateRecord: function(record) {41 this.consumeRecord(record);42 },43 updateDisabled: function(newDisabled, oldDisabled) {44 this.mixins.fieldmanager.updateDisabled.call(this, newDisabled, oldDisabled);45 this.callParent([newDisabled, oldDisabled]);46 }47 });48 Ext.define('MyModel', {49 extend: 'Ext.data.Model',50 fields: ['foo', 'bar', 'baz']51 });52 });53 afterAll(function() {54 Ext.undefine('MyContainer');55 Ext.undefine('MyModel');56 delete window.MyContainer;57 delete window.MyModel;58 });59 afterEach(function() {60 ct = Ext.destroy(ct);61 });62 it('should get mixed in', function() {63 createContainer();64 expect(ct.mixins.fieldmanager).toBeTruthy();65 });66 describe('fillRecord', function() {67 it('should fill passed record', function() {68 var record = new MyModel({69 id: 'mymodel'70 });71 createContainer([72 { name: 'foo', value: 'foo value' },73 { name: 'bar', value: 'bar value' },74 {75 xtype: 'container',76 defaultType: 'checkboxfield',77 items: [78 { name: 'baz', value: 'baz 1', checked: true },79 { name: 'baz', value: 'baz 2', checked: true },80 { name: 'baz', value: 'baz 3' },81 { name: 'baz', value: 'baz 4', checked: true }82 ]83 }84 ]);85 expect(ct.fillRecord(record)).toBe(ct);86 expect(record.data).toEqual({87 bar: 'bar value',88 foo: 'foo value',89 id: 'mymodel',90 baz: [91 'baz 1',92 'baz 2',93 'baz 4'94 ]95 });96 });97 it('should fill passed record overwriting values', function() {98 var record = new MyModel({99 id: 'mymodel',100 foo: 'blah',101 baz: 'nothing'102 });103 createContainer([104 { name: 'foo', value: 'foo value' },105 { name: 'bar', value: 'bar value' },106 {107 xtype: 'container',108 defaultType: 'checkboxfield',109 items: [110 { name: 'baz', value: 'baz 1', checked: true },111 { name: 'baz', value: 'baz 2', checked: true },112 { name: 'baz', value: 'baz 3' },113 { name: 'baz', value: 'baz 4', checked: true }114 ]115 }116 ]);117 expect(ct.fillRecord(record)).toBe(ct);118 expect(record.data).toEqual({119 bar: 'bar value',120 foo: 'foo value',121 id: 'mymodel',122 baz: [123 'baz 1',124 'baz 2',125 'baz 4'126 ]127 });128 });129 it('should not fill undefined record', function() {130 createContainer();131 var spy = spyOn(ct, 'getValues');132 expect(ct.fillRecord()).toBe(ct);133 expect(spy).not.toHaveBeenCalled();134 });135 });136 describe('updateRecord', function() {137 it('should set values from a record', function() {138 createContainer();139 var record = new MyModel({140 bar: 'bar value',141 baz: 'baz value',142 foo: 'foo value',143 id: 'mymodel'144 }),145 spy = spyOn(ct, 'setValues');146 ct.updateRecord(record);147 expect(spy).toHaveBeenCalled();148 expect(spy.mostRecentCall.args[0]).toEqual({149 bar: 'bar value',150 baz: 'baz value',151 foo: 'foo value',152 id: 'mymodel'153 });154 });155 it('should not set values from an undefined record', function() {156 createContainer();157 var spy = spyOn(ct, 'setValues');158 ct.updateRecord();159 expect(spy).not.toHaveBeenCalled();160 });161 });162 describe('setValues', function() {163 it('should set values to all fields', function() {164 createContainer([165 { name: 'foo' },166 { name: 'bar' },167 {168 xtype: 'container',169 defaultType: 'checkboxfield',170 items: [171 { name: 'baz', value: 'baz 1' },172 { name: 'baz', value: 'baz 2' },173 { name: 'baz', value: 'baz 3' },174 { name: 'baz', value: 'baz 4' }175 ]176 },177 {178 xtype: 'container',179 defaultType: 'radiofield',180 items: [181 { name: 'bazier', value: 'bazier 1', checked: true },182 { name: 'bazier', value: 'bazier 2' },183 { name: 'bazier', value: 'bazier 3' },184 { name: 'bazier', value: 'bazier 4' }185 ]186 }187 ]);188 var values = {189 bar: 'bar value',190 bazier: 'bazier 3',191 foo: 'foo value',192 baz: [193 'baz 1',194 'baz 3'195 ]196 };197 expect(ct.setValues(values)).toBe(ct);198 expect(ct.getValues()).toEqual({199 bar: 'bar value',200 bazier: 'bazier 3',201 foo: 'foo value',202 baz: [203 'baz 1',204 'baz 3'205 ]206 });207 });208 it('should not set values if none passed', function() {209 createContainer([210 { name: 'foo' },211 { name: 'bar' },212 {213 xtype: 'container',214 defaultType: 'checkboxfield',215 items: [216 { name: 'baz', value: 'baz 1' },217 { name: 'baz', value: 'baz 2' },218 { name: 'baz', value: 'baz 3' },219 { name: 'baz', value: 'baz 4' }220 ]221 },222 {223 xtype: 'container',224 defaultType: 'radiofield',225 items: [226 { name: 'bazier', value: 'bazier 1', checked: true },227 { name: 'bazier', value: 'bazier 2' },228 { name: 'bazier', value: 'bazier 3' },229 { name: 'bazier', value: 'bazier 4' }230 ]231 }232 ]);233 expect(ct.setValues()).toBe(ct);234 var values = ct.getValues();235 expect(values).toEqual({236 bar: null,237 bazier: 'bazier 1',238 foo: null,239 baz: null240 });241 });242 });243 describe('getValues', function() {244 it('should get values from all fields', function() {245 createContainer([246 { name: 'foo', value: 'foo value' },247 { name: 'bar', value: 'bar value' },248 {249 xtype: 'container',250 defaultType: 'checkboxfield',251 items: [252 { name: 'baz', value: 'baz 1', checked: true },253 { name: 'baz', value: 'baz 2', checked: true },254 { name: 'baz', value: 'baz 3' },255 { name: 'baz', value: 'baz 4', checked: true }256 ]257 },258 {259 xtype: 'container',260 defaultType: 'radiofield',261 items: [262 { name: 'bazier', value: 'bazier 1', checked: true },263 { name: 'bazier', value: 'bazier 2' },264 { name: 'bazier', value: 'bazier 3' },265 { name: 'bazier', value: 'bazier 4' }266 ]267 }268 ]);269 expect(ct.getValues()).toEqual({270 bar: 'bar value',271 bazier: 'bazier 1',272 foo: 'foo value',273 baz: [274 'baz 1',275 'baz 2',276 'baz 4'277 ]278 });279 });280 });281 describe('reset', function() {282 it('should reset all fields', function() {283 createContainer([284 { required: true, name: 'foo', value: 'foo value' },285 { required: true, name: 'bar', value: 'bar value' },286 {287 xtype: 'container',288 defaultType: 'checkboxfield',289 items: [290 { name: 'baz', value: 'baz 1', checked: true },291 { name: 'baz', value: 'baz 2', checked: true },292 { name: 'baz', value: 'baz 3' },293 { name: 'baz', value: 'baz 4', checked: true }294 ]295 },296 {297 xtype: 'container',298 defaultType: 'radiofield',299 items: [300 { name: 'bazier', value: 'bazier 1', checked: true },301 { name: 'bazier', value: 'bazier 2' },302 { name: 'bazier', value: 'bazier 3' },303 { name: 'bazier', value: 'bazier 4' }304 ]305 }306 ]);307 var origValues = {308 bar: 'bar value',309 bazier: 'bazier 1',310 foo: 'foo value',311 baz: [312 'baz 1',313 'baz 2',314 'baz 4'315 ]316 },317 newValues = {318 bar: '',319 bazier: 'bazier 3',320 foo: '',321 baz: [322 'baz 1',323 'baz 3'324 ]325 },326 foo = ct.lookupName('foo'),327 bar = ct.lookupName('bar');328 expect(ct.getValues()).toEqual(origValues);329 expect(ct.setValues(newValues)).toBe(ct);330 expect(ct.getValues()).toEqual(newValues);331 expect(foo.getError()).toEqual(['This field is required']);332 expect(bar.getError()).toEqual(['This field is required']);333 expect(ct.reset()).toBe(ct);334 expect(ct.getValues()).toEqual(origValues);335 });336 it('should reset all fields and setError(null) each field', function() {337 createContainer([338 { required: true, name: 'foo', value: 'foo value' },339 { required: true, name: 'bar', value: 'bar value' },340 {341 xtype: 'container',342 defaultType: 'checkboxfield',343 items: [344 { name: 'baz', value: 'baz 1', checked: true },345 { name: 'baz', value: 'baz 2', checked: true },346 { name: 'baz', value: 'baz 3' },347 { name: 'baz', value: 'baz 4', checked: true }348 ]349 },350 {351 xtype: 'container',352 defaultType: 'radiofield',353 items: [354 { name: 'bazier', value: 'bazier 1', checked: true },355 { name: 'bazier', value: 'bazier 2' },356 { name: 'bazier', value: 'bazier 3' },357 { name: 'bazier', value: 'bazier 4' }358 ]359 }360 ]);361 var origValues = {362 bar: 'bar value',363 bazier: 'bazier 1',364 foo: 'foo value',365 baz: [366 'baz 1',367 'baz 2',368 'baz 4'369 ]370 },371 newValues = {372 bar: '',373 bazier: 'bazier 3',374 foo: '',375 baz: [376 'baz 1',377 'baz 3'378 ]379 },380 foo = ct.lookupName('foo'),381 bar = ct.lookupName('bar');382 expect(ct.getValues()).toEqual(origValues);383 expect(ct.setValues(newValues)).toBe(ct);384 expect(ct.getValues()).toEqual(newValues);385 expect(foo.getError()).toEqual(['This field is required']);386 expect(bar.getError()).toEqual(['This field is required']);387 expect(ct.reset(true)).toBe(ct);388 expect(ct.getValues()).toEqual(origValues);389 expect(foo.getError()).toBeNull();390 expect(bar.getError()).toBeNull();391 });392 });393 describe('updateDisabled', function() {394 it('should disable all fields', function() {395 createContainer([396 { required: true, name: 'foo', value: 'foo value' },397 { required: true, name: 'bar', value: 'bar value' },398 {399 xtype: 'container',400 defaultType: 'checkboxfield',401 items: [402 { name: 'baz', value: 'baz 1', checked: true },403 { name: 'baz', value: 'baz 2', checked: true },404 { name: 'baz', value: 'baz 3' },405 { name: 'baz', value: 'baz 4', checked: true }406 ]407 }408 ]);409 var foo = ct.lookupName('foo'),410 bar = ct.lookupName('bar'),411 baz = ct.lookupName('baz');412 expect(ct.setDisabled(true)).toBe(ct);413 expect(foo.getDisabled()).toBe(true);414 expect(bar.getDisabled()).toBe(true);415 baz.forEach(function(field) {416 expect(field.getDisabled()).toBe(true);417 });418 });419 it('should enable all fields', function() {420 createContainer([421 { required: true, name: 'foo', value: 'foo value', disabled: true },422 { required: true, name: 'bar', value: 'bar value', disabled: true },423 {424 xtype: 'container',425 defaultType: 'checkboxfield',426 items: [427 { name: 'baz', value: 'baz 1', disabled: true, checked: true },428 { name: 'baz', value: 'baz 2', disabled: true, checked: true },429 { name: 'baz', value: 'baz 3', disabled: true },430 { name: 'baz', value: 'baz 4', disabled: true, checked: true }431 ]432 }433 ]);434 var foo = ct.lookupName('foo'),435 bar = ct.lookupName('bar'),436 baz = ct.lookupName('baz');437 expect(foo.getDisabled()).toBe(true);438 expect(bar.getDisabled()).toBe(true);439 baz.forEach(function(field) {440 expect(field.getDisabled()).toBe(true);441 });442 expect(ct.setDisabled(false)).toBe(ct);443 expect(foo.getDisabled()).toBe(false);444 expect(bar.getDisabled()).toBe(false);445 baz.forEach(function(field) {446 expect(field.getDisabled()).toBe(false);447 });448 });449 });450 describe('setErrors', function() {451 it('should set errors on all fields', function() {452 createContainer([453 { name: 'foo' },454 { name: 'bar' },455 {456 xtype: 'container',457 defaultType: 'checkboxfield',458 items: [459 { name: 'baz', value: 'baz 1' },460 { name: 'baz', value: 'baz 2' },461 { name: 'baz', value: 'baz 3' },462 { name: 'baz', value: 'baz 4' }463 ]464 },465 {466 xtype: 'container',467 defaultType: 'radiofield',468 items: [469 { name: 'bazier', value: 'bazier 1' },470 { name: 'bazier', value: 'bazier 2' },471 { name: 'bazier', value: 'bazier 3' },472 { name: 'bazier', value: 'bazier 4' }473 ]474 }475 ]);476 var foo = ct.lookupName('foo'),477 bar = ct.lookupName('bar'),478 baz = ct.lookupName('baz'),479 bazier = ct.lookupName('bazier'),480 errors = {481 foo: 'Foo is in error!',482 bar: [483 'Bar is in error!',484 'Bar still error!'485 ],486 baz: 'Baz is errored',487 bazier: 'Bazier not very good'488 };489 expect(ct.setErrors(errors)).toBe(ct);490 expect(foo.getError()).toBe('Foo is in error!');491 expect(bar.getError()).toEqual(['Bar is in error!', 'Bar still error!']);492 baz.forEach(function(check) {493 expect(check.getError()).toBe('Baz is errored');494 });495 bazier.forEach(function(radio) {496 expect(radio.getError()).toBe('Bazier not very good');497 });498 });499 it('should not set errors if an array is passed', function() {500 createContainer();501 var spy = spyOn(Ext, 'raise');502 ct.setErrors([]);503 expect(spy).toHaveBeenCalled();504 });505 it('should not set errors if a string is passed', function() {506 createContainer();507 var spy = spyOn(Ext, 'raise');508 ct.setErrors('foobar');509 expect(spy).toHaveBeenCalled();510 });511 it('should set errors on nested fields', function() {512 createContainer({513 layout: {514 type: 'form'515 },516 items: [{517 xtype: 'containerfield',518 label: 'Name',519 defaults: {520 flex: 1,521 labelAlign: 'top'522 },523 items: [524 { label: 'First', name: 'first' },525 { label: 'Middle', name: 'middle' },526 { label: 'Last', name: 'last' }527 ]528 }, {529 xtype: 'textfield',530 label: 'A longer label to test width',531 name: 'text'532 }]533 });534 var first = ct.lookupName('first'),535 middle = ct.lookupName('middle'),536 last = ct.lookupName('last'),537 text = ct.lookupName('text'),538 errors = {539 text: 'Text value is bad!',540 // containerfield errors below541 first: 'First is bad!',542 middle: 'Middle is bad!',543 last: 'Last is bad!'544 };545 expect(ct.setErrors(errors)).toBe(ct);546 expect(first.getError()).toBe('First is bad!');547 expect(middle.getError()).toBe('Middle is bad!');548 expect(last.getError()).toBe('Last is bad!');549 expect(text.getError()).toBe('Text value is bad!');550 });551 });552 describe('clearErrors', function() {553 it('should clear all field errors', function() {554 createContainer([555 { name: 'foo', error: 'foo error' },556 { name: 'bar', error: 'bar error' },557 {558 xtype: 'container',559 defaultType: 'radiofield',560 items: [561 { name: 'bazier', value: 'bazier 1', error: 'bazier error' },562 { name: 'bazier', value: 'bazier 2', error: 'bazier error' },563 { name: 'bazier', value: 'bazier 3', error: 'bazier error' },564 { name: 'bazier', value: 'bazier 4', error: 'bazier error' }565 ]566 }567 ]);568 var foo = ct.lookupName('foo'),569 bar = ct.lookupName('bar'),570 baz = ct.lookupName('baz'),571 bazier = ct.lookupName('bazier');572 expect(foo.getError()).toBe('foo error');573 expect(bar.getError()).toBe('bar error');574 bazier.forEach(function(radio) {575 expect(radio.getError()).toBe('bazier error');576 });577 expect(ct.clearErrors()).toBe(ct);578 expect(foo.getError()).toBeNull();579 expect(bar.getError()).toBeNull();580 bazier.forEach(function(radio) {581 expect(radio.getError()).toBeNull();582 });583 });584 it('should not clear fields without a name', function() {585 createContainer([586 { name: 'foo', error: 'foo error' },587 { error: 'bar error' },588 {589 xtype: 'container',590 defaultType: 'radiofield',591 items: [592 { name: 'bazier', value: 'bazier 1', error: 'bazier error' },593 { name: 'bazier', value: 'bazier 2', error: 'bazier error' },594 { name: 'bazier', value: 'bazier 3', error: 'bazier error' },595 { name: 'bazier', value: 'bazier 4', error: 'bazier error' }596 ]597 }598 ]);599 var foo = ct.lookupName('foo'),600 bar = ct.getAt(1),601 baz = ct.lookupName('baz'),602 bazier = ct.lookupName('bazier');603 expect(foo.getError()).toBe('foo error');604 expect(bar.getError()).toBe('bar error');605 bazier.forEach(function(radio) {606 expect(radio.getError()).toBe('bazier error');607 });608 expect(ct.clearErrors()).toBe(ct);609 expect(foo.getError()).toBeNull();610 expect(bar.getError()).toBe('bar error');611 bazier.forEach(function(radio) {612 expect(radio.getError()).toBeNull();613 });614 });615 });616 describe('getErrors', function() {617 it('should return field errors', function() {618 createContainer([619 { name: 'foo', error: 'foo error' },620 { name: 'bar' },621 {622 xtype: 'container',623 defaultType: 'radiofield',624 items: [625 { name: 'bazier', value: 'bazier 1', error: 'bazier error' },626 { name: 'bazier', value: 'bazier 2', error: 'bazier error' },627 { name: 'bazier', value: 'bazier 3', error: 'bazier error' },628 { name: 'bazier', value: 'bazier 4', error: 'bazier error' }629 ]630 }631 ]);632 expect(ct.getErrors()).toEqual({633 foo: 'foo error',634 bar: null,635 bazier: 'bazier error'636 });637 });638 });639 describe('isValid', function() {640 it('should stop checking fields when a field is not valid', function() {641 it('should stop checking fields when a field is not valid', function() {642 createContainer([643 { name: 'foo', error: 'foo error' },644 { name: 'bar' }645 ]);646 var foo = ct.lookupName('foo'),647 bar = ct.lookupName('bar'),648 spy = spyOn(bar, 'isValid');649 expect(ct.isValid()).toBe(false);650 expect(spy).not.toHaveBeenCalled();651 });652 });653 it('should check all fields if valid', function() {654 createContainer([655 { name: 'foo' },656 { name: 'bar' }657 ]);658 var bar = ct.lookupName('bar'),659 spy = spyOn(bar, 'isValid').andCallThrough();660 expect(ct.isValid()).toBe(true);661 expect(spy).toHaveBeenCalled();662 });663 });664 describe('validate', function() {665 it('should validate all fields', function() {666 createContainer([667 { name: 'foo', required: true },668 { name: 'bar' }669 ]);670 var foo = ct.lookupName('foo'),671 bar = ct.lookupName('bar'),672 spy = spyOn(bar, 'validate').andCallThrough();673 expect(ct.validate()).toBe(false);674 expect(spy).toHaveBeenCalled();675 });676 it('should be valid', function() {677 createContainer([678 { name: 'foo', value: 'foo', required: true },679 { name: 'bar' }680 ]);681 var foo = ct.lookupName('foo'),682 bar = ct.lookupName('bar'),683 spy = spyOn(bar, 'validate').andCallThrough();684 expect(ct.validate()).toBe(true);685 expect(spy).toHaveBeenCalled();686 });687 });688 describe('getFields', function() {689 beforeEach(function() {690 createContainer([691 { name: 'foo' },692 { name: 'bar' },693 {694 xtype: 'container',695 defaultType: 'checkboxfield',696 items: [697 { name: 'baz', value: 'baz 1' },698 { name: 'baz', value: 'baz 2' },699 { name: 'baz', value: 'baz 3' },700 { name: 'baz', value: 'baz 4' }701 ]702 },703 {704 xtype: 'container',705 defaultType: 'radiofield',706 items: [707 { name: 'bazier', value: 'bazier 1' },708 { name: 'bazier', value: 'bazier 2' },709 { name: 'bazier', value: 'bazier 3' },710 { name: 'bazier', value: 'bazier 4' }711 ]712 }713 ]);714 });715 describe('return object', function() {716 it('should return an object of fields by name', function() {717 var fields = {718 foo: ct.lookupName('foo'),719 bar: ct.lookupName('bar'),720 baz: jasmine.array.toMap(ct.lookupName('baz'), 'id'),721 bazier: jasmine.array.toMap(ct.lookupName('bazier'), 'id')722 },723 found = ct.getFields();724 found.baz = jasmine.array.toMap(found.baz, 'id');725 found.bazier = jasmine.array.toMap(found.bazier, 'id');726 expect(found).toEqual(fields);727 });728 it('should return an object of shallow fields by name', function() {729 var fields = {730 foo: ct.lookupName('foo'),731 bar: ct.lookupName('bar')732 };733 expect(ct.getFields(null, false)).toEqual(fields);734 });735 });736 describe('return array', function() {737 it('should return an array if byName is false', function() {738 var fields = jasmine.array.toMap([739 ct.lookupName('foo'),740 ct.lookupName('bar')741 ].concat(742 ct.lookupName('baz'),743 ct.lookupName('bazier')744 ), 'id');745 expect(jasmine.array.toMap(ct.getFields(false), 'id')).toEqual(fields);746 });747 it('should return an array if name passed', function() {748 var fields = jasmine.array.toMap(ct.lookupName('baz'), 'id');749 expect(jasmine.array.toMap(ct.getFields('baz'), 'id')).toEqual(fields);750 });751 });752 describe('return instance', function() {753 it('should return an instance if name passed', function() {754 var field = ct.lookupName('foo');755 expect(ct.getFields('foo')).toBe(field);756 });757 it('should return a shallow instance if name is passed', function() {758 var field = ct.lookupName('foo');759 expect(ct.getFields('foo', false)).toBe(field);760 });761 });762 describe('return undefined', function() {763 it('should not return if name does not match', function() {764 expect(ct.getFields('foobar')).toBeUndefined();765 });766 it('should not return if name is passed but is not shallow', function() {767 expect(ct.getFields('baz', false)).toBeUndefined();768 });769 });770 });771 describe('getFocusedField', function() {772 it('should find a focused field', function() {773 createContainer({774 renderTo: Ext.getBody(),775 items: [776 { name: 'foo' },777 { name: 'bar' }778 ]779 });780 var foo = ct.lookupName('foo');781 waitsFor(function() {782 return ct.rendered;783 });784 runs(function() {785 foo.onFocus();786 expect(ct.getFocusedField()).toBe(foo);787 });788 });789 it('should not find a focused field', function() {790 createContainer({791 renderTo: Ext.getBody(),792 items: [793 { name: 'foo' },794 { name: 'bar' }795 ]796 });797 var foo = ct.lookupName('foo');798 waitsFor(function() {799 return ct.rendered;800 });801 runs(function() {802 expect(ct.getFocusedField()).toBeNull();803 });804 });805 });806 describe('getNextField', function() {807 it('should find the next field after the focused field', function() {808 createContainer({809 renderTo: Ext.getBody(),810 items: [811 { name: 'foo' },812 { name: 'bar' }813 ]814 });815 var foo = ct.lookupName('foo'),816 bar = ct.lookupName('bar');817 waitsFor(function() {818 return ct.rendered;819 });820 runs(function() {821 foo.onFocus();822 expect(ct.getNextField()).toBe(bar);823 });824 });825 it('should not find the next field after the focused field', function() {826 createContainer({827 renderTo: Ext.getBody(),828 items: [829 { name: 'foo' },830 { name: 'bar' }831 ]832 });833 var foo = ct.lookupName('foo'),834 bar = ct.lookupName('bar');835 waitsFor(function() {836 return ct.rendered;837 });838 runs(function() {839 expect(ct.getNextField()).toBe(false);840 });841 });842 it('should not find the next field if focused is last field', function() {843 createContainer({844 renderTo: Ext.getBody(),845 items: [846 { name: 'foo' },847 { name: 'bar' }848 ]849 });850 var bar = ct.lookupName('bar');851 waitsFor(function() {852 return ct.rendered;853 });854 runs(function() {855 bar.onFocus();856 expect(ct.getNextField()).toBe(false);857 });858 });859 });860 describe('focusNextField', function() {861 it('should focus next field', function() {862 createContainer({863 renderTo: Ext.getBody(),864 items: [865 { name: 'foo' },866 { name: 'bar' }867 ]868 });869 var foo = ct.lookupName('foo'),870 bar = ct.lookupName('bar'),871 spy = spyOn(bar, 'focus');872 waitsFor(function() {873 return ct.rendered;874 });875 runs(function() {876 foo.onFocus();877 expect(ct.focusNextField()).toBe(bar);878 expect(spy).toHaveBeenCalled();879 });880 });881 it('should not focus next field if no field was focused', function() {882 createContainer({883 renderTo: Ext.getBody(),884 items: [885 { name: 'foo' },886 { name: 'bar' }887 ]888 });889 var foo = ct.lookupName('foo'),890 bar = ct.lookupName('bar'),891 spy = spyOn(bar, 'focus');892 waitsFor(function() {893 return ct.rendered;894 });895 runs(function() {896 expect(ct.focusNextField()).toBe(false);897 expect(spy).not.toHaveBeenCalled();898 });899 });900 it('should not focus next field if focused is last field', function() {901 createContainer({902 renderTo: Ext.getBody(),903 items: [904 { name: 'foo' },905 { name: 'bar' }906 ]907 });908 var bar = ct.lookupName('bar');909 waitsFor(function() {910 return ct.rendered;911 });912 runs(function() {913 bar.onFocus();914 expect(ct.focusNextField()).toBe(false);915 });916 });917 });918 describe('getPreviousField', function() {919 it('should get field before focused field', function() {920 createContainer({921 renderTo: Ext.getBody(),922 items: [923 { name: 'foo' },924 { name: 'bar' }925 ]926 });927 var foo = ct.lookupName('foo'),928 bar = ct.lookupName('bar');929 waitsFor(function() {930 return ct.rendered;931 });932 runs(function() {933 bar.onFocus();934 expect(ct.getPreviousField()).toBe(foo);935 });936 });937 it('should not find the previous field if no field is focused', function() {938 createContainer({939 renderTo: Ext.getBody(),940 items: [941 { name: 'foo' },942 { name: 'bar' }943 ]944 });945 var foo = ct.lookupName('foo'),946 bar = ct.lookupName('bar');947 waitsFor(function() {948 return ct.rendered;949 });950 runs(function() {951 expect(ct.getPreviousField()).toBe(false);952 });953 });954 it('should not find the previous field if focused is first field', function() {955 createContainer({956 renderTo: Ext.getBody(),957 items: [958 { name: 'foo' },959 { name: 'bar' }960 ]961 });962 var foo = ct.lookupName('foo');963 waitsFor(function() {964 return ct.rendered;965 });966 runs(function() {967 foo.onFocus();968 expect(ct.getPreviousField()).toBe(false);969 });970 });971 });972 describe('focusPreviousField', function() {973 it('should focus previous field', function() {974 createContainer({975 renderTo: Ext.getBody(),976 items: [977 { name: 'foo' },978 { name: 'bar' }979 ]980 });981 var foo = ct.lookupName('foo'),982 bar = ct.lookupName('bar'),983 spy = spyOn(foo, 'focus');984 waitsFor(function() {985 return ct.rendered;986 });987 runs(function() {988 bar.onFocus();989 expect(ct.focusPreviousField()).toBe(foo);990 expect(spy).toHaveBeenCalled();991 });992 });993 it('should not focus previous field if no field was focused', function() {994 createContainer({995 renderTo: Ext.getBody(),996 items: [997 { name: 'foo' },998 { name: 'bar' }999 ]1000 });1001 var foo = ct.lookupName('foo'),1002 bar = ct.lookupName('bar'),1003 spy = spyOn(foo, 'focus');1004 waitsFor(function() {1005 return ct.rendered;1006 });1007 runs(function() {1008 expect(ct.focusPreviousField()).toBe(false);1009 expect(spy).not.toHaveBeenCalled();1010 });1011 });1012 it('should not focus previous field if focused is first field', function() {1013 createContainer({1014 renderTo: Ext.getBody(),1015 items: [1016 { name: 'foo' },1017 { name: 'bar' }1018 ]1019 });1020 var foo = ct.lookupName('foo');1021 waitsFor(function() {1022 return ct.rendered;1023 });1024 runs(function() {1025 foo.onFocus();1026 expect(ct.focusPreviousField()).toBe(false);1027 });...
container.spec.js
Source:container.spec.js
...4describe('Container', () => {5 let container;6 describe('Constructor', () => {7 it('should instantiate a new Container', () => {8 container = createContainer();9 expect(container).to.be.an.instanceof(Container);10 });11 it('should not have a collider by default', () => {12 container = createContainer();13 expect(container.colliderType).to.equal(null);14 });15 it('should accept arguments', () => {16 container = createContainer({ collider: { type: 'rect' } });17 expect(container.colliderType).to.equal('rect');18 expect(container.collider).to.be.an.instanceof(GeoRect);19 });20 });21 describe('Set', () => {22 it('should set correct values', () => {23 container = createContainer();24 container.set({ collider: { type: 'rect' } });25 expect(container.colliderType).to.equal('rect');26 expect(container.collider).to.be.an.instanceof(GeoRect);27 });28 it('should handle no arguments', () => {29 container = createContainer();30 container.set();31 expect(container.colliderType).to.equal(null);32 });33 it('should be able to disable the collider', () => {34 container = createContainer({ collider: { type: 'rect' } });35 container.set({ collider: { type: null } });36 expect(container.colliderType).to.equal(null);37 });38 });39 describe('BoundingRect', () => {40 it('should return a zero sized rect if no children have been added', () => {41 container = createContainer();42 expect(container.boundingRect()).to.deep.equal({43 x: 0, y: 0, width: 0, height: 044 });45 });46 it('should return correct value if container and children are without a transformation', () => {47 container = createContainer();48 container.addChildren([49 createRect({50 x: 5, y: 10, width: 1, height: 2051 }), // Height52 createRect({53 x: 0, y: 0, width: 10, height: 254 }), // Width55 createRect({56 x: -10, y: -20, width: 1, height: 257 }) // x,y58 ]);59 expect(container.boundingRect()).to.deep.equal({60 x: -10, y: -20, width: 20, height: 5061 });62 });63 it('should return correct value with a transformation on its children', () => {64 container = createContainer();65 container.addChildren([66 createRect({67 x: 5, y: 10, width: 1, height: 20, transform: 'scale(2, 3)'68 }),69 createRect({70 x: 0, y: 0, width: 10, height: 2, transform: 'scale(2, 3)'71 }),72 createRect({73 x: -10, y: -20, width: 1, height: 2, transform: 'scale(2, 3)'74 })75 ]);76 container.children.forEach(c => c.resolveGlobalTransform());77 expect(container.boundingRect(true)).to.deep.equal({78 x: -20, y: -60, width: 40, height: 15079 });80 });81 it('should return correct value with a transformation the container and its children', () => {82 container = createContainer({ transform: 'scale(2, 3)' });83 container.addChildren([84 createRect({85 x: 5, y: 10, width: 1, height: 20, transform: 'translate(1, 2)'86 }),87 createRect({88 x: 0, y: 0, width: 10, height: 2, transform: 'translate(1, 2)'89 }),90 createRect({91 x: -10, y: -20, width: 1, height: 2, transform: 'translate(1, 2)'92 })93 ]);94 container.children.forEach(c => c.resolveGlobalTransform());95 expect(container.boundingRect(true)).to.deep.equal({96 x: -18, y: -54, width: 40, height: 15097 });98 });99 it('should return correct value a scale transformation', () => {100 container = createContainer({ transform: 'scale(2, 3)' });101 container.addChildren([102 createRect({103 x: 5, y: 10, width: 1, height: 20104 }), // Height105 createRect({106 x: 0, y: 0, width: 10, height: 2107 }), // Width108 createRect({109 x: -10, y: -20, width: 1, height: 2110 }) // x,y111 ]);112 container.children.forEach(c => c.resolveGlobalTransform());113 expect(container.boundingRect(true)).to.deep.equal({114 x: -20, y: -60, width: 40, height: 150115 });116 });117 it('should return correct value with a translate transformation', () => {118 container = createContainer({ transform: 'translate(2, 3)' });119 container.addChildren([120 createRect({121 x: 5, y: 10, width: 1, height: 20122 }), // Height123 createRect({124 x: 0, y: 0, width: 10, height: 2125 }), // Width126 createRect({127 x: -10, y: -20, width: 1, height: 2128 }) // x,y129 ]);130 container.children.forEach(c => c.resolveGlobalTransform());131 expect(container.boundingRect(true)).to.deep.equal({132 x: -8, y: -17, width: 20, height: 50133 });134 });135 it('should return correct value with a rotate transformation', () => {136 container = createContainer({ transform: 'rotate(45)' });137 container.addChildren([138 createRect({139 x: 5, y: 10, width: 1, height: 20140 }),141 createRect({142 x: 0, y: 0, width: 10, height: 2143 }),144 createRect({145 x: -10, y: -20, width: 1, height: 2146 })147 ]);148 container.children.forEach(c => c.resolveGlobalTransform());149 expect(container.boundingRect(true)).to.deep.equal({150 x: -17.677669529663685, y: -21.213203435596427, width: 25.455844122715707, height: 46.66904755831214151 });152 });153 });154 describe('Bounds', () => {155 it('should return a zero sized rect if no children have been added', () => {156 container = createContainer();157 expect(container.bounds()).to.deep.equal([158 { x: 0, y: 0 },159 { x: 0, y: 0 },160 { x: 0, y: 0 },161 { x: 0, y: 0 }162 ]);163 });164 it('should return correct value if container and children are without a transformation', () => {165 container = createContainer();166 container.addChildren([167 createRect({168 x: 5, y: 10, width: 1, height: 20169 }), // Height170 createRect({171 x: 0, y: 0, width: 10, height: 2172 }), // Width173 createRect({174 x: -10, y: -20, width: 1, height: 2175 }) // x,y176 ]);177 expect(container.bounds()).to.deep.equal([178 { x: -10, y: -20 },179 { x: 10, y: -20 },180 { x: 10, y: 30 },181 { x: -10, y: 30 }182 ]);183 });184 it('should return correct value with a transformation on its children', () => {185 container = createContainer();186 container.addChildren([187 createRect({188 x: 5, y: 10, width: 1, height: 20, transform: 'scale(2, 3)'189 }),190 createRect({191 x: 0, y: 0, width: 10, height: 2, transform: 'scale(2, 3)'192 }),193 createRect({194 x: -10, y: -20, width: 1, height: 2, transform: 'scale(2, 3)'195 })196 ]);197 container.children.forEach(c => c.resolveGlobalTransform());198 expect(container.bounds(true)).to.deep.equal([199 { x: -20, y: -60 },200 { x: 20, y: -60 },201 { x: 20, y: 90 },202 { x: -20, y: 90 }203 ]);204 });205 it('should return correct value with a transformation the container and its children', () => {206 container = createContainer({ transform: 'scale(2, 3)' });207 container.addChildren([208 createRect({209 x: 5, y: 10, width: 1, height: 20, transform: 'translate(1, 2)'210 }),211 createRect({212 x: 0, y: 0, width: 10, height: 2, transform: 'translate(1, 2)'213 }),214 createRect({215 x: -10, y: -20, width: 1, height: 2, transform: 'translate(1, 2)'216 })217 ]);218 container.children.forEach(c => c.resolveGlobalTransform());219 expect(container.bounds(true)).to.deep.equal([220 { x: -18, y: -54 },221 { x: 22, y: -54 },222 { x: 22, y: 96 },223 { x: -18, y: 96 }224 ]);225 });226 it('should return correct value a scale transformation', () => {227 container = createContainer({ transform: 'scale(2, 3)' });228 container.addChildren([229 createRect({230 x: 5, y: 10, width: 1, height: 20231 }), // Height232 createRect({233 x: 0, y: 0, width: 10, height: 2234 }), // Width235 createRect({236 x: -10, y: -20, width: 1, height: 2237 }) // x,y238 ]);239 container.children.forEach(c => c.resolveGlobalTransform());240 expect(container.bounds(true)).to.deep.equal([241 { x: -20, y: -60 },242 { x: 20, y: -60 },243 { x: 20, y: 90 },244 { x: -20, y: 90 }245 ]);246 });247 it('should return correct value with a translate transformation', () => {248 container = createContainer({ transform: 'translate(2, 3)' });249 container.addChildren([250 createRect({251 x: 5, y: 10, width: 1, height: 20252 }), // Height253 createRect({254 x: 0, y: 0, width: 10, height: 2255 }), // Width256 createRect({257 x: -10, y: -20, width: 1, height: 2258 }) // x,y259 ]);260 container.children.forEach(c => c.resolveGlobalTransform());261 expect(container.bounds(true)).to.deep.equal([262 { x: -8, y: -17 },263 { x: 12, y: -17 },264 { x: 12, y: 33 },265 { x: -8, y: 33 }266 ]);267 });268 it('should return correct value with a rotate transformation', () => {269 container = createContainer({ transform: 'rotate(45)' });270 container.addChildren([271 createRect({272 x: 5, y: 10, width: 1, height: 20273 }),274 createRect({275 x: 0, y: 0, width: 10, height: 2276 }),277 createRect({278 x: -10, y: -20, width: 1, height: 2279 })280 ]);281 container.children.forEach(c => c.resolveGlobalTransform());282 expect(container.bounds(true)).to.deep.equal([283 { x: -17.677669529663685, y: -21.213203435596427 },284 { x: 7.778174593052022, y: -21.213203435596427 },285 { x: 7.778174593052022, y: 25.45584412271571 },286 { x: -17.677669529663685, y: 25.45584412271571 }287 ]);288 });289 });290 describe('containsPoint', () => {291 it('should return true if any child contains point', () => {292 container = createContainer();293 container.addChild(createRect({294 x: 500, y: 500, width: 100, height: 100295 }));296 container.addChild(createRect({297 x: 500, y: 500, width: 200, height: 200298 }));299 const r = container.containsPoint({ x: 550, y: 550 });300 expect(r).to.equal(true);301 });302 it('should return true if any childs child contains point', () => {303 container = createContainer();304 container.addChild(createRect({305 x: 500, y: 500, width: 100, height: 100306 }));307 container.addChild(createRect({308 x: 500, y: 500, width: 200, height: 200309 }));310 const childContainer = createContainer();311 childContainer.addChild(createRect({312 x: 0, y: 0, width: 200, height: 200313 }));314 childContainer.addChild(createRect({315 x: 1500, y: 1500, width: 200, height: 200316 }));317 container.addChild(childContainer);318 const r = container.containsPoint({ x: 1550, y: 1550 });319 expect(r).to.equal(true);320 });321 it('should return false if no child contains point', () => {322 container = createContainer();323 container.addChild(createRect({324 x: 500, y: 500, width: 100, height: 100325 }));326 container.addChild(createRect({327 x: 500, y: 500, width: 200, height: 200328 }));329 const r = container.containsPoint({ x: 0, y: 0 });330 expect(r).to.equal(false);331 });332 it('should return true if bounds contains point', () => {333 container = createContainer({ collider: { type: 'bounds' } });334 container.addChild(createRect({335 x: 0, y: 0, width: 100, height: 100336 }));337 container.addChild(createRect({338 x: 1500, y: 1500, width: 200, height: 200339 }));340 const r = container.containsPoint({ x: 2, y: 2 });341 expect(r).to.equal(true);342 });343 it('should include self transformation when resolving collision', () => {344 const rect = createRect({345 x: 0,346 y: 0,347 width: 100,348 height: 100349 });350 container = createContainer({ transform: 'translate(10, 20)', collider: { type: 'bounds' } });351 container.addChild(rect);352 rect.resolveGlobalTransform();353 // After transform, container should have a bounds of { x: 10, y: 20, width: 100, height: 100 }354 const r = container.containsPoint({ x: 105, y: 110 });355 expect(r).to.equal(true);356 });357 it('should include descendant transformation when resolving collision', () => {358 container = createContainer({ collider: { type: 'bounds' } });359 const rect = createRect({360 x: 0,361 y: 0,362 width: 100,363 height: 100,364 transform: 'translate(10, 20)'365 });366 container.addChild(rect);367 // After transform, container should have a bounds of { x: 10, y: 20, width: 100, height: 100 }368 rect.resolveGlobalTransform();369 const r = container.containsPoint({ x: 105, y: 110 });370 expect(r).to.equal(true);371 });372 it('should include self and descendant transformation when resolving collision', () => {373 container = createContainer({ transform: 'translate(-100, -100)', collider: { type: 'bounds' } });374 const rect = createRect({375 x: 0,376 y: 0,377 width: 100,378 height: 100,379 transform: 'translate(10, 20)'380 });381 container.addChild(rect);382 // After transform, container should have a bounds of { x: -90, y: -80, width: 100, height: 100 }383 rect.resolveGlobalTransform();384 expect(container.containsPoint({ x: -10, y: -20 })).to.true;385 expect(container.containsPoint({ x: 20, y: 30 })).to.false;386 });387 it('should include ancestors transformation when resolving collision', () => {388 const ancestor = createContainer({ transform: 'translate(-100, -100)' });389 const rect = createRect({390 x: 0,391 y: 0,392 width: 100,393 height: 100394 });395 container = createContainer({ collider: { type: 'bounds' } });396 container.addChild(rect);397 ancestor.addChild(container);398 // After transform, container should have a bounds of { x: -100, y: -100, width: 100, height: 100 }399 rect.resolveGlobalTransform();400 expect(container.containsPoint({ x: -10, y: -20 })).to.true;401 expect(container.containsPoint({ x: 20, y: 30 })).to.false;402 });403 it('should return true if custom collider contains point', () => {404 container = createContainer({405 collider: {406 type: 'rect', x: 0, y: 0, width: 100, height: 100407 }408 });409 container.addChild(createRect({410 x: 0, y: 0, width: 100, height: 100411 }));412 container.addChild(createRect({413 x: 1500, y: 1500, width: 200, height: 200414 }));415 const r = container.containsPoint({ x: 2, y: 2 });416 expect(r).to.equal(true);417 });418 it('should return true if frontChild contains point', () => {419 container = createContainer({ collider: { type: 'frontChild' } });420 container.addChild(createRect({421 x: 0, y: 0, width: 100, height: 100422 }));423 container.addChild(createRect({424 x: 1500, y: 1500, width: 200, height: 200425 }));426 const r = container.containsPoint({ x: 2, y: 2 });427 expect(r).to.equal(true);428 });429 });430 describe('intersectsLine', () => {431 it('should return true if any child intersects line', () => {432 container = createContainer();433 container.addChild(createRect({434 x: 500, y: 500, width: 100, height: 100435 }));436 container.addChild(createRect({437 x: 500, y: 500, width: 200, height: 200438 }));439 const r = container.intersectsLine({440 x1: 550, y1: 550, x2: 0, y2: 0441 });442 expect(r).to.equal(true);443 });444 it('should return true if any childs child intersects line', () => {445 container = createContainer();446 container.addChild(createRect({447 x: 500, y: 500, width: 100, height: 100448 }));449 container.addChild(createRect({450 x: 500, y: 500, width: 200, height: 200451 }));452 const childContainer = createContainer();453 childContainer.addChild(createRect({454 x: 0, y: 0, width: 200, height: 200455 }));456 childContainer.addChild(createRect({457 x: 1500, y: 1500, width: 200, height: 200458 }));459 container.addChild(childContainer);460 const r = container.intersectsLine({461 x1: 1550, y1: 1550, x2: 2000, y2: 2000462 });463 expect(r).to.equal(true);464 });465 it('should return false if no child intersects line', () => {466 container = createContainer();467 container.addChild(createRect({468 x: 500, y: 500, width: 100, height: 100469 }));470 container.addChild(createRect({471 x: 500, y: 500, width: 200, height: 200472 }));473 const childContainer = createContainer();474 childContainer.addChild(createRect({475 x: 1500, y: 1500, width: 200, height: 200476 }));477 const r = container.intersectsLine({478 x1: 2, y1: 2, x2: 0, y2: 0479 });480 expect(r).to.equal(false);481 });482 it('should return true if bounds intersects line', () => {483 container = createContainer({ collider: { type: 'bounds' } });484 container.addChild(createRect({485 x: 0, y: 0, width: 100, height: 100486 }));487 container.addChild(createRect({488 x: 1500, y: 1500, width: 200, height: 200489 }));490 const r = container.intersectsLine({491 x1: 2, y1: 2, x2: 0, y2: 0492 });493 expect(r).to.equal(true);494 });495 it('should return true if custom collider intersects line', () => {496 container = createContainer({497 collider: {498 type: 'rect', x: 0, y: 0, width: 100, height: 100499 }500 });501 container.addChild(createRect({502 x: 0, y: 0, width: 100, height: 100503 }));504 container.addChild(createRect({505 x: 1500, y: 1500, width: 200, height: 200506 }));507 const r = container.intersectsLine({508 x1: 2, y1: 2, x2: 0, y2: 0509 });510 expect(r).to.equal(true);511 });512 it('should return true if frontChild intersects line', () => {513 container = createContainer({ collider: { type: 'frontChild' } });514 container.addChild(createRect({515 x: 0, y: 0, width: 100, height: 100516 }));517 container.addChild(createRect({518 x: 1500, y: 1500, width: 200, height: 200519 }));520 const r = container.intersectsLine({521 x1: 2, y1: 2, x2: 0, y2: 0522 });523 expect(r).to.equal(true);524 });525 });526 describe('intersectsRect', () => {527 it('should return true if any child intersects rect', () => {528 container = createContainer();529 container.addChild(createRect({530 x: 500, y: 500, width: 100, height: 100531 }));532 container.addChild(createRect({533 x: 500, y: 500, width: 200, height: 200534 }));535 const r = container.intersectsRect({536 x: 550, y: 550, width: 100, height: 100537 });538 expect(r).to.equal(true);539 });540 it('should return true if bounds intersects rect', () => {541 container = createContainer({ collider: { type: 'bounds' } });542 container.addChild(createRect({543 x: 0, y: 0, width: 100, height: 100544 }));545 container.addChild(createRect({546 x: 1500, y: 1500, width: 200, height: 200547 }));548 const r = container.intersectsRect({549 x: 550, y: 550, width: 100, height: 100550 });551 expect(r).to.equal(true);552 });553 it('should return true if custom collider intersects rect', () => {554 container = createContainer({555 collider: {556 type: 'rect', x: 0, y: 0, width: 100, height: 100557 }558 });559 container.addChild(createRect({560 x: 0, y: 0, width: 100, height: 100561 }));562 container.addChild(createRect({563 x: 1500, y: 1500, width: 200, height: 200564 }));565 const r = container.intersectsRect({566 x: 2, y: 2, width: 2, height: 2567 });568 expect(r).to.equal(true);569 });570 it('should return true if frontChild intersects rect', () => {571 container = createContainer({ collider: { type: 'frontChild' } });572 container.addChild(createRect({573 x: 0, y: 0, width: 100, height: 100574 }));575 container.addChild(createRect({576 x: 1500, y: 1500, width: 200, height: 200577 }));578 const r = container.intersectsRect({579 x: 20, y: 20, width: 2, height: 2580 });581 expect(r).to.equal(true);582 });583 it('should return true if any childs child intersects rect', () => {584 container = createContainer();585 container.addChild(createRect({586 x: 500, y: 500, width: 100, height: 100587 }));588 container.addChild(createRect({589 x: 500, y: 500, width: 200, height: 200590 }));591 const childContainer = createContainer();592 childContainer.addChild(createRect({593 x: 0, y: 0, width: 200, height: 200594 }));595 childContainer.addChild(createRect({596 x: 1500, y: 1500, width: 200, height: 200597 }));598 container.addChild(childContainer);599 const r = container.intersectsRect({600 x: 1550, y: 1550, width: 100, height: 100601 });602 expect(r).to.equal(true);603 });604 it('should return false if no child intersects rect', () => {605 container = createContainer();606 container.addChild(createRect({607 x: 500, y: 500, width: 100, height: 100608 }));609 container.addChild(createRect({610 x: 500, y: 500, width: 200, height: 200611 }));612 const childContainer = createContainer();613 childContainer.addChild(createRect({614 x: 1500, y: 1500, width: 200, height: 200615 }));616 const r = container.intersectsRect({617 x: 0, y: 0, width: 100, height: 100618 });619 expect(r).to.equal(false);620 });621 });622 describe('intersectsCircle', () => {623 it('should return true if any child intersects circle', () => {624 container = createContainer();625 container.addChild(createRect({626 x: 500, y: 500, width: 100, height: 100627 }));628 container.addChild(createRect({629 x: 500, y: 500, width: 200, height: 200630 }));631 const r = container.intersectsCircle({ x: 550, y: 550, r: 10 });632 expect(r).to.equal(true);633 });634 it('should return true if bounds intersects circle', () => {635 container = createContainer({ collider: { type: 'bounds' } });636 container.addChild(createRect({637 x: 0, y: 0, width: 100, height: 100638 }));639 container.addChild(createRect({640 x: 1500, y: 1500, width: 200, height: 200641 }));642 const r = container.intersectsCircle({ x: 550, y: 550, r: 100 });643 expect(r).to.equal(true);644 });645 it('should return true if custom collider intersects circle', () => {646 container = createContainer({647 collider: {648 type: 'rect', x: 0, y: 0, width: 100, height: 100649 }650 });651 container.addChild(createRect({652 x: 0, y: 0, width: 100, height: 100653 }));654 container.addChild(createRect({655 x: 1500, y: 1500, width: 200, height: 200656 }));657 const r = container.intersectsCircle({ x: 2, y: 2, r: 2 });658 expect(r).to.equal(true);659 });660 it('should return true if frontChild intersects circle', () => {661 container = createContainer({ collider: { type: 'frontChild' } });662 container.addChild(createRect({663 x: 0, y: 0, width: 100, height: 100664 }));665 container.addChild(createRect({666 x: 1500, y: 1500, width: 200, height: 200667 }));668 const r = container.intersectsCircle({ x: 20, y: 20, r: 2 });669 expect(r).to.equal(true);670 });671 it('should return true if any childs child intersects circle', () => {672 container = createContainer();673 container.addChild(createRect({674 x: 500, y: 500, width: 100, height: 100675 }));676 container.addChild(createRect({677 x: 500, y: 500, width: 200, height: 200678 }));679 const childContainer = createContainer();680 childContainer.addChild(createRect({681 x: 0, y: 0, width: 200, height: 200682 }));683 childContainer.addChild(createRect({684 x: 1500, y: 1500, width: 200, height: 200685 }));686 container.addChild(childContainer);687 const r = container.intersectsCircle({ x: 1550, y: 1550, r: 100 });688 expect(r).to.equal(true);689 });690 it('should return false if no child intersects circle', () => {691 container = createContainer();692 container.addChild(createRect({693 x: 500, y: 500, width: 100, height: 100694 }));695 container.addChild(createRect({696 x: 500, y: 500, width: 200, height: 200697 }));698 const childContainer = createContainer();699 childContainer.addChild(createRect({700 x: 1500, y: 1500, width: 200, height: 200701 }));702 const r = container.intersectsCircle({ x: 0, y: 0, r: 100 });703 expect(r).to.equal(false);704 });705 });706 describe('getItemsFrom', () => {707 it('should return an empty array if call has no argument', () => {708 container = createContainer();709 container.addChild(createRect({710 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'711 }));712 container.addChild(createRect({713 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'714 }));715 const items = container.getItemsFrom();716 expect(items).to.be.empty;717 });718 it('should return an empty array if call argument is an empty object', () => {719 container = createContainer();720 container.addChild(createRect({721 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'722 }));723 container.addChild(createRect({724 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'725 }));726 const items = container.getItemsFrom({});727 expect(items).to.be.empty;728 });729 it('should return an empty array if call argument is null', () => {730 container = createContainer();731 container.addChild(createRect({732 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'733 }));734 container.addChild(createRect({735 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'736 }));737 const items = container.getItemsFrom(null);738 expect(items).to.be.empty;739 });740 it('should return an empty array if call argument shape is not supported', () => {741 container = createContainer();742 container.addChild(createRect({743 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'744 }));745 container.addChild(createRect({746 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'747 }));748 const items = container.getItemsFrom({749 a: 1, b: 2, c: 20, width: 20750 });751 expect(items).to.be.empty;752 });753 describe('Bounds', () => {754 it('should return the bounding node', () => {755 container = createContainer({ collider: { type: 'bounds' }, fill: 'container' });756 container.addChild(createRect({757 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'758 }));759 container.addChild(createRect({760 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'761 }));762 const items = container.getItemsFrom({ x: 550, y: 550 });763 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['container']);764 });765 it('should include childrens children', () => {766 container = createContainer({ collider: { type: 'bounds' }, fill: 'container' });767 container.addChild(createRect({768 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'769 }));770 container.addChild(createRect({771 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'772 }));773 const childContainer = createContainer({ fill: 'childContainer' });774 childContainer.addChild(createRect({775 x: 1500, y: 1500, width: 200, height: 200, fill: 'containerRect3'776 }));777 container.addChild(childContainer);778 const items = container.getItemsFrom({ x: 1550, y: 1550 });779 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['container']);780 });781 it('should return empty result if no collision is detected', () => {782 container = createContainer({ collider: { type: 'bounds' }, fill: 'container' });783 container.addChild(createRect({784 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'785 }));786 container.addChild(createRect({787 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'788 }));789 const items = container.getItemsFrom({ x: 400, y: 450 });790 expect(items).to.be.empty;791 });792 it('should handle polygon as input shape', () => {793 container = createContainer({ collider: { type: 'bounds' }, fill: 'container' });794 container.addChild(createRect({795 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'796 }));797 container.addChild(createRect({798 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'799 }));800 const vertices = [801 { x: 0, y: 0 },802 { x: 500, y: 550 },803 { x: 600, y: 50 }804 ];805 const items = container.getItemsFrom({ vertices });806 expect(items).to.not.be.empty;807 });808 });809 describe('FrontChild', () => {810 it('should return the first colliding child node', () => {811 container = createContainer({ collider: { type: 'frontChild' }, fill: 'container' });812 container.addChild(createRect({813 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'814 }));815 container.addChild(createRect({816 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'817 }));818 const items = container.getItemsFrom({ x: 550, y: 550 });819 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect2']);820 });821 it('should include childrens children', () => {822 container = createContainer({ collider: { type: 'frontChild' }, fill: 'container' });823 container.addChild(createRect({824 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'825 }));826 container.addChild(createRect({827 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'828 }));829 const childContainer = createContainer({ fill: 'childContainer' });830 childContainer.addChild(createRect({831 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect3'832 }));833 container.addChild(childContainer);834 const items = container.getItemsFrom({ x: 550, y: 550 });835 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect3']);836 });837 it('should ignore children with no collider', () => {838 container = createContainer({ collider: { type: 'frontChild' }, fill: 'container' });839 container.addChild(createRect({840 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'841 }));842 container.addChild(createRect({843 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2', collider: { type: null }844 }));845 const items = container.getItemsFrom({ x: 550, y: 550 });846 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect1']);847 });848 it('should return empty result if there are no children', () => {849 container = createContainer({ collider: { type: 'frontChild' }, fill: 'container' });850 const items = container.getItemsFrom({ x: 550, y: 550 });851 expect(items).to.be.empty;852 });853 });854 describe('Default collider', () => {855 it('should return the all colliding child nodes', () => {856 container = createContainer({ fill: 'container' });857 container.addChild(createRect({858 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'859 }));860 container.addChild(createRect({861 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'862 }));863 container.addChild(createRect({864 x: 1500, y: 1500, width: 200, height: 200, fill: 'containerRect3'865 }));866 const items = container.getItemsFrom({ x: 550, y: 550 });867 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect1', 'containerRect2']);868 });869 it('should include childrens children', () => {870 container = createContainer({ fill: 'container' });871 container.addChild(createRect({872 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'873 }));874 container.addChild(createRect({875 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'876 }));877 const childContainer = createContainer({ fill: 'childContainer' });878 childContainer.addChild(createRect({879 x: 1500, y: 1500, width: 200, height: 200, fill: 'containerRect3'880 }));881 container.addChild(childContainer);882 const items = container.getItemsFrom({ x: 1550, y: 1550 });883 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect3']);884 });885 it('should return ignore children with no collider', () => {886 container = createContainer({ fill: 'container' });887 container.addChild(createRect({888 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'889 }));890 container.addChild(createRect({891 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2', collider: { type: null }892 }));893 const items = container.getItemsFrom({ x: 550, y: 550 });894 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['containerRect1']);895 });896 it('should return empty result if there are no children', () => {897 container = createContainer({ fill: 'container' });898 const items = container.getItemsFrom({ x: 550, y: 550 });899 expect(items).to.be.empty;900 });901 it('should return empty result if there are no colliding children', () => {902 container = createContainer({ fill: 'container' });903 container.addChild(createRect({904 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'905 }));906 container.addChild(createRect({907 x: 500, y: 500, width: 200, height: 200, fill: 'containerRect2'908 }));909 const items = container.getItemsFrom({ x: 450, y: 450 });910 expect(items).to.be.empty;911 });912 });913 describe('Custom collider', () => {914 it('should return the colliding container', () => {915 container = createContainer({916 collider: {917 type: 'rect', x: 500, y: 500, width: 100, height: 100918 },919 fill: 'container'920 });921 container.addChild(createRect({922 x: 0, y: 0, width: 100, height: 100, fill: 'containerRect1'923 }));924 const items = container.getItemsFrom({ x: 550, y: 550 });925 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['container']);926 });927 it('should return the colliding container if child collider also matches', () => {928 container = createContainer({929 collider: {930 type: 'rect', x: 500, y: 500, width: 100, height: 100931 },932 fill: 'container'933 });934 container.addChild(createRect({935 x: 500, y: 500, width: 100, height: 100, fill: 'containerRect1'936 }));937 const items = container.getItemsFrom({ x: 550, y: 550 });938 expect(items.map(i => i.node.attrs.fill)).to.deep.equal(['container']);939 });940 it('should not collide if custom collider doesnt but child collider does', () => {941 container = createContainer({942 collider: {943 type: 'rect', x: 500, y: 500, width: 100, height: 100944 },945 fill: 'container'946 });947 container.addChild(createRect({948 x: 0, y: 0, width: 100, height: 100, fill: 'containerRect1'949 }));950 const childContainer = createContainer({ collider: { type: 'bounds' }, fill: 'childContainer' });951 childContainer.addChild(createRect({952 x: 0, y: 0, width: 200, height: 200, fill: 'containerRect2'953 }));954 const items = container.getItemsFrom({ x: 10, y: 10 });955 expect(items).to.be.empty;956 });957 it('should return empty result if no collision is detected', () => {958 container = createContainer({959 collider: {960 type: 'rect', x: 500, y: 500, width: 100, height: 100961 },962 fill: 'containerBounds'963 });964 const items = container.getItemsFrom({ x: 400, y: 450 });965 expect(items).to.be.empty;966 });967 });968 });...
test_container.js
Source:test_container.js
...104 });105 });106 describe('.state', () => {107 it("Should be an object.", () => {108 const container = createContainer();109 assert('object' == typeof container.state);110 });111 it("Should be a cloned object.", () => {112 const container = createContainer();113 const a = container.state;114 const b = container.state;115 assert('object' == typeof a);116 assert('object' == typeof b);117 assert(a != b);118 });119 it("Should be immutable.", done => {120 const container = createContainer();121 const value = {foo: 'bar'};122 try { container.state = value; }123 catch (e) {124 assert(undefined === container.state.foo);125 done();126 }127 });128 });129 describe('.id', () => {130 it("Should be a string.", () => {131 const container = createContainer();132 assert('string' == typeof container.id);133 });134 it("Should be immutable.", done => {135 const container = createContainer();136 const id = container.id;137 try { container.id = '123'; }138 catch (e) {139 assert(container.id == id);140 done();141 }142 });143 });144 describe('.parent', () => {145 it("Should be null when container is an orphaned.", () => {146 const container = createContainer();147 assert(null == container.parent);148 });149 it("Should derive parent from parent DOM element.", () => {150 const parent = createContainer();151 const child = createContainer();152 parent.appendChild(child);153 assert(parent == child.parent);154 });155 it("Should derive parent from parent DOM element from existing DOM tree.", () => {156 const tree = document.createElement('div');157 tree.innerHTML = '<div><span></span></div>';158 const container = createContainer(tree.children[0]); // div159 const child = createContainer(tree.children[0].children[0]);160 assert(container == child.parent);161 });162 });163 describe('.domElement', () => {164 it("Should be an instance of Element", () => {165 const container = createContainer();166 assert(container.domElement instanceof Element);167 });168 it("Should be mutable effectively replacing the container DOM element.", () => {169 const container = createContainer();170 const domElement = document.createElement('span');171 domElement.innerHTML = 'hello ${name}';172 container.domElement = domElement;173 assert(domElement == container.domElement);174 container.update({name: 'kinkajou'});175 assert('hello kinkajou' == domElement.innerHTML);176 assert('hello kinkajou' == container.domElement.innerHTML);177 });178 it("Should throw a TypeError when value set is not a DOM element.", done => {179 const container = createContainer();180 try {181 container.domElement = 'foo';182 throw new Error("Error not thrown.");183 } catch (e) {184 assert(e instanceof TypeError);185 done();186 }187 });188 });189 describe('.innerContents', () => {190 it("Should be a string.", () => {191 const container = createContainer();192 assert('string' == typeof container.innerContents);193 });194 it("Should be a string representation of the containers DOM element.", () => {195 const container = createContainer();196 container.domElement.innerHTML = 'hello';197 assert('hello' == container.innerContents);198 });199 });200 describe('.children', () => {201 it("Should return an array of child containers.", () => {202 const container = new Container();203 const childA = new Container();204 const childB = new Container();205 container.appendChild(childA);206 container.appendChild(childB);207 const children = container.children;208 assert(children);209 assert(childA == children[0]);210 assert(childB == children[1]);211 });212 });213 describe('#define(model)', () => {214 it("Should extend the container state object.", () => {215 const container = new Container();216 container.define({key: 'value'});217 assert('value' == container.state.key);218 });219 });220 describe('#use(...plugins)', () => {221 it("Should install reducer middleware.", done => {222 done = once(done);223 const container = new Container();224 container.use(() => done());225 container.update();226 });227 });228 describe('#update(data[, propagate = true]', () => {229 it("Should update internal state.", () => {230 const container = new Container();231 container.update({value: 123});232 assert(123 == container.state.value);233 });234 it("Should propagate changes to child containers.", () => {235 const container = new Container();236 const childA = new Container();237 const childAA = new Container();238 const childB = new Container();239 container.appendChild(childA);240 container.appendChild(childB);241 childA.appendChild(childAA);242 assert(childA.children.length)243 container.update({value: 123});244 assert(123 == container.state.value);245 assert(123 == childA.state.value);246 assert(123 == childAA.state.value);247 assert(123 == childB.state.value);248 });249 it("Should only update the container and not children when `propagate = false`.", () => {250 const container = new Container();251 const childA = new Container();252 const childB = new Container();253 container.appendChild(childA);254 container.appendChild(childB);255 container.update({value: 123}, false);256 assert(123 == container.state.value);257 assert(!childA.state.value);258 assert(!childB.state.value);259 });260 it("Should dispatch `stardux.UPDATE` event type in a reducer.", done => {261 done = once(done);262 const container = new Container(null, (state, action) => {263 if (stardux.UPDATE == action.type) done();264 return {};265 });266 container.update();267 });268 });269 describe('#render(domElement)', () => {270 it("Should render the container to a given DOM element.", () => {271 const container = new Container();272 const domElement = document.createElement('div');273 container.render(domElement);274 assert(domElement.contains(container.domElement));275 });276 });277 describe('#dispatch(type[, data = {}, args = {}])', () => {278 it("Should dispatch any arbitrary event type and propagate to a reducer.", done => {279 done = once(done);280 const type = Symbol('foo');281 const container = new Container(null, (state, action) => {282 if (type == action.type) done();283 return {};284 });285 container.dispatch(type);286 });287 });288 describe('#replaceChildren(children)', () => {289 it("Should remove all existing children and append new ones.", () => {290 const container = new Container();291 const childA = new Container();292 const childB = new Container();293 const childC = new Container();294 const childX = new Container();295 const childY = new Container();296 const childZ = new Container();297 container.update();298 container.appendChild(childA);299 container.appendChild(childB);300 container.appendChild(childC);301 assert(container.contains(childA));302 assert(container.contains(childB));303 assert(container.contains(childC));304 container.replaceChildren([childX, childY, childZ]);305 assert(false == container.contains(childA));306 assert(false == container.contains(childB));307 assert(false == container.contains(childC));308 assert(container.contains(childX));309 assert(container.contains(childY));310 assert(container.contains(childZ));311 });312 });313 describe('#valueOf()', () => {314 it("Should return the underlying DOM element.", () => {315 const container = new Container();316 assert(container.valueOf() instanceof Element);317 })318 });319 describe('#toString()', () => {320 it("Should return a text representation of the container contents.", () => {321 const container = new Container();322 container.innerContents = '${value}';323 container.update({value: 'hello'});324 assert('hello' == String(container));325 container.update({value: 'kinkajou'});326 assert('kinkajou' == String(container));327 });328 });329 describe('#toJSON()', () => {330 it("Should return a JSON object representation.", () => {331 const container = new Container();332 container.innerContents = 'hello ${value}';333 container.update({value: 'world'});334 const json = container.toJSON();335 assert('object' == typeof json);336 assert(json.id);337 assert(json.src);338 assert(json.state);339 assert(json.children);340 });341 });342 describe('#pipe(container)', () => {343 it("Should pipe update to another container.", done => {344 done = once(done);345 const containerA = new Container();346 const containerB = new Container();347 containerA.pipe(containerB);348 containerB.use(_ => done());349 containerA.update();350 });351 });352 describe('#unpipe(container)', () => {353 it("Should unpipe containers.", () => {354 const containerA = new Container();355 const containerB = new Container();356 containerA.pipe(containerB);357 containerB.use(_ => { throw new Error("Unpipe failed."); });358 containerA.unpipe(containerB);359 containerA.update();360 });361 });362 describe('#appendChild(child)', () => {363 it("Should append a child container.", () => {364 const container = new Container();365 const child = new Container();366 container.appendChild(child);367 assert(container.children[0] == child);368 assert(container.children[0].domElement == child.domElement);369 });370 });371 describe('#removeChild(child)', () => {372 it("Should remove a child container.", () => {373 const container = new Container();374 const child = new Container();375 container.appendChild(child);376 assert(container.children[0] == child);377 container.removeChild(child);378 assert(container.children[0] != child);379 assert(0 == container.children.length);380 });381 });382 describe('#contains(container[, recursive = true])', () => {383 it("Should return true or false if a container is a child or not.", () => {384 const container = new Container();385 const child = new Container();386 const other = new Container();387 container.appendChild(child);388 assert(container.contains(child));389 assert(false == container.contains(other));390 });391 it("Should only search direct descendants if [recursive = false].", () => {392 const container = new Container();393 const child = new Container();394 const other = new Container();395 container.appendChild(child);396 child.appendChild(other);397 assert(container.contains(child));398 assert(container.contains(other));399 assert(false == container.contains(other, false));400 });401 });402});403describe('createContainer([domElement = null, initialState = {}, ...reducers]', () => {404 it("Should create an instance of a Container", () => {405 assert(createContainer() instanceof Container);406 });407 it("Should create a container with a default DOM Element.", () => {408 const container = createContainer();409 assert(container);410 assert(container.domElement instanceof Element);411 });412 it("Should create a container with a given DOM Element.", () => {413 const domElement = document.createElement('div');414 const container = createContainer(domElement);415 assert(container);416 assert(domElement == container.domElement);417 });418 it("Should create a container with initial state.", () => {419 const container = createContainer(null, {value: 123});420 assert(container);421 assert(123 == container.state.value);422 });423 it("Should return an existing container for an already wrapped " +424 "DOM Element.", () => {425 const domElement = document.createElement('div');426 const container = createContainer(domElement);427 const duplicate = createContainer(domElement);428 assert(container);429 assert(duplicate);430 assert(duplicate.domElement == container.domElement);431 assert(duplicate === container);432 });433 it("Should return an existing container for an already existing " +434 "container.", () => {435 const container = createContainer();436 const duplicate = createContainer(container);437 assert(container);438 assert(duplicate);439 assert(duplicate.domElement == container.domElement);440 assert(duplicate === container);441 });442 it("Should apply a set of given reducers.", done => {443 done = once(done);444 const called = [0, 0, 0, 0];445 const container = createContainer(null, null,446 (state, action) => (called[0] = true),447 (state, action) => (called[1] = true),448 (state, action) => (called[2] = true),449 (state, action) => (called[3] = true),450 (state, action) => {451 assert(called.every(Boolean),452 "Missing reducer call.");453 done();454 return {};455 });456 });457});458describe('makeContainer(domElement)', () => {459 it("Should make a container from a DOM element.", () => {460 const domElement = document.createElement('div');461 const container = makeContainer(domElement);462 assert(container);463 assert(container.domElement == domElement);464 });465});466describe('restoreContainerFromJSON(object)', () => {467 it("Should be able to restore a container from a JSON structure.", () => {468 const container = createContainer();469 const json = JSON.stringify(container);470 const restored = restoreContainerFromJSON(JSON.parse(json));471 assert(restored.id == container.id)472 // prevents copies and returns existing if still in memory473 assert(restored == container,474 "Failed to restore existing container.");475 });476 it("Should be able to create a new container from a JSON structure.", () => {477 const id = '.81b55b8d'478 const str = `{"id":"${id}","src":"","state":{"value":123},"children":[]}`479 const json = JSON.parse(str);480 const container = restoreContainerFromJSON(json);481 assert(container);482 assert(id == container.id);483 });484 it("Should be able to restore a container with new initial state.", () => {485 const container = createContainer(null, {value: 123});486 const json = JSON.stringify(container);487 const restored = restoreContainerFromJSON(JSON.parse(json), {other: 456});488 assert(restored.id == container.id)489 assert(restored == container, "Failed to restore existing container.");490 assert(123 == restored.state.value);491 assert(456 == restored.state.other);492 });493});494describe('composeContainers([...containers]', () => {495 it("Should return a new Container instance with no arguments.", () => {496 const composite = composeContainers();497 assert(composite);498 });499 it("Should use the first argument as the root composite.", () => {500 const container = createContainer();501 const composite = composeContainers(container);502 assert(composite);503 assert(composite == container);504 });505 it("Should create a new container when given an array of containers.", done => {506 done = once(done);507 const containerA = createContainer();508 const containerB = createContainer();509 const composite = composeContainers([containerA, containerB]);510 assert(composite);511 containerB.use(_ => done());512 composite.update();513 });514 it("Should return a root container with chained containers.", done => {515 done = once(done);516 const root = createContainer();517 const containerA = createContainer();518 const containerB = createContainer();519 const composite = composeContainers(root, containerA, containerB);520 assert(composite);521 assert(composite == root);522 containerB.use(_ => done());523 root.update();524 });525});526describe('getContainerData([container | id | domElement])', () => {527 it("Should return null for DOM Elements that have not been claimed by a container.", () => {528 const domElement = document.createElement('div');529 const data = getContainerData(domElement);530 assert(null == data);531 });532 it("Should return data for a DOM Element claimed by a container.", () => {533 const domElement = document.createElement('div');534 const container = createContainer(domElement);535 const data = getContainerData(domElement);536 assert(data);537 assert(data.id == container.id);538 });539 it("Should return data for an existing container.", () => {540 const domElement = document.createElement('div');541 const container = createContainer(domElement);542 const data = getContainerData(container);543 assert(data);544 assert(data.id == container.id);545 });546 it("Should return data for an existing container by id.", () => {547 const domElement = document.createElement('div');548 const container = createContainer(domElement);549 const data = getContainerData(container.id);550 assert(data);551 assert(data.id == container.id);552 });553});554describe('restoreOrphanedTree(container | domElement)', () => {555 it("Should restore orphaned containers DOM elements", () => {556 const domElement = document.createElement('div');557 const childDomElementA = document.createElement('div');558 const childDomElementB = document.createElement('div');559 const container = createContainer(domElement);560 const childContainerA = createContainer(childDomElementA);561 const childContainerB = createContainer(childDomElementB);562 container.appendChild(childContainerA);563 container.appendChild(childContainerB);564 assert(container.contains(childContainerA));565 assert(container.contains(childContainerB));566 domElement.removeChild(childDomElementA);567 domElement.removeChild(childDomElementB);568 assert(container.contains(childContainerA, false));569 assert(container.contains(childContainerB, false));570 assert(false == domElement.contains(childDomElementA));571 assert(false == domElement.contains(childDomElementB));572 restoreOrphanedTree(container);573 assert(domElement.contains(childDomElementA));574 assert(domElement.contains(childDomElementB));575 assert(container.contains(childContainerA));576 assert(container.contains(childContainerB));577 });578});579/**580 * Tests container tree realignment.581 */582describe('realignContainerTree(container[, recursive = false])', () => {583 it("Should realign an unaligned container tree by restoring lost DOM elements.", () => {584 const domElement = document.createElement('div');585 const childDomElementA = document.createElement('div');586 const childDomElementB = document.createElement('div');587 const container = createContainer(domElement);588 const childContainerA = createContainer(childDomElementA);589 const childContainerB = createContainer(childDomElementB);590 container.appendChild(childContainerA);591 container.appendChild(childContainerB);592 assert(container.contains(childContainerA));593 assert(container.contains(childContainerB));594 // child DOM element is removed but the container will595 // still reference a child container596 domElement.removeChild(childDomElementB);597 assert(false == domElement.contains(childDomElementB));598 assert(container.contains(childContainerB));599 // realign container tree force lost node to be restored600 realignContainerTree(container);601 assert(domElement.contains(childDomElementB));602 });603 it("Should recursively realign a container tree.", () => {604 const domElement = document.createElement('div');605 const childDomElementA = document.createElement('div');606 const childDomElementAA = document.createElement('div');607 const container = createContainer(domElement);608 const childContainerA = createContainer(childDomElementA);609 const childContainerAA = createContainer(childDomElementAA);610 container.appendChild(childContainerA);611 childContainerA.appendChild(childContainerAA);612 assert(container.contains(childContainerA));613 assert(childContainerA.contains(childContainerAA));614 childDomElementA.removeChild(childDomElementAA);615 assert(false == childDomElementA.contains(childDomElementAA));616 assert(childContainerA.contains(childContainerAA));617 realignContainerTree(container, true);618 assert(childDomElementA.contains(childDomElementAA));619 });620});621describe('replaceDOMElement(container, domElement)', () => {622 it("Should replace the internal DOM element associated witht the container.", () => {623 const domElement = document.createElement('div');624 const container = createContainer();625 assert(container.domElement);626 replaceDOMElement(container, domElement);627 assert(domElement == container.domElement);628 });629});630describe('createContainerUid()', () => {631 it("Should return a string.", () => {632 assert('string' == typeof createContainerUid());633 });634 it("Should return a UID prefixed with a '.'.", () => {635 assert('.' == createContainerUid()[0]);636 });637});638describe('getAllContainers()', () => {639 it("Should return all created containers.", () => {640 const a = createContainer();641 const b = createContainer();642 const c = createContainer();643 const containers = [ ...getAllContainers() ].map(_ => _[1]); // [id, container]644 assert(containers.indexOf(a) > -1);645 assert(containers.indexOf(b) > -1);646 assert(containers.indexOf(c) > -1);647 });648});649describe('fetchContainer(container | domElement | id)', () => {650 it("Should return a container if a container is given.", () => {651 const container = createContainer();652 assert(container == fetchContainer(container));653 });654 it("Should return a container if a DOM element is given.", () => {655 const container = createContainer();656 assert(container == fetchContainer(container.domElement));657 });658 it("Should return a container if a id is given.", () => {659 const container = createContainer();660 assert(container == fetchContainer(container.id));661 });662 it("Should return a container if an object with id is given.", () => {663 const container = createContainer();664 assert(container == fetchContainer({id: container.id}));665 });666});667describe('removeContainer(container | domElement | id)', () => {668 it("Should remove a container from its parent.", () => {669 const parent = createContainer();670 const child = createContainer();671 parent.appendChild(child);672 assert(true == removeContainer(child));673 assert(false == parent.contains(child));674 });675 it("Should remove a container from the internal tree.", () => {676 const container = createContainer();677 assert(true == removeContainer(container));678 const containers = [ ...getAllContainers() ];679 assert(0 == containers.length);680 });681 it("Should remove a container by a given DOM element.", () => {682 const container = createContainer();683 assert(true == removeContainer(container.domElement));684 const containers = [ ...getAllContainers() ];685 assert(0 == containers.length);686 });687 it("Should remove a container by a given id.", () => {688 const container = createContainer();689 assert(true == removeContainer(container.id));690 const containers = [ ...getAllContainers() ];691 assert(0 == containers.length);692 });693});694describe('saveContainer(container)', () => {695 it("Should save a container.", () => {696 const container = createContainer();697 // containers are saved automatically698 assert(true == removeContainer(container));699 assert(null == fetchContainer(container.id));700 assert(true === saveContainer(container));701 });702});703describe('clearContainers()', () => {704 it("Should clear all existing containers.", () => {705 const count = 10;706 for (let i = 0; i < count; ++i) createContainer();707 assert(count == [ ...getAllContainers() ].length);708 clearContainers();709 assert(0 == [ ...getAllContainers() ].length);710 });711});712describe('forEachContainer(fn[, scope])', () => {713 it("Should iterate over each container in the order in which they were created.", () => {714 const a = createContainer();715 const b = createContainer();716 const c = createContainer();717 const d = createContainer();718 const seen = [];719 forEachContainer(container => seen.push(container));720 assert(seen.length);721 assert(a == seen[0]);722 assert(b == seen[1]);723 assert(c == seen[2]);724 assert(d == seen[3]);725 });726 it("Should iterate over each container with an optional scope.", () => {727 const a = createContainer();728 const b = createContainer();729 const c = createContainer();730 const seen = [];731 forEachContainer(function (container) {732 assert(this == seen);733 this.push(container);734 }, seen);735 assert(seen.length);736 assert(a == seen[0]);737 assert(b == seen[1]);738 assert(c == seen[2]);739 });740});741describe('traverseContainer(container, fn[, scope])', () => {742 it("Should traverse a container's children.", () => {743 const root = createContainer();744 const a = createContainer();745 const b = createContainer();746 const c = createContainer();747 const d = createContainer();748 const e = createContainer();749 const seen = [];750 a.appendChild(c);751 a.appendChild(d);752 traverseContainer(a, container => seen.push(container));753 assert(seen.length);754 assert(c == seen[0]);755 assert(d == seen[1]);756 });757 it("Should traverse a container's children with an optional scope.", () => {758 const root = createContainer();759 const a = createContainer();760 const b = createContainer();761 const c = createContainer();762 const d = createContainer();763 const e = createContainer();764 const seen = [];765 a.appendChild(c);766 a.appendChild(d);767 traverseContainer(a, function (container) {768 assert(this == seen);769 this.push(container);770 }, seen);771 assert(seen.length);772 assert(c == seen[0]);773 assert(d == seen[1]);774 });...
Container.js
Source:Container.js
1topSuite('Ext.field.Container', ['Ext.JSON', 'Ext.field.Checkbox', 'Ext.field.Radio', 'Ext.field.Text'], function() {2 var ct;3 function createContainer(cfg) {4 if (Ext.isArray(cfg)) {5 cfg = {6 items: cfg7 };8 }9 return ct = new Ext.field.Container(Ext.apply({}, cfg));10 }11 afterEach(function() {12 ct = Ext.destroy(ct);13 });14 describe('proxied', function() {15 it('should have proxied container configs', function() {16 var proto = Ext.field.Container.prototype;17 expect(proto.hasConfig('defaults')).toBe(true);18 expect(proto.hasConfig('defaultType')).toBe(true);19 expect(proto.hasConfig('items')).toBe(true);20 expect(proto.hasConfig('layout')).toBe(true);21 expect(proto).toHaveProperties(22 'getDefaults', 'setDefaults',23 'getDefaultType', 'setDefaultType',24 'getItems', 'setItems',25 'getLayout', 'setLayout'26 );27 });28 it('should have proxied container methods', function() {29 var proto = Ext.field.Container.prototype;30 expect(proto).toHaveProperties('add', 'insert', 'remove', 'removeAll', 'getAt');31 });32 });33 describe('errorTarget', function() {34 it('should set errorTarget to "parent" of configured items', function() {35 createContainer([36 { label: 'foo', name: 'foo' },37 { label: 'bar', name: 'bar' },38 { label: 'baz', name: 'baz' }39 ]);40 var first = ct.getAt(0),41 second = ct.getAt(1),42 third = ct.getAt(2);43 expect(first.getErrorTarget()).toBe('parent');44 expect(second.getErrorTarget()).toBe('parent');45 expect(third.getErrorTarget()).toBe('parent');46 });47 it('should set errorTarget to null of added item', function() {48 createContainer();49 var item = ct.add({50 label: 'foo',51 name: 'foo'52 });53 expect(item.getErrorTarget()).toBe('parent');54 });55 it('should not set errorTarget of configured items', function() {56 createContainer([57 { label: 'foo', name: 'foo', errorTarget: 'qtip' },58 { label: 'bar', name: 'bar', errorTarget: 'side' },59 { label: 'baz', name: 'baz', errorTarget: 'under' }60 ]);61 var first = ct.getAt(0),62 second = ct.getAt(1),63 third = ct.getAt(2);64 expect(first.getErrorTarget()).toBe('qtip');65 expect(second.getErrorTarget()).toBe('side');66 expect(third.getErrorTarget()).toBe('under');67 });68 it('should not set errorTarget of added item', function() {69 createContainer();70 var item = ct.add({71 errorTarget: 'side',72 label: 'foo',73 name: 'foo'74 });75 expect(item.getErrorTarget()).toBe('side');76 });77 });78 describe('getValues', function() {79 it('should return an object as a value', function() {80 createContainer([81 { label: 'foo', name: 'foo', value: 'Foo' },82 { label: 'bar', name: 'bar', value: 'Bar' },83 { label: 'baz', name: 'baz', value: 'Baz' }84 ]);85 expect(ct.getValues()).toEqual({86 foo: 'Foo',87 bar: 'Bar',88 baz: 'Baz'89 });90 });91 it('should return an object as a value with checkboxfields', function() {92 createContainer([93 { label: 'foo', name: 'foo', value: 'Foo' },94 { xtype: 'checkboxfield', label: 'bar 1', name: 'bar', value: 'Bar 1', checked: true },95 { xtype: 'checkboxfield', label: 'bar 2', name: 'bar', value: 'Bar 2', checked: true },96 { label: 'baz', name: 'baz', value: 'Baz' }97 ]);98 expect(ct.getValues()).toEqual({99 foo: 'Foo',100 bar: ['Bar 1', 'Bar 2'],101 baz: 'Baz'102 });103 });104 it('should return an object as a value with radiofields', function() {105 createContainer([106 { label: 'foo', name: 'foo', value: 'Foo' },107 { xtype: 'radiofield', label: 'bar 1', name: 'bar', value: 'Bar 1' },108 { xtype: 'radiofield', label: 'bar 2', name: 'bar', value: 'Bar 2', checked: true },109 { label: 'baz', name: 'baz', value: 'Baz' }110 ]);111 expect(ct.getValues()).toEqual({112 foo: 'Foo',113 bar: 'Bar 2',114 baz: 'Baz'115 });116 });117 });118 describe('setValues', function() {119 it('should set values on all fields', function() {120 createContainer([121 { label: 'foo', name: 'foo' },122 { label: 'bar', name: 'bar' },123 { label: 'baz', name: 'baz' }124 ]);125 var first = ct.getAt(0),126 second = ct.getAt(1),127 third = ct.getAt(2),128 values = {129 foo: 'Foo',130 bar: 'Bar',131 baz: 'Baz'132 };133 expect(ct.setValues(values)).toBe(ct);134 expect(first.getValue()).toBe('Foo');135 expect(second.getValue()).toBe('Bar');136 expect(third.getValue()).toBe('Baz');137 });138 it('should set values on some fields', function() {139 createContainer([140 { label: 'foo', name: 'foo' },141 { label: 'bar', name: 'bar' },142 { label: 'baz', name: 'baz' }143 ]);144 var first = ct.getAt(0),145 second = ct.getAt(1),146 third = ct.getAt(2),147 values = {148 foo: 'Foo',149 baz: 'Baz'150 };151 expect(ct.setValues(values)).toBe(ct);152 expect(first.getValue()).toBe('Foo');153 expect(second.getValue()).toBeNull();154 expect(third.getValue()).toBe('Baz');155 });156 });157 describe('onFieldErrorChange', function() {158 it('should get called when a field is marked with error', function() {159 createContainer([160 { label: 'foo', name: 'foo' },161 { label: 'bar', name: 'bar' },162 { label: 'baz', name: 'baz' }163 ]);164 var first = ct.getAt(0),165 spy = spyOn(ct, 'onFieldErrorChange');166 first.setError(['test error']);167 expect(spy).toHaveBeenCalled();168 });169 });170 describe('getRefItems', function() {171 it('should find a field via down()', function() {172 var container = new Ext.Container({173 items: [174 {},175 {},176 createContainer([177 { label: 'foo', name: 'foo' },178 { label: 'bar', name: 'bar' },179 { label: 'baz', name: 'baz' }180 ]),181 {}182 ]183 }),184 field = container.down('textfield'),185 first = ct.getAt(0);186 expect(field).toBe(first);187 Ext.destroy(container);188 });189 it('should find all fields via query()', function() {190 var container = new Ext.Container({191 items: [192 {},193 {},194 createContainer([195 { label: 'foo', name: 'foo' },196 { label: 'bar', name: 'bar' },197 { label: 'baz', name: 'baz' }198 ]),199 {}200 ]201 }),202 fields = container.query('textfield'),203 first = ct.getAt(0),204 second = ct.getAt(1),205 third = ct.getAt(2);206 expect(fields).toEqual([207 first,208 second,209 third210 ]);211 Ext.destroy(container);212 });213 });214 describe('getFocusEl', function() {215 it('should get first field\'s focus element', function() {216 createContainer([217 { label: 'foo', name: 'foo' },218 { label: 'bar', name: 'bar' },219 { label: 'baz', name: 'baz' }220 ]);221 var first = ct.getAt(0);222 expect(ct.getFocusEl()).toBe(first.getFocusEl());223 });224 });225 describe('reset', function() {226 it('should reset all fields', function() {227 createContainer([228 { label: 'foo', name: 'foo' },229 { label: 'bar', name: 'bar', value: 'bar' }230 ]);231 var first = ct.getAt(0),232 second = ct.getAt(1);233 first.setValue('foo');234 second.setValue('foobar');235 expect(ct.reset()).toBe(ct);236 expect(first.getValue()).toBe('');237 expect(second.getValue()).toBe('bar');238 });239 });240 describe('setErrors', function() {241 it('should only mark specified fields when passing an object', function() {242 createContainer([243 { placeholder: 'foo', name: 'foo' },244 { placeholder: 'bar', name: 'bar' },245 { placeholder: 'baz', name: 'baz' }246 ]);247 var first = ct.getAt(0),248 second = ct.getAt(1),249 third = ct.getAt(2),250 error = {251 foo: 'Foo is in error',252 baz: 'Baz has an error'253 };254 expect(ct.setErrors(error)).toBe(ct);255 expect(ct.getError()).toEqual([256 {257 label: 'foo',258 error: 'Foo is in error'259 },260 {261 label: 'baz',262 error: 'Baz has an error'263 }264 ]);265 expect(first.getError()).toEqual(['Foo is in error']);266 expect(second.getError()).toBeNull();267 expect(third.getError()).toEqual(['Baz has an error']);268 });269 it('should only mark specified fields when passing an object with nested array', function() {270 createContainer([271 { placeholder: 'foo', name: 'foo' },272 { placeholder: 'bar', name: 'bar' },273 { placeholder: 'baz', name: 'baz' }274 ]);275 var first = ct.getAt(0),276 second = ct.getAt(1),277 third = ct.getAt(2),278 error = {279 foo: ['Foo is in error', 'Another Foo Error'],280 baz: 'Baz has an error'281 };282 expect(ct.setErrors(error)).toBe(ct);283 expect(ct.getError()).toEqual([284 {285 label: 'foo',286 error: 'Foo is in error'287 },288 {289 label: 'foo',290 error: 'Another Foo Error'291 },292 {293 label: 'baz',294 error: 'Baz has an error'295 }296 ]);297 expect(first.getError()).toEqual(['Foo is in error', 'Another Foo Error']);298 expect(second.getError()).toBeNull();299 expect(third.getError()).toEqual(['Baz has an error']);300 });301 it('should clear all field invalids', function() {302 createContainer([303 { label: 'foo', name: 'foo' },304 { label: 'bar', name: 'bar' },305 { label: 'baz', name: 'baz' }306 ]);307 var first = ct.getAt(0),308 second = ct.getAt(1),309 third = ct.getAt(2),310 errors = {311 foo: 'test error',312 bar: 'test error',313 baz: 'test error'314 };315 expect(ct.setErrors(errors)).toBe(ct);316 errors.foo = errors.bar = errors.baz = null;317 expect(ct.setErrors(errors)).toBe(ct);318 expect(ct.getError()).toBeNull();319 expect(first.getError()).toBeNull();320 expect(second.getError()).toBeNull();321 expect(third.getError()).toBeNull();322 });323 describe('with child errorTarget', function() {324 it('should only mark specified fields when passing an object', function() {325 createContainer([326 { placeholder: 'foo', name: 'foo', errorTarget: 'side' },327 { placeholder: 'bar', name: 'bar', errorTarget: 'side' },328 { placeholder: 'baz', name: 'baz', errorTarget: 'side' }329 ]);330 var first = ct.getAt(0),331 second = ct.getAt(1),332 third = ct.getAt(2),333 error = {334 foo: 'Foo is in error',335 baz: 'Baz has an error'336 };337 expect(ct.setErrors(error)).toBe(ct);338 expect(ct.getError()).toBeNull();339 expect(first.getError()).toEqual(['Foo is in error']);340 expect(second.getError()).toBeNull();341 expect(third.getError()).toEqual(['Baz has an error']);342 });343 it('should only mark specified fields when passing an object with nested array', function() {344 createContainer([345 { placeholder: 'foo', name: 'foo', errorTarget: 'side' },346 { placeholder: 'bar', name: 'bar', errorTarget: 'side' },347 { placeholder: 'baz', name: 'baz', errorTarget: 'side' }348 ]);349 var first = ct.getAt(0),350 second = ct.getAt(1),351 third = ct.getAt(2),352 error = {353 foo: ['Foo is in error', 'Another Foo Error'],354 baz: 'Baz has an error'355 };356 expect(ct.setErrors(error)).toBe(ct);357 expect(ct.getError()).toBeNull();358 expect(first.getError()).toEqual(['Foo is in error', 'Another Foo Error']);359 expect(second.getError()).toBeNull();360 expect(third.getError()).toEqual(['Baz has an error']);361 });362 it('should clear all field invalids', function() {363 createContainer([364 { label: 'foo', name: 'foo', errorTarget: 'side' },365 { label: 'bar', name: 'bar', errorTarget: 'side' },366 { label: 'baz', name: 'baz', errorTarget: 'side' }367 ]);368 var first = ct.getAt(0),369 second = ct.getAt(1),370 third = ct.getAt(2),371 errors = {372 foo: 'test error',373 bar: 'test error',374 baz: 'test error'375 };376 expect(ct.setErrors(errors)).toBe(ct);377 errors.foo = errors.bar = errors.baz = null;378 expect(ct.setErrors(errors)).toBe(ct);379 expect(ct.getError()).toBeNull();380 expect(first.getError()).toBeNull();381 expect(second.getError()).toBeNull();382 expect(third.getError()).toBeNull();383 });384 });385 });386 describe('isValid', function() {387 it('should return true if all fields are valid', function() {388 createContainer([389 { label: 'foo', name: 'foo' },390 { label: 'bar', name: 'bar' }391 ]);392 expect(ct.isValid()).toBe(true);393 });394 it('should return false when one field is invalid', function() {395 createContainer([396 { label: 'foo', name: 'foo', required: true },397 { label: 'bar', name: 'bar' }398 ]);399 ct.getAt(0).validate();400 expect(ct.isValid()).toBe(false);401 });402 it('should not check items after one field is found invalid', function() {403 createContainer([404 { label: 'foo', name: 'foo', required: true },405 { label: 'bar', name: 'bar' }406 ]);407 ct.getAt(0).validate();408 var spy = spyOn(ct.getAt(1), 'isValid');409 expect(ct.isValid()).toBe(false);410 expect(spy).not.toHaveBeenCalled();411 });412 });413 describe('validate', function() {414 it('should return true if all fields are valid', function() {415 createContainer([416 { label: 'foo', name: 'foo' },417 { label: 'bar', name: 'bar' }418 ]);419 expect(ct.validate()).toBe(true);420 });421 it('should return false when one field is invalid', function() {422 createContainer([423 { label: 'foo', name: 'foo', required: true },424 { label: 'bar', name: 'bar' }425 ]);426 expect(ct.validate()).toBe(false);427 });428 it('should validate all fields', function() {429 createContainer([430 { label: 'foo', name: 'foo', required: true },431 { label: 'bar', name: 'bar', required: true, requiredMessage: 'This field should not be empty' }432 ]);433 var first = ct.getAt(0),434 spy1 = spyOn(first, 'validate').andCallThrough(),435 second = ct.getAt(1),436 spy2 = spyOn(second, 'validate').andCallThrough();437 expect(ct.validate()).toBe(false);438 expect(first.getError()).toEqual(['This field is required']);439 expect(second.getError()).toEqual(['This field should not be empty']);440 expect(spy1).toHaveBeenCalled();441 expect(spy2).toHaveBeenCalled();442 });443 });444 describe('getFields', function() {445 it('should get all child fields', function() {446 createContainer([447 { label: 'foo', name: 'foo' },448 { label: 'bar', name: 'bar' },449 { label: 'baz', name: 'baz' }450 ]);451 var first = ct.getAt(0),452 second = ct.getAt(1),453 third = ct.getAt(2),454 fields = ct.getFields();455 // tests if the deep arg works456 expect(Object.keys(fields).length).toBe(3);457 expect(fields).toEqual({458 foo: first,459 bar: second,460 baz: third461 });462 });463 it('should get all child fields by name', function() {464 createContainer([465 { label: 'foo', name: 'foo' },466 { label: 'bar', name: 'bar' },467 { label: 'baz', name: 'baz' }468 ]);469 var first = ct.getAt(0),470 second = ct.getAt(1),471 third = ct.getAt(2);472 expect(ct.getFields('foo')).toBe(first);473 expect(ct.getFields('bar')).toBe(second);474 expect(ct.getFields('baz')).toBe(third);475 });476 it('should get all child fields as an array', function() {477 createContainer([478 { label: 'foo', name: 'foo' },479 { label: 'bar', name: 'bar' },480 { label: 'baz', name: 'baz' }481 ]);482 var first = ct.getAt(0),483 second = ct.getAt(1),484 third = ct.getAt(2),485 fields = ct.getFields(false);486 expect(fields.length).toBe(3);487 expect(fields).toEqual([488 first,489 second,490 third491 ]);...
index.test.js
Source:index.test.js
1'use strict';2const assert = require('chai').assert;3const sinon = require('sinon');4const mockery = require('mockery');5sinon.assert.expose(assert, { prefix: '' });6describe('index', function() {7 // Time not important. Only life important.8 this.timeout(5000);9 let Executor;10 let dockerodeMock;11 let dockerMock;12 let containerMock;13 let containerShellMock;14 let executor;15 before(() => {16 mockery.enable({17 useCleanCache: true,18 warnOnUnregistered: false19 });20 });21 beforeEach(() => {22 containerMock = {23 id: 'containerID',24 start: sinon.stub().yieldsAsync(),25 remove: sinon.stub().yieldsAsync()26 };27 containerShellMock = {28 id: 'containerID'29 };30 dockerMock = {31 createContainer: sinon.stub().yieldsAsync(null, containerMock),32 createImage: sinon.stub().yieldsAsync(null),33 listContainers: sinon.stub().yieldsAsync(null, [containerShellMock]),34 getContainer: sinon.stub().returns(containerMock)35 };36 dockerodeMock = sinon.stub().returns(dockerMock);37 mockery.registerMock('dockerode', dockerodeMock);38 /* eslint-disable global-require */39 Executor = require('../index');40 /* eslint-enable global-require */41 executor = new Executor({42 ecosystem: {43 api: 'api',44 ui: 'ui',45 store: 'store'46 },47 docker: {48 host: 'docker-swarm'49 },50 fusebox: {51 breaker: {52 timeout: 153 },54 retry: {55 retries: 1,56 minTimeout: 157 }58 }59 });60 });61 afterEach(() => {62 mockery.deregisterAll();63 mockery.resetCache();64 });65 after(() => {66 mockery.disable();67 });68 describe('constructor', () => {69 it('passes options to Dockerode', () => {70 assert.calledWith(dockerodeMock, {71 host: 'docker-swarm'72 });73 });74 it('defaults to stable containers', () => {75 assert.equal(executor.launchVersion, 'stable');76 assert.equal(executor.prefix, '');77 });78 it('supports customizing containers', () => {79 executor = new Executor({80 launchVersion: 'v1.2.3',81 prefix: 'beta_'82 });83 assert.equal(executor.launchVersion, 'v1.2.3');84 assert.equal(executor.prefix, 'beta_');85 });86 });87 describe('start', () => {88 const buildId = 1992;89 const apiUri = 'https://api.sd.cd';90 const token = '123456';91 let container = 'node:6';92 const launcherImageArgs = {93 fromImage: 'screwdrivercd/launcher',94 tag: 'stable'95 };96 let buildArgs;97 let launcherContainer;98 let launcherArgs;99 let buildContainer;100 beforeEach(() => {101 launcherContainer = {102 id: 'launcherID',103 start: sinon.stub().yieldsAsync(new Error()),104 remove: sinon.stub().yieldsAsync(new Error())105 };106 launcherArgs = {107 name: `${buildId}-init`,108 Image: 'screwdrivercd/launcher:stable',109 Entrypoint: '/bin/true',110 Labels: {111 sdbuild: buildId.toString()112 }113 };114 buildContainer = {115 id: 'buildID',116 start: sinon.stub().yieldsAsync(null),117 remove: sinon.stub().yieldsAsync(new Error())118 };119 buildArgs = {120 name: `${buildId}-build`,121 Image: container,122 Entrypoint: '/opt/sd/launcher_entrypoint.sh',123 Labels: {124 sdbuild: buildId.toString()125 },126 Cmd: [['/opt/sd/run.sh', `"${token}"`, 'api', 'store', '90', buildId, 'ui'].join(' ')],127 HostConfig: {128 Memory: 2 * 1024 * 1024 * 1024,129 MemoryLimit: 3 * 1024 * 1024 * 1024,130 VolumesFrom: ['launcherID:rw']131 }132 };133 });134 it('creates the required containers and starts them', () => {135 const buildImageArgs = {136 fromImage: 'node',137 tag: '6'138 };139 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));140 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);141 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);142 return executor143 .start({144 buildId,145 container,146 apiUri,147 token148 })149 .then(() => {150 assert.calledWith(dockerMock.createImage, buildImageArgs);151 assert.calledWith(dockerMock.createImage, launcherImageArgs);152 assert.callCount(dockerMock.createImage, 2);153 assert.calledWith(dockerMock.createContainer, buildArgs);154 assert.calledWith(dockerMock.createContainer, launcherArgs);155 assert.callCount(dockerMock.createContainer, 2);156 assert.callCount(buildContainer.start, 1);157 });158 });159 it('creates the containers with correct args from build config', () => {160 const buildImageArgs = {161 fromImage: 'node',162 tag: '6'163 };164 buildArgs.Cmd = [['/opt/sd/run.sh', `"${token}"`, 'api', 'store', 5, buildId, 'ui'].join(' ')];165 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));166 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);167 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);168 return executor169 .start({170 buildId,171 container,172 apiUri,173 token,174 annotations: {175 'screwdriver.cd/timeout': 5176 }177 })178 .then(() => {179 assert.calledWith(dockerMock.createImage, buildImageArgs);180 assert.calledWith(dockerMock.createImage, launcherImageArgs);181 assert.callCount(dockerMock.createImage, 2);182 assert.calledWith(dockerMock.createContainer, buildArgs);183 assert.calledWith(dockerMock.createContainer, launcherArgs);184 assert.callCount(dockerMock.createContainer, 2);185 assert.callCount(buildContainer.start, 1);186 });187 });188 it('supports prefixed containers', () => {189 const prefix = 'beta_';190 const buildImageArgs = {191 fromImage: 'node',192 tag: '6'193 };194 launcherArgs = {195 name: `${prefix}${buildId}-init`,196 Image: 'screwdrivercd/launcher:stable',197 Entrypoint: '/bin/true',198 Labels: {199 sdbuild: `${prefix}${buildId}`200 }201 };202 buildArgs = {203 name: `${prefix}${buildId}-build`,204 Image: container,205 Entrypoint: '/opt/sd/launcher_entrypoint.sh',206 Labels: {207 sdbuild: `${prefix}${buildId}`208 },209 Cmd: [['/opt/sd/run.sh', `"${token}"`, 'api', 'store', '90', buildId, 'ui'].join(' ')],210 HostConfig: {211 Memory: 2 * 1024 * 1024 * 1024,212 MemoryLimit: 3 * 1024 * 1024 * 1024,213 VolumesFrom: ['launcherID:rw']214 }215 };216 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));217 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);218 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);219 executor = new Executor({220 prefix,221 ecosystem: {222 api: 'api',223 ui: 'ui',224 store: 'store'225 }226 });227 return executor228 .start({229 buildId,230 container,231 apiUri,232 token233 })234 .then(() => {235 assert.calledWith(dockerMock.createImage, buildImageArgs);236 assert.calledWith(dockerMock.createImage, launcherImageArgs);237 assert.callCount(dockerMock.createImage, 2);238 assert.calledWith(dockerMock.createContainer, buildArgs);239 assert.calledWith(dockerMock.createContainer, launcherArgs);240 assert.callCount(dockerMock.createContainer, 2);241 assert.callCount(buildContainer.start, 1);242 });243 });244 it('creates containers without specifying a tag', () => {245 const buildImageArgs = {246 fromImage: 'node',247 tag: 'latest'248 };249 container = 'node';250 buildArgs.Image = container;251 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));252 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);253 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);254 return executor255 .start({256 buildId,257 container,258 apiUri,259 token260 })261 .then(() => {262 assert.calledWith(dockerMock.createImage, buildImageArgs);263 assert.calledWith(dockerMock.createImage, launcherImageArgs);264 assert.callCount(dockerMock.createImage, 2);265 assert.calledWith(dockerMock.createContainer, buildArgs);266 assert.calledWith(dockerMock.createContainer, launcherArgs);267 assert.callCount(dockerMock.createContainer, 2);268 assert.callCount(buildContainer.start, 1);269 });270 });271 it('creates containers from a private docker registry and starts them', () => {272 const buildImageArgs = {273 fromImage: 'docker-registry.foo.bar:1111/someImage',274 tag: 'latest'275 };276 container = 'docker-registry.foo.bar:1111/someImage:latest';277 buildArgs.Image = container;278 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));279 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);280 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);281 return executor282 .start({283 buildId,284 container,285 apiUri,286 token287 })288 .then(() => {289 assert.calledWith(dockerMock.createImage, buildImageArgs);290 assert.calledWith(dockerMock.createImage, launcherImageArgs);291 assert.callCount(dockerMock.createImage, 2);292 assert.calledWith(dockerMock.createContainer, buildArgs);293 assert.calledWith(dockerMock.createContainer, launcherArgs);294 assert.callCount(dockerMock.createContainer, 2);295 assert.callCount(buildContainer.start, 1);296 });297 });298 it('creates containers from a private docker registry without specifying a tag', () => {299 const buildImageArgs = {300 fromImage: 'docker-registry.foo.bar:1111/someImage',301 tag: 'latest'302 };303 container = 'docker-registry.foo.bar:1111/someImage';304 buildArgs.Image = container;305 dockerMock.createContainer.yieldsAsync(new Error('bad container args'));306 dockerMock.createContainer.withArgs(launcherArgs).yieldsAsync(null, launcherContainer);307 dockerMock.createContainer.withArgs(buildArgs).yieldsAsync(null, buildContainer);308 return executor309 .start({310 buildId,311 container,312 apiUri,313 token314 })315 .then(() => {316 assert.calledWith(dockerMock.createImage, buildImageArgs);317 assert.calledWith(dockerMock.createImage, launcherImageArgs);318 assert.callCount(dockerMock.createImage, 2);319 assert.calledWith(dockerMock.createContainer, buildArgs);320 assert.calledWith(dockerMock.createContainer, launcherArgs);321 assert.callCount(dockerMock.createContainer, 2);322 assert.callCount(buildContainer.start, 1);323 });324 });325 it('bubbles create problems back', () => {326 dockerMock.createContainer.yieldsAsync(new Error('Unable to create container'));327 return executor328 .start({329 buildId,330 container,331 apiUri,332 token333 })334 .then(() => {335 throw new Error('should not have gotten here');336 })337 .catch(error => {338 assert.equal(error.message, 'Unable to create container');339 });340 });341 it('bubbles start problems back', () => {342 containerMock.start.yieldsAsync(new Error('Unable to start container'));343 return executor344 .start({345 buildId,346 container,347 apiUri,348 token349 })350 .then(() => {351 throw new Error('should not have gotten here');352 })353 .catch(error => {354 assert.equal(error.message, 'Unable to start container');355 });356 });357 });358 describe('stop', () => {359 const buildId = 1992;360 it('finds and removes the containers', () => {361 const findArgs = {362 filters: `{"label":["sdbuild=${buildId}"]}`,363 all: true364 };365 const removeArgs = {366 v: true,367 force: true368 };369 dockerMock.listContainers.yieldsAsync(new Error('bad container args'));370 dockerMock.listContainers.withArgs(findArgs).yieldsAsync(null, [containerShellMock, containerShellMock]);371 return executor372 .stop({373 buildId374 })375 .then(() => {376 assert.calledWith(dockerMock.listContainers, findArgs);377 assert.calledWith(containerMock.remove, removeArgs);378 assert.callCount(containerMock.remove, 2);379 });380 });381 it('supports prefixes', () => {382 const prefix = 'beta_';383 const findArgs = {384 filters: `{"label":["sdbuild=${prefix}${buildId}"]}`,385 all: true386 };387 const removeArgs = {388 v: true,389 force: true390 };391 dockerMock.listContainers.yieldsAsync(new Error('bad container args'));392 dockerMock.listContainers.withArgs(findArgs).yieldsAsync(null, [containerShellMock, containerShellMock]);393 executor = new Executor({394 prefix,395 ecosystem: {396 api: 'api',397 ui: 'ui',398 store: 'store'399 }400 });401 return executor402 .stop({403 buildId404 })405 .then(() => {406 assert.calledWith(dockerMock.listContainers, findArgs);407 assert.calledWith(containerMock.remove, removeArgs);408 assert.callCount(containerMock.remove, 2);409 });410 });411 it('bubbles list problems back', () => {412 dockerMock.listContainers.yieldsAsync(new Error('Unable to list containers'));413 return executor414 .stop({415 buildId416 })417 .then(() => {418 throw new Error('should not have gotten here');419 })420 .catch(error => {421 assert.equal(error.message, 'Unable to list containers');422 });423 });424 it('bubbles remove problems back', () => {425 containerMock.remove.yieldsAsync(new Error('Unable to remove container'));426 return executor427 .stop({428 buildId429 })430 .then(() => {431 throw new Error('should not have gotten here');432 })433 .catch(error => {434 assert.equal(error.message, 'Unable to remove container');435 });436 });437 });438 describe('stats', () => {439 it('bubbles stats from circuit fuses', () => {440 assert.deepEqual(441 {442 requests: {443 total: 0,444 timeouts: 0,445 success: 0,446 failure: 0,447 concurrent: 0,448 averageTime: 0449 },450 breaker: {451 isClosed: true452 }453 },454 executor.stats()455 );456 });457 });458 describe('periodic', () => {459 it('resolves to null when calling periodic start', () =>460 executor.startPeriodic().then(res => assert.isNull(res)));461 it('resolves to null when calling periodic stop', () =>462 executor.stopPeriodic().then(res => assert.isNull(res)));463 });464 describe('frozen', () => {465 it('resolves to null when calling frozen start', () => executor.startFrozen().then(res => assert.isNull(res)));466 it('resolves to null when calling frozen stop', () => executor.stopFrozen().then(res => assert.isNull(res)));467 });...
Application.js
Source:Application.js
...4 const Application = KraGL.app.Application;5 const KraGLError = KraGL.KraGLError;6 describe('constructor', () => {7 it('defaults', () => {8 let container = createContainer();9 let app = new _MockApp({ container });10 assert.isDefined(app);11 assert.isFalse(app.isRunning);12 assert.instanceOf(app.gl, WebGLRenderingContext);13 assert.isFalse(app.gl.getContextAttributes().alpha);14 assert.isTrue(app.gl.getContextAttributes().stencil);15 assert.equal(app.width, 800);16 assert.equal(app.height, 600);17 destroyApp(app);18 });19 it('webgl2', () => {20 let container = createContainer();21 let app = new _MockApp({22 container,23 glVersion: '2.0'24 });25 assert.instanceOf(app.gl, WebGL2RenderingContext);26 destroyApp(app);27 });28 it('width & height', () => {29 let container = createContainer();30 let app = new _MockApp({31 container,32 width: 320,33 height: 24034 });35 assert.equal(app.width, 320);36 assert.equal(app.height, 240);37 destroyApp(app);38 });39 it('glAttrs', () => {40 let container = createContainer();41 let app = new _MockApp({42 container,43 glAttrs: {44 // Opposite of KraGL defaults45 alpha: true,46 stencil: false47 }48 });49 assert.isTrue(app.gl.getContextAttributes().alpha);50 assert.isFalse(app.gl.getContextAttributes().stencil);51 destroyApp(app);52 });53 });54 // Property tests55 describe('canvas', () => {56 it('normal', () => {57 let container = createContainer();58 let app = new _MockApp({ container });59 assert.instanceOf(app.canvas, HTMLCanvasElement);60 destroyApp(app);61 });62 });63 describe('container', () => {64 it('normal', () => {65 let container = createContainer();66 let app = new _MockApp({ container });67 assert.equal(app.container, container);68 destroyApp(app);69 });70 it('no container', () => {71 assert.throws(() => {72 let app = new _MockApp({});73 }, KraGLError);74 });75 });76 describe('fps', () => {77 it('not started', () => {78 let container = createContainer();79 let app = new _MockApp({ container });80 assert.equal(app.fps, 0);81 destroyApp(app);82 });83 it('running', () => {84 let container = createContainer();85 let app = new _MockApp({ container });86 return app.start()87 .then(() => {88 return new Promise(resolve => {89 setTimeout(() => {90 resolve();91 }, 1100);92 });93 })94 .then(() => {95 assert.approximately(app.fps, 60.0, 3.0);96 return app.end();97 })98 .finally(() => {99 destroyApp(app);100 });101 });102 });103 describe('gl', () => {104 it('normal', () => {105 let container = createContainer();106 let app = new _MockApp({ container });107 assert.instanceOf(app.gl, WebGLRenderingContext);108 destroyApp(app);109 });110 it('webgl2', () => {111 let container = createContainer();112 let app = new _MockApp({113 container,114 glVersion: '2.0'115 });116 assert.instanceOf(app.gl, WebGL2RenderingContext);117 destroyApp(app);118 });119 });120 describe('height', () => {121 it('normal', () => {122 let container = createContainer();123 let app = new _MockApp({ container });124 assert.equal(app.height, 600);125 destroyApp(app);126 });127 it('custom', () => {128 let container = createContainer();129 let app = new _MockApp({130 container,131 height: 240132 });133 assert.equal(app.height, 240);134 destroyApp(app);135 });136 });137 describe('isContextLost', () => {138 it('not lost', () => {139 let container = createContainer();140 let app = new _MockApp({ container });141 return app.start()142 .then(() => {143 assert.isFalse(app.isContextLost);144 return app.end();145 })146 .finally(() => {147 destroyApp(app);148 });149 });150 it('context lost', () => {151 let container = createContainer();152 let app = new _MockApp({ container });153 return app.start()154 .then(() => {155 app.gl.getExtension('WEBGL_lose_context').loseContext();156 return new Promise(resolve => {157 setTimeout(() => {158 resolve();159 }, 10);160 });161 })162 .then(() => {163 assert.isTrue(app.isContextLost);164 return app.end();165 })166 .finally(() => {167 destroyApp(app);168 });169 });170 it('after context restored', () => {171 let container = createContainer();172 let app = new _MockApp({ container });173 return app.start()174 .then(() => {175 app.canvas.dispatchEvent(new WebGLContextEvent('webglcontextlost'));176 return new Promise(resolve => {177 setTimeout(() => {178 resolve();179 }, 10);180 });181 })182 .then(() => {183 app.canvas.dispatchEvent(new WebGLContextEvent('webglcontextrestored'));184 return new Promise(resolve => {185 setTimeout(() => {186 resolve();187 }, 10);188 });189 })190 .then(() => {191 assert.isFalse(app.isContextLost);192 return app.end();193 })194 .finally(() => {195 destroyApp(app);196 });197 });198 });199 describe('isLoading', () => {200 it('from NOT_STARTED', () => {201 let container = createContainer();202 let app = new _MockApp({ container });203 assert.isFalse(app.isLoading);204 destroyApp(app);205 });206 it('from LOADING', () => {207 let container = createContainer();208 let app = new _MockApp({ container });209 // Implement initResources so that it takes 200 millis to load.210 app.initResources = function() {211 return new Promise(resolve => {212 setTimeout(() => {213 resolve();214 }, 200);215 });216 }217 let result = false;218 let promise = app.start();219 // Wait for an animation frame between when start is invoked and when220 // initResources finished. Capture the isLoading value at that time.221 setTimeout(() => {222 result = app.isLoading;223 }, 100);224 return promise225 .then(() => {226 assert.isTrue(result);227 return app.end();228 })229 .finally(() => {230 destroyApp(app);231 });232 });233 it('from RUNNING', () => {234 let container = createContainer();235 let app = new _MockApp({ container });236 return app.start()237 .then(() => {238 assert.isFalse(app.isLoading);239 return app.end();240 })241 .finally(() => {242 destroyApp(app);243 });244 });245 it('from ENDED', () => {246 let container = createContainer();247 let app = new _MockApp({ container });248 app.initResources = function() {249 return new Promise(resolve => {250 setTimeout(() => {251 resolve();252 }, 100);253 });254 }255 return app.start()256 .then(() => {257 return app.end();258 })259 .then(() => {260 assert.isFalse(app.isLoading);261 })262 .finally(() => {263 destroyApp(app);264 });265 });266 });267 describe('isPaused', () => {268 it('from NOT_STARTED', () => {269 let container = createContainer();270 let app = new _MockApp({ container });271 assert.isFalse(app.isPaused);272 destroyApp(app);273 });274 it('from LOADING', () => {275 let container = createContainer();276 let app = new _MockApp({ container });277 app.initResources = function() {278 return new Promise(resolve => {279 setTimeout(() => {280 resolve();281 }, 100);282 });283 };284 let result;285 let promise = app.start();286 setTimeout(() => {287 result = app.isPaused;288 }, 10);289 return promise290 .then(() => {291 return app.end();292 })293 .then(() => {294 assert.isFalse(result);295 })296 .finally(() => {297 destroyApp(app);298 });299 });300 it('from RUNNING', () => {301 let container = createContainer();302 let app = new _MockApp({ container });303 return app.start()304 .then(() => {305 assert.isFalse(app.isPaused);306 return app.end();307 })308 .finally(() => {309 destroyApp(app);310 });311 });312 it('from PAUSED', () => {313 let container = createContainer();314 let app = new _MockApp({ container });315 return app.start()316 .then(() => {317 return app.pause();318 })319 .then(() => {320 assert.isTrue(app.isPaused);321 return app.end();322 })323 .finally(() => {324 destroyApp(app);325 });326 });327 it('from ENDED', () => {328 let container = createContainer();329 let app = new _MockApp({ container });330 return app.start()331 .then(() => {332 return app.end();333 })334 .then(() => {335 assert.isFalse(app.isPaused);336 })337 .finally(() => {338 destroyApp(app);339 });340 });341 });342 describe('isRunning', () => {343 it('from NOT_STARTED', () => {344 let container = createContainer();345 let app = new _MockApp({ container });346 assert.isFalse(app.isRunning);347 destroyApp(app);348 });349 it('from LOADING', () => {350 let container = createContainer();351 let app = new _MockApp({ container });352 app.initResources = function() {353 return new Promise(resolve => {354 setTimeout(() => {355 resolve();356 }, 100);357 });358 };359 let promise = app.start();360 let result;361 setTimeout(() => {362 result = app.isRunning;363 }, 10);364 return promise365 .then(() => {366 assert.isFalse(result);367 return app.end();368 })369 .finally(() => {370 destroyApp(app);371 });372 });373 it('from RUNNING', () => {374 let container = createContainer();375 let app = new _MockApp({ container });376 return app.start()377 .then(() => {378 assert.isTrue(app.isRunning);379 return app.end();380 })381 .finally(() => {382 destroyApp(app);383 });384 });385 it('from CONTEXT_LOST', () => {386 let container = createContainer();387 let app = new _MockApp({ container });388 return app.start()389 .then(() => {390 app.gl.getExtension('WEBGL_lose_context').loseContext();391 return new Promise(resolve => {392 setTimeout(() => {393 resolve();394 }, 10);395 });396 })397 .then(() => {398 assert.isFalse(app.isRunning);399 })400 .finally(() => {401 destroyApp(app);402 });403 });404 it('from ENDED', () => {405 let container = createContainer();406 let app = new _MockApp({ container });407 return app.start()408 .then(() => {409 return app.end();410 })411 .then(() => {412 assert.isFalse(app.isRunning);413 })414 .finally(() => {415 destroyApp(app);416 });417 });418 });419 describe('shaderLib', () => {420 it('normal', () => {421 let container = createContainer();422 let app = new _MockApp({ container });423 assert.instanceOf(app.shaderLib, KraGL.shaders.ShaderLib);424 destroyApp(app);425 });426 });427 describe('width', () => {428 it('default', () => {429 let container = createContainer();430 let app = new _MockApp({ container });431 assert.equal(app.width, 800);432 destroyApp(app);433 });434 it('custom', () => {435 let container = createContainer();436 let app = new _MockApp({437 container,438 width: 320439 });440 assert.equal(app.width, 320);441 destroyApp(app);442 });443 });444 // Method tests445 describe('clean', () => {446 it('called by restart', () => {447 let container = createContainer();448 let app = new _MockApp({ container });449 let result;450 app.clean = function() {451 result = true;452 return Promise.resolve();453 }454 return app.start()455 .then(() => {456 return app.restart();457 })458 .then(() => {459 assert.isTrue(result);460 return app.end();461 })462 .finally(() => {463 destroyApp(app);464 });465 });466 });467 describe('end', () => {468 it('can be restarted', () => {469 let container = createContainer();470 let app = new _MockApp({ container });471 return app.start()472 .then(() => {473 return app.end();474 })475 .then(() => {476 assert.isFalse(app.isRunning);477 return app.restart();478 })479 .then(() => {480 assert.isTrue(app.isRunning);481 return app.end();482 })483 .finally(() => {484 destroyApp(app);485 });486 });487 it('cannot be started', () => {488 let container = createContainer();489 let app = new _MockApp({ container });490 let promise = app.start()491 .then(() => {492 return app.end();493 })494 .then(() => {495 assert.isFalse(app.isRunning);496 return app.start();497 })498 .finally(() => {499 destroyApp(app);500 });501 assert.isRejected(promise);502 });503 });504 describe('initResources', () => {505 it('called during startup', () => {506 let container = createContainer();507 let app = new _MockApp({ container });508 let result;509 app.initResources = function() {510 result = true;511 return Promise.resolve();512 };513 return app.start()514 .then(() => {515 assert.isTrue(result);516 return app.end();517 })518 .finally(() => {519 destroyApp(app);520 });521 });522 });523 describe('initWebGLResources', () => {524 it('called during startup', () => {525 let container = createContainer();526 let app = new _MockApp({ container });527 let result;528 app.initWebGLResources = function() {529 result = true;530 return Promise.resolve();531 };532 return app.start()533 .then(() => {534 assert.isTrue(result);535 return app.end();536 })537 .finally(() => {538 destroyApp(app);539 });;540 });541 });542 describe('pause', () => {543 it('normal', () => {544 let container = createContainer();545 let app = new _MockApp({ container });546 return app.start()547 .then(() => {548 return app.pause();549 })550 .then(() => {551 assert.isTrue(app.isPaused);552 return app.end();553 })554 .finally(() => {555 destroyApp(app);556 });557 });558 it('wrong state', () => {559 let container = createContainer();560 let app = new _MockApp({ container });561 assert.throws(() => {562 app.pause();563 }, KraGL.K);564 destroyApp(app);565 });566 });567 describe('render', () => {568 it('called while running', () => {569 let container = createContainer();570 let app = new _MockApp({ container });571 let result;572 app.render = function() {573 result = true;574 }575 return app.start()576 .then(() => {577 assert.isTrue(result);578 return app.end();579 })580 .finally(() => {581 destroyApp(app);582 });583 });584 });585 describe('restart', () => {586 it('normal', () => {587 let container = createContainer();588 let app = new _MockApp({ container });589 let startCount = 0;590 app.initResources = function() {591 startCount++;592 return Promise.resolve();593 };594 return app.start()595 .then(() => {596 return app.restart();597 })598 .then(() => {599 assert.equal(startCount, 2);600 return app.end();601 })602 .finally(() => {603 destroyApp(app);604 });605 });606 });607 describe('resume', () => {608 it('from PAUSED', () => {609 let container = createContainer();610 let app = new _MockApp({ container });611 return app.start()612 .then(() => {613 return app.pause();614 })615 .then(() => {616 assert.isFalse(app.isRunning);617 return app.resume();618 })619 .then(() => {620 assert.isTrue(app.isRunning);621 return app.end();622 })623 .finally(() => {624 destroyApp(app);625 });626 });627 it('from NOT_STARTED', () => {628 let container = createContainer();629 let app = new _MockApp({ container });630 assert.throws(() => {631 app.resume();632 }, KraGL.KraGLError);633 destroyApp(app);634 });635 it('from RUNNING', () => {636 let container = createContainer();637 let app = new _MockApp({ container });638 let promise = app.start()639 .then(() => {640 return app.resume();641 })642 .finally(() => {643 destroyApp(app);644 });645 return assert.isRejected(promise);646 });647 });648 describe('start', () => {649 it('normal', () => {650 let container = createContainer();651 let app = new _MockApp({ container });652 return app.start()653 .then(() => {654 assert.isTrue(app.isRunning);655 return app.end();656 })657 .then(() => {658 assert.isFalse(app.isRunning);659 })660 .finally(() => {661 destroyApp(app);662 });663 });664 it('wrong state', () => {665 let container = createContainer();666 let app = new _MockApp({ container });667 let promise = app.start()668 .then(() => {669 assert.isTrue(app.isRunning);670 return app.start();671 })672 .then(() => {673 throw new Error('fail');674 })675 .catch(() => {676 assert.isFalse(app.isRunning);677 })678 .finally(() => {679 destroyApp(app);680 });681 return assert.isRejected(promise);682 });683 });684 describe('update', () => {685 it('normal', () => {686 let container = createContainer();687 let app = new _MockApp({ container });688 let updateCount = 0;689 app.update = function() {690 updateCount++;691 };692 return app.start()693 .then(() => {694 return new Promise(resolve => {695 setTimeout(() => {696 resolve();697 }, 1000);698 });699 })700 .then(() => {...
CreateContainer-dbg.js
Source:CreateContainer-dbg.js
1/*!2 * OpenUI53 * (c) Copyright 2009-2019 SAP SE or an SAP affiliate company.4 * Licensed under the Apache License, Version 2.0 - see LICENSE.txt.5 */6sap.ui.define([7 "sap/ui/rta/plugin/Plugin",8 "sap/ui/fl/Utils",9 "sap/ui/rta/Utils",10 "sap/ui/dt/Util",11 "sap/base/util/uid"12], function(13 Plugin,14 FlexUtils,15 RtaUtils,16 DtUtil,17 uid18) {19 "use strict";20 /**21 * Constructor for a new CreateContainer Plugin.22 *23 * @param {string} [sId] id for the new object, generated automatically if no id is given24 * @param {object} [mSettings] initial settings for the new object25 * @class The CreateContainer allows trigger CreateContainer operations on the overlay26 * @extends sap.ui.rta.plugin.Plugin27 * @author SAP SE28 * @version 1.72.029 * @constructor30 * @private31 * @since 1.3432 * @alias sap.ui.rta.plugin.CreateContainer33 * @experimental Since 1.34. This class is experimental and provides only limited functionality. Also the API might be changed in future.34 */35 var CreateContainer = Plugin.extend("sap.ui.rta.plugin.CreateContainer", /** @lends sap.ui.rta.plugin.CreateContainer.prototype */ {36 metadata: {37 library: "sap.ui.rta",38 properties: {},39 associations: {},40 events: {}41 }42 });43 /**44 * This function gets called on startup. It checks if the Overlay is editable by this plugin.45 * @param {sap.ui.dt.Overlay} oOverlay - overlay to be checked46 * @returns {object} Returns object with editable boolean values for "asChild" and "asSibling"47 * @private48 */49 CreateContainer.prototype._isEditable = function (oOverlay) {50 return Promise.all([this._isEditableCheck(oOverlay, true), this._isEditableCheck(oOverlay, false)])51 .then(function(aPromiseValues) {52 return {53 asSibling: aPromiseValues[0],54 asChild: aPromiseValues[1]55 };56 });57 };58 CreateContainer.prototype._isEditableCheck = function (oOverlay, bOverlayIsSibling) {59 var oParentOverlay = this._getParentOverlay(bOverlayIsSibling, oOverlay);60 var sAggregationName;61 if (!oParentOverlay || !oParentOverlay.getParentElementOverlay()) {62 //root element is not editable as parent and as sibling63 return Promise.resolve(false);64 }65 if (bOverlayIsSibling) {66 sAggregationName = oOverlay.getParentAggregationOverlay().getAggregationName();67 }68 return this.checkAggregationsOnSelf(oParentOverlay, "createContainer", sAggregationName)69 .then(function(bEditableCheck) {70 if (bEditableCheck) {71 // If ids are created within fragments or controller code,72 // the id of the parent view might not be part of the control id.73 // In these cases the control might have a stable id (this.hasStableId()), but the view doesn't.74 // As the view is needed create the id for the newly created container it75 // has to be stable, otherwise the new id will not be stable.76 var oParentView = FlexUtils.getViewForControl(oParentOverlay.getElement());77 return this.hasStableId(oOverlay) && FlexUtils.checkControlId(oParentView);78 }79 return false;80 }.bind(this));81 };82 CreateContainer.prototype._getParentOverlay = function (bSibling, oOverlay) {83 var oParentOverlay;84 if (bSibling) {85 oParentOverlay = oOverlay.getParentElementOverlay();86 } else {87 oParentOverlay = oOverlay;88 }89 return oParentOverlay;90 };91 CreateContainer.prototype.getCreateAction = function (bSibling, oOverlay) {92 var oParentOverlay = this._getParentOverlay(bSibling, oOverlay);93 var oDesignTimeMetadata = oParentOverlay.getDesignTimeMetadata();94 var aActions = oDesignTimeMetadata.getActionDataFromAggregations("createContainer", oOverlay.getElement());95 return aActions[0];96 };97 CreateContainer.prototype.isAvailable = function (bSibling, aElementOverlays) {98 return this._isEditableByPlugin(aElementOverlays[0], bSibling);99 };100 CreateContainer.prototype.isEnabled = function (bSibling, aElementOverlays) {101 var oElementOverlay = aElementOverlays[0];102 var vAction = this.getCreateAction(bSibling, oElementOverlay);103 if (!vAction) {104 return false;105 }106 if (vAction.isEnabled && typeof vAction.isEnabled === "function") {107 var fnIsEnabled = vAction.isEnabled;108 var oParentOverlay = this._getParentOverlay(bSibling, oElementOverlay);109 return fnIsEnabled(oParentOverlay.getElement());110 }111 return true;112 };113 /**114 * Returns the id of a newly created container using the function115 * defined in the control designtime metadata to retrieve the correct value116 * @param {object} vAction create container action from designtime metadata117 * @param {string} sNewControlID id of the new control118 * @return {string} Returns the id of the created control119 */120 CreateContainer.prototype.getCreatedContainerId = function (vAction, sNewControlID) {121 var sId = sNewControlID;122 if (vAction.getCreatedContainerId && typeof vAction.getCreatedContainerId === "function") {123 var fnMapToRelevantControlID = vAction.getCreatedContainerId;124 sId = fnMapToRelevantControlID(sNewControlID);125 }126 return sId;127 };128 CreateContainer.prototype._determineIndex = function (oParentElement, oSiblingElement, sAggregationName, fnGetIndex) {129 return RtaUtils.getIndex(oParentElement, oSiblingElement, sAggregationName, fnGetIndex);130 };131 CreateContainer.prototype._getText = function (vAction, oElement, oDesignTimeMetadata, sText) {132 if (!vAction) {133 return sText;134 }135 var oAggregationDescription = oDesignTimeMetadata.getAggregationDescription(vAction.aggregation, oElement);136 if (!oAggregationDescription) {137 return sText;138 }139 var sContainerTitle = oAggregationDescription.singular;140 var oTextResources = sap.ui.getCore().getLibraryResourceBundle("sap.ui.rta");141 return oTextResources.getText(sText, sContainerTitle);142 };143 CreateContainer.prototype.getCreateContainerText = function(bSibling, oOverlay) {144 var vAction = this.getCreateAction(bSibling, oOverlay);145 var oParentOverlay = this._getParentOverlay(bSibling, oOverlay);146 var oDesignTimeMetadata = oParentOverlay.getDesignTimeMetadata();147 var oElement = oParentOverlay.getElement();148 var sText = "CTX_CREATE_CONTAINER";149 return this._getText(vAction, oElement, oDesignTimeMetadata, sText);150 };151 CreateContainer.prototype._getContainerTitle = function (vAction, oElement, oDesignTimeMetadata) {152 var sText = "TITLE_CREATE_CONTAINER";153 return this._getText(vAction, oElement, oDesignTimeMetadata, sText);154 };155 CreateContainer.prototype.handleCreate = function (bSibling, oOverlay) {156 var vAction = this.getCreateAction(bSibling, oOverlay);157 var oParentOverlay = this._getParentOverlay(bSibling, oOverlay);158 var oParent = oParentOverlay.getElement();159 var oDesignTimeMetadata = oParentOverlay.getDesignTimeMetadata();160 var oView = FlexUtils.getViewForControl(oParent);161 var oSiblingElement;162 if (bSibling) {163 oSiblingElement = oOverlay.getElement();164 }165 var sNewControlID = oView.createId(uid());166 var fnGetIndex = oDesignTimeMetadata.getAggregation(vAction.aggregation).getIndex;167 var iIndex = this._determineIndex(oParent, oSiblingElement, vAction.aggregation, fnGetIndex);168 var sVariantManagementReference = this.getVariantManagementReference(oParentOverlay);169 return this.getCommandFactory().getCommandFor(oParent, "createContainer", {170 newControlId : sNewControlID,171 label : this._getContainerTitle(vAction, oParent, oDesignTimeMetadata),172 index : iIndex,173 parentId : oParent.getId()174 }, oDesignTimeMetadata, sVariantManagementReference)175 .then(function(oCreateCommand) {176 this.fireElementModified({177 command : oCreateCommand,178 action : vAction,179 newControlId : sNewControlID180 });181 }.bind(this))182 .catch(function(oMessage) {183 throw DtUtil.createError("CreateContainer#handleCreate", oMessage, "sap.ui.rta");184 });185 };186 /**187 * Retrieve the context menu item for the actions.188 * Two items are returned here: one for when the overlay is sibling and one for when it is child.189 * @param {sap.ui.dt.ElementOverlay[]} aElementOverlays - Target overlays190 * @return {object[]} returns array containing the items with required data191 */192 CreateContainer.prototype.getMenuItems = function (aElementOverlays) {193 var bOverlayIsSibling = true;194 var sPluginId = "CTX_CREATE_SIBLING_CONTAINER";195 var iRank = 40;196 var aMenuItems = [];197 for (var i = 0; i < 2; i++) {198 if (this.isAvailable(bOverlayIsSibling, aElementOverlays)) {199 var sMenuItemText = this.getCreateContainerText.bind(this, bOverlayIsSibling);200 aMenuItems.push({201 id: sPluginId,202 text: sMenuItemText,203 handler: this.handler.bind(this, bOverlayIsSibling),204 enabled: this.isEnabled.bind(this, bOverlayIsSibling),205 icon: "sap-icon://add-folder",206 rank: iRank207 });208 }209 bOverlayIsSibling = false;210 sPluginId = "CTX_CREATE_CHILD_CONTAINER";211 iRank = 50;212 }213 return aMenuItems;214 };215 /**216 * Get the name of the action related to this plugin.217 * @return {string} Returns the action name218 */219 CreateContainer.prototype.getActionName = function () {220 return "createContainer";221 };222 /**223 * Trigger the plugin execution.224 * @param {boolean} bOverlayIsSibling True if the overlay is sibling225 * @param {sap.ui.dt.ElementOverlay[]} aElementOverlays - Target overlays226 */227 CreateContainer.prototype.handler = function (bOverlayIsSibling, aElementOverlays) {228 this.handleCreate(bOverlayIsSibling, aElementOverlays[0]);229 };230 return CreateContainer;...
PointSelector.spec.js
Source:PointSelector.spec.js
...4import { PointSelector as selector } from '../../src/selectors'5function createPoint ({ x, y } = { x: 10, y: 10 }) {6 return { x, y }7}8function createContainer({ width, height } = { width: 100, height: 100 }) {9 return { width, height }10}11describe('PoinntSelector', () => {12 describe('TYPE', () => {13 it('should be a defined string', () => {14 expect(selector.TYPE).to.be.a('string')15 })16 })17 describe('intersects', () => {18 it('should return true when point is inside geometry', () => {19 expect(20 selector.intersects({ x: 10, y: 10 }, createPoint(), createContainer())21 ).to.be.true22 })23 it('should return false when point is outside of geometry', () => {24 expect(selector.intersects({ x: 0, y: 0 }, createPoint(), createContainer())).to.be.false25 expect(selector.intersects({ x: 10, y: 0 }, createPoint(), createContainer())).to.be.false26 expect(selector.intersects({ x: 0, y: 10 }, createPoint(), createContainer())).to.be.false27 expect(selector.intersects({ x: 30, y: 30 }, createPoint(), createContainer())).to.be.false28 })29 })30 describe('area', () => {31 it('should return geometry area', () => {32 expect(33 selector.area(createPoint(), createContainer())34 ).to.equal(36)35 })36 it('should return geometry area based on container', () => {37 expect(38 selector.area(createPoint(), createContainer({ width: 200, height: 200 }))39 ).to.equal(9)40 })41 })42 describe('methods', () => {43 xit('should be defined')44 })...
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 const container = await page.createContainer();7 await container.addInitScript({ path: './initScript.js' });8 await container.addInitScript({ path: './initScript2.js' });9 await container.addInitScript({ path: './initScript3.js' });10 await container.addInitScript({ path: './initScript4.js' });11 await container.addInitScript({ path: './initScript5.js' });12 await container.addInitScript({ path: './initScript6.js' });13 await container.addInitScript({ path: './initScript7.js' });14 await container.addInitScript({ path: './initScript8.js' });15 await container.addInitScript({ path: './initScript9.js' });16 await container.addInitScript({ path: './initScript10.js' });17 await container.addInitScript({ path: './initScript11.js' });18 await container.addInitScript({ path: './initScript12.js' });19 await container.addInitScript({ path: './initScript13.js' });20 await container.addInitScript({ path: './initScript14.js' });21 await container.addInitScript({ path: './initScript15.js' });22 await container.addInitScript({ path: './initScript16.js' });23 await container.addInitScript({ path: './initScript17.js' });24 await container.addInitScript({ path: './initScript18.js' });25 await container.addInitScript({ path: './initScript19.js' });26 await container.addInitScript({ path: './initScript20.js' });27 await container.addInitScript({ path: './initScript21.js' });28 await container.addInitScript({ path: './initScript22.js' });29 await container.addInitScript({ path: './initScript23.js' });30 await container.addInitScript({ path: './initScript24.js' });31 await container.addInitScript({ path: './initScript25.js' });32 await container.addInitScript({ path: './initScript26.js' });33 await container.addInitScript({ path: './initScript27.js' });34 await container.addInitScript({ path: './initScript
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 const container = await page.createContainer();7 await container.setContent('<h1>My Page</h1>');8 const h1 = await container.$('h1');9 console.log(await h1.innerText());10 await browser.close();11})();12const { chromium } = require('playwright');13(async () => {14 const browser = await chromium.launch();15 const context = await browser.newContext();16 const page = await context.newPage();17 const container = await page.createContainer();18 await container.setContent('<h1>My Page</h1>');19 const h1 = await container.$('h1');20 console.log(await h1.innerText());21 await browser.close();22})();23const { chromium } = require('playwright');24(async () => {25 const browser = await chromium.launch();26 const context = await browser.newContext();27 const page = await context.newPage();28 const container = await page.createContainer();29 await container.setContent('<h1>My Page</h1>');30 const h1 = await container.$('h1');31 console.log(await h1.innerText());32 await browser.close();33})();34const { chromium } = require('playwright');35(async () => {36 const browser = await chromium.launch();37 const context = await browser.newContext();38 const page = await context.newPage();39 const container = await page.createContainer();40 await container.setContent('<h1>My Page</h1>');41 const h1 = await container.$('h1');42 console.log(await h1.innerText());43 await browser.close();44})();45const { chromium } = require('playwright');46(async () => {47 const browser = await chromium.launch();48 const context = await browser.newContext();49 const page = await context.newPage();50 const container = await page.createContainer();51 await container.setContent('<h1>My Page</h1>');
Using AI Code Generation
1const playwright = require('playwright');2(async () => {3 const browser = await playwright['chromium'].launch({ headless: false });4 const context = await browser.newContext();5 const page = await context.newPage();6 const container = await page._delegate.createContainer();7 console.log(container);8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2const path = require('path');3(async () => {4 const browser = await chromium.launch({ headless: false });5 const context = await browser.newContext();6 const page = await context.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await page.screenshot({ path: `example.png` });7 await browser.close();8})();9const { chromium } = require('playwright');10(async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await page.screenshot({ path: `example.png` });15 await browser.close();16})();17const { chromium } = require('playwright');18(async () => {19 const browser = await chromium.launch();20 const context = await browser.newContext();21 const page = await context.newPage();22 await page.screenshot({ path: `example.png` });23 await browser.close();24})();25const { chromium } = require('playwright');26(async () => {27 const browser = await chromium.launch();28 const context = await browser.newContext();29 const page = await context.newPage();30 await page.screenshot({ path: `example.png` });31 await browser.close();32})();33const { chromium } = require('playwright');34(async () => {35 const browser = await chromium.launch();36 const context = await browser.newContext();37 const page = await context.newPage();38 await page.screenshot({ path: `example.png` });39 await browser.close();40})();41const { chromium } = require('playwright');
Using AI Code Generation
1const { chromium } = require('playwright');2(async () => {3 const browser = await chromium.launch();4 const page = await browser.newPage();5 const container = await page.createContainer();6 await container.setContent('<div>My div</div>');7 await container.waitForSelector('div');8 await browser.close();9})();10 at Object.throwProtocolError (/home/akshay/projects/playwright/node_modules/playwright-core/lib/cjs/protocol/errors.js:118:14)11 at CDPSession._onMessage (/home/akshay/projects/playwright/node_modules/playwright-core/lib/cjs/protocol/protocol.js:187:23)12 at CDPSession.emit (events.js:315:20)13 at CDPSession.EventEmitter.emit (domain.js:467:12)14 at CDPSession._onMessage (/home/akshay/projects/playwright/node_modules/playwright-core/lib/cjs/protocol/Connection.js:200:14)15 at Connection._onMessage (/home/akshay/projects/playwright/node_modules/playwright-core/lib/cjs/protocol/Connection.js:112:17)16 at WebSocketTransport._ws.addEventListener.event (/home/akshay/projects/playwright/node_modules/playwright-core/lib/cjs/protocol/Transport.js:184:24)17 at WebSocket.onMessage (/home/akshay/projects/playwright/node_modules/ws/lib/event-target.js:132:16)18 at WebSocket.emit (events.js:315:20)19 at WebSocket.EventEmitter.emit (domain.js:467:12)
Using AI Code Generation
1const { createContainer } = require('@playwright/test');2(async () => {3 const container = await createContainer();4 const { page } = await container.newPage();5 await page.screenshot({ path: 'example.png' });6 await container.close();7})();8const { createContainer } = require('@playwright/test');9(async () => {10 const container = await createContainer({11 });12 const { page } = await container.newPage();13 await page.screenshot({ path: 'example.png' });14 await container.close();15})();16const { createContainer } = require('@playwright/test');17(async () => {18 const container = await createContainer({19 });20 const { page } = await container.newPage();21 await page.screenshot({ path: 'example.png' });22 await container.close();23})();
Using AI Code Generation
1const { createContainer } = require('playwright/lib/server/browserType');2const container = createContainer({3});4(async () => {5 const browser = await container.createBrowser();6 const page = await browser.newPage();7 await page.screenshot({ path: 'example.png' });8 await browser.close();9})();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!