Best JavaScript code snippet using qawolf
model.test.js
Source:model.test.js
1/* global expect, test, describe, beforeEach */2import newModel from '../src/model.js';3/**4 * Setup test model5 * @return {[type]} [description]6 */7function makeTestnewModel() {8 return newModel(9 {10 'stuff': {11 'northwind': 'costa',12 'info': [1, 2, 3],13 'nest': [{'foo': 'bar'}],14 },15 'name': 'dave',16 'zero': [],17 },18 );19}20describe('Test basic get functionalty', () => {21 const testModel = makeTestnewModel();22 test('data object exists', () => {23 expect(typeof testModel).toBe('object');24 });25 test('data object is populated', () => {26 expect(testModel.name).toBe('dave');27 });28 test('data object array is populated', () => {29 expect(testModel.stuff.info[1]).toBe(2);30 });31 test('Get root data', () => {32 expect(testModel.get().name).toBe('dave');33 expect(testModel.get('').name).toBe('dave');34 });35 test('non-nested getting', () => {36 expect(testModel.get('name')).toBe('dave');37 });38 test('dot syntax getting', () => {39 expect( testModel.get('stuff.info.1')).toBe(2);40 });41 test('square bracket getting', () => {42 expect(testModel.get('stuff.info[1]')).toBe(2);43 });44 test('array based getting', () => {45 expect(testModel.get(['stuff', 'info', 1])).toBe(2);46 });47 test('mixed syntax getting', () => {48 expect( testModel.get('stuff.nest[0].foo')).toBe('bar');49 });50 test('non-existent fallback response', () => {51 expect(testModel.get('stuff.info.6')).toBe(undefined);52 });53 test('custom fallback response', () => {54 expect(testModel.get('stuff.info.6', 'hello')).toBe('hello');55 });56 test('Get allows access to values with protected names', () => {57 testModel.get = 'test';58 expect(testModel.get('get')).toBe('test');59 });60 test('Get something that doesnt exist', () => {61 expect(testModel.get('bacon.egg.sausage')).toBe(undefined);62 });63});64describe('Test basic set functionalty', () => {65 const testModel = makeTestnewModel();66 test('Basic set', () => {67 testModel.set('name', 'bert');68 expect(testModel.get('name')).toBe('bert');69 expect(testModel.name).toBe('bert');70 });71 test('Nested set', () => {72 testModel.set('stuff.northwind', 'example');73 expect(testModel.stuff.northwind).toBe('example');74 expect(testModel.get('stuff.northwind')).toBe('example');75 });76 test('deep object creation', () => {77 testModel.set('new.object.name.potato', 'Hullo');78 expect(testModel.get('new.object.name.potato')).toBe('Hullo');79 });80 test('Set arrays', () => {81 testModel.set('new.object.arr', [1]);82 expect(testModel.new.object.arr[0]).toBe(1);83 expect(testModel.get('new.object.arr[0]')).toBe(1);84 });85 test('Set numerical property', () => {86 testModel.set('new.object.arr2.0', 'hi');87 expect(testModel.new.object.arr2[0]).toBe('hi');88 expect(testModel.get('new.object.arr2.0')).toBe('hi');89 });90 test('Set numerical property with array syntax', () => {91 testModel.set('new.object.arr3[0]', 'hey');92 expect(testModel.new.object.arr3[0]).toBe('hey');93 expect(testModel.get('new.object.arr3.0')).toBe('hey');94 });95 test('Set as array of attrs', () => {96 testModel.set(['new', 'object', 'arr2', '0'], 'yo');97 expect(testModel.new.object.arr2[0]).toBe('yo');98 expect(testModel.get(['new', 'object', 'arr2', '0'])).toBe('yo');99 });100});101describe('Test read events', () => {102 let testModel;103 beforeEach(() => {104 testModel = makeTestnewModel();105 });106 test('Read via get', () => {107 testModel.on('read', (data) => {108 expect(data).toBe('name');109 });110 testModel.get('name');111 });112 test('Read via object', () => {113 testModel.on('read', (data) => {114 expect(data).toBe('name');115 });116 testModel.name;117 });118 // Deep data read will travel up the chain of values till the relevent one.119 // This means a read listener on stuff will trigger as well as the one on stuff.info120 test('Read deep data', () => {121 const calls = ['stuff', 'stuff.info'];122 testModel.on('read', (data) => {123 expect(data).toBe(calls.pop());124 });125 testModel.get('stuff.info');126 });127 test('Add additional listeners', () => {128 const f1 = function(a) {129 return 1+1;130 };131 const f2 = function(a) {132 return 2+2;133 };134 testModel.on('read', f1);135 testModel.on('read', f2);136 expect(testModel.getEvents('read').length).toBe(2);137 testModel.off('read', f1);138 expect(testModel.getEvents('read').length).toBe(1);139 testModel.off('read');140 // Should remove all read listerns141 expect(!testModel.getEvents('read')).toBe(true);142 });143});144describe('Simple change detection', () => {145 let testModel;146 beforeEach(() => {147 testModel = makeTestnewModel();148 });149 test('Listen to value created by set', () => {150 testModel.on('all', (type, namespace, updated, original) => {151 expect(type).toBe('CREATE');152 expect(namespace).toBe('count');153 expect(updated).toBe(0);154 });155 testModel.set('count', 0);156 });157 test('Listen to value created directly', () => {158 testModel.on('all', (type, namespace, updated, original) => {159 expect(type).toBe('CREATE');160 expect(namespace).toBe('count');161 expect(updated).toBe(0);162 });163 testModel.count = 0;164 });165 test('Listen to value update', () => {166 testModel.on('all', (type, namespace, updated, original) => {167 expect(type).toBe('UPDATE');168 expect(namespace).toBe('name');169 expect(updated).toBe('Gertrude');170 expect(original).toBe('dave');171 });172 testModel.set('name', 'Gertrude');173 });174 test('Listen to value unchanged', () => {175 testModel.on('all', (type, namespace, updated, original) => {176 expect(type).toBe('NONE');177 expect(namespace).toBe('name');178 expect(updated).toBe('dave');179 expect(original).toBe('dave');180 });181 testModel.set('name', 'dave');182 });183 test('Listen to value change numeric', () => {184 testModel.on('all', (type, namespace, updated, original) => {185 expect(type).toBe('UPDATE');186 expect(namespace).toBe('name');187 expect(updated).toBe(0);188 expect(original).toBe('dave');189 });190 testModel.set('name', 0);191 });192 test('Listen to value change false', () => {193 testModel.on('all', (type, namespace, updated, original) => {194 expect(type).toBe('UPDATE');195 expect(namespace).toBe('name');196 expect(updated).toBe(false);197 expect(original).toBe('dave');198 });199 testModel.set('name', false);200 });201 test('Listen to value change null', () => {202 testModel.on('all', (type, namespace, updated, original) => {203 expect(type).toBe('UPDATE');204 expect(namespace).toBe('name');205 expect(updated).toBe(null);206 expect(original).toBe('dave');207 });208 testModel.set('name', null);209 });210 test('Listen to value remove', () => {211 let count = 0;212 testModel.on('all', (type, namespace, updated, original) => {213 count++;214 expect(type).toBe('REMOVE');215 expect(namespace).toBe('name');216 expect(updated).toBe(undefined);217 expect(original).toBe('dave');218 });219 delete testModel.name;220 expect(testModel.name).toBe(undefined);221 expect(count).toBe(1);222 });223 test('Listen to object update', () => {224 const namespaces = ['stuff.northwind', 'stuff'];225 const changes = ['UPDATE', 'UPDATE'];226 testModel.on('all', (type, namespace, updated, original) => {227 expect(type).toBe(changes.shift());228 expect(namespace).toBe(namespaces.shift());229 });230 testModel.set('stuff.northwind', 'eggs');231 });232 test('Listen update object with new', () => {233 const namespaces = ['stuff.cheese', 'stuff'];234 const changes = ['CREATE', 'UPDATE'];235 testModel.on('all', (type, namespace, updated, original) => {236 expect(type).toBe(changes.shift());237 expect(namespace).toBe(namespaces.shift());238 });239 // cheese will log a CREATE240 // stuff will log its been UPDATED241 testModel.set('stuff.cheese', 'yes');242 });243 test('Listen update object with object', () => {244 testModel.set('testing', {'animal': 'cat', 'cake': 'yes'});245 // When replacing a object with another object, all old properties will trigger as removed.246 // the base object will consider itself updated and the new entity has created247 const namespaces = ['testing.platypus', 'testing.animal', 'testing.cake', 'testing'];248 const changes = ['CREATE', 'REMOVE', 'REMOVE', 'UPDATE'];249 testModel.on('all', (type, namespace, updated, original) => {250 expect(type).toBe(changes.shift());251 expect(namespace).toBe(namespaces.shift());252 });253 testModel.set('testing', {'platypus': false});254 });255 test('Listen update object with object with same object', () => {256 testModel.set('testing', {'animal': 'cat', 'cake': 'yes'});257 // When replacing with same object, everthing will consider itself unchanged258 const namespaces = ['testing.animal', 'testing.cake', 'testing'];259 const changes = ['NONE', 'NONE', 'NONE'];260 testModel.on('all', (type, namespace, updated, original) => {261 expect(type).toBe(changes.shift());262 expect(namespace).toBe(namespaces.shift());263 });264 testModel.set('testing', {'animal': 'cat', 'cake': 'yes'});265 });266 test('Listen update object with object with similar object', () => {267 testModel.set('testing', {'animal': 'cat', 'cake': 'no'});268 // cake value is changed, so object is changed.269 const namespaces = ['testing.animal', 'testing.cake', 'testing'];270 const changes = ['NONE', 'UPDATE', 'UPDATE'];271 testModel.on('all', (type, namespace, updated, original) => {272 expect(type).toBe(changes.shift());273 expect(namespace).toBe(namespaces.shift());274 });275 testModel.set('testing', {'animal': 'cat', 'cake': 'yes'});276 });277 test('Listen update object with empty string', () => {278 testModel.set('testing', {'animal': 'cat', 'cake': 'no'});279 // Remove old obj values & update testing to new.280 const namespaces = ['testing.animal', 'testing.cake', 'testing'];281 const changes = ['REMOVE', 'REMOVE', 'UPDATE'];282 testModel.on('all', (type, namespace, updated, original) => {283 expect(type).toBe(changes.shift());284 expect(namespace).toBe(namespaces.shift());285 });286 testModel.set('testing', '');287 });288 test('Make tree', () => {289 let callbackCount = 0;290 // Remove old obj values & update testing to new.291 const namespaces = ['a.b.c.d.e.f', 'a.b.c.d.e', 'a.b.c.d', 'a.b.c', 'a.b', 'a'];292 const changes = ['CREATE', 'CREATE', 'CREATE', 'CREATE', 'CREATE', 'CREATE'];293 testModel.on('all', (type, namespace, updated, original) => {294 callbackCount++;295 expect(type).toBe(changes.shift());296 expect(namespace).toBe(namespaces.shift());297 });298 testModel.set('a.b.c.d.e.f', 'Hi');299 // Fire only once per change300 expect(callbackCount).toBe(6);301 });302 test('Remove tree', () => {303 testModel.set('a.b.c.d.e.f', 'Hi');304 // Remove old obj values & update testing to new.305 const namespaces = ['a.b.c.d.e.f', 'a.b.c.d.e', 'a.b.c.d', 'a.b.c', 'a.b', 'a'];306 const changes = ['REMOVE', 'REMOVE', 'REMOVE', 'REMOVE', 'REMOVE', 'UPDATE'];307 testModel.on('all', (type, namespace, updated, original) => {308 expect(type).toBe(changes.shift());309 expect(namespace).toBe(namespaces.shift());310 });311 testModel.set('a', {});312 });313 test('Wildcard new element', () => {314 let called = 0;315 testModel.set('players', [{'name': 'bob'}, {'name': 'sally'}]);316 testModel.on('create:players.*', (change) => {317 called++;318 expect(change.name).toBe('buzz');319 });320 testModel.set('players', [{'name': 'bob'}, {'name': 'sally'}, {'name': 'buzz'}]);321 expect(called).toBe(1);322 });323 test('Test simple array match', () => {324 testModel.set('abc', ['bob']);325 testModel.on('all', (type, namespace, updated, original) => {326 expect(type).toBe('NONE');327 });328 testModel.set('abc', ['bob']);329 });330 test('Test simple object match', () => {331 testModel.set('abc', {name: 'bob'});332 testModel.on('all', (type, namespace, updated, original) => {333 expect(type).toBe('NONE');334 });335 testModel.set('abc', {name: 'bob'});336 });337 test('Empty object match', () => {338 testModel.set('abc', []);339 testModel.on('all', (type, namespace, updated, original) => {340 expect(type).toBe('NONE');341 });342 testModel.set('abc', []);343 });344 test('Empty array match', () => {345 testModel.set('abc', []);346 testModel.on('all', (type, namespace, updated, original) => {347 expect(type).toBe('NONE');348 });349 testModel.set('abc', []);350 });351});352describe('Context events', () => {353 let testModel;354 beforeEach(() => {355 testModel = makeTestnewModel();356 });357 test('Context event simple', () => {358 const stuff = testModel.get('stuff');359 stuff.on('all', () => {});360 expect(Object.keys(testModel.getEvents())[0]).toBe('all:stuff');361 });362 test('Context event, sub object', () => {363 const stuff = testModel.get('stuff');364 stuff.on('change:name', () => {});365 expect(Object.keys(testModel.getEvents())[0]).toBe('change:stuff.name');366 });367 test('Add event listener directly to sub object', () => {368 const stuff = testModel.get('stuff');369 stuff.on('all', (type, updated, original) => {370 expect(type).toBe('UPDATE');371 });372 stuff.name = 'Harry';373 });374 test('Use get on a sub object', () => {375 testModel.set('test.testing', {'name': 'bobbert'});376 const testing = testModel.get('test.testing');377 expect(testing.get('name')).toBe('bobbert');378 });379 test('Detect object being removed using sub object event', () => {380 testModel.set('test.testing', {'name': 'bobbert'});381 const testing = testModel.get('test.testing');382 testing.on('all', (type, updated, original) => {383 expect(type).toBe('REMOVE');384 });385 testModel.set('test', {});386 });387 test('Set value on subobject', () => {388 testModel.set('test.testing', {'name': 'bobbert'});389 const testing = testModel.get('test.testing');390 testing.on('all', (type, updated, original) => {391 expect(type).toBe('UPDATE');392 expect(updated.name).toBe('Jane');393 expect(original.name).toBe('bobbert');394 });395 // testModel.set('test.testing', {'name': 'Jane'});396 testing.set('name', 'Jane');397 });398 test('Get context', () => {399 testModel.set('test.testing.1', {'name': 'bobbert'});400 const testing = testModel.get('test.testing.1');401 expect(testing.getContext()).toBe('test.testing.1');402 });403 test('Ensure orphaned object, still shows latest from datapath', () => {404 testModel.set('test', {'data': {name: 'abc'}});405 // When using a local obj, complete refresh of object can lead to it becoming406 // orphaned. Refresh model allows it to figure out its real version again.407 const data = testModel.get('test.data');408 testModel.set('test', {'data': {name: 'def'}});409 expect(data.name).toBe('def');410 });411 test('Ensure orphaned object handles no longer existing in datapath', () => {412 testModel.set('test', {'data': {name: 'abc'}});413 // When using a local obj, complete refresh of object can lead to it becoming414 // orphaned. Refresh model allows it to figure out its real version again.415 const data = testModel.get('test.data');416 testModel.set('test', {});417 expect(data.name).toBe(undefined);418 });419 test('Ensure orphaned object can set values correctly', () => {420 testModel.set('test', {'data': {name: 'abc'}});421 // When using a local obj, complete refresh of object can lead to it becoming422 // orphaned. Refresh model allows it to figure out its real version again.423 const data = testModel.get('test.data');424 testModel.set('test', {'data': {name: 'def'}});425 data.set('name', 'huh');426 expect(testModel.get('test.data.name')).toBe('huh');427 });428 test('Ensure orphaned object can set values correctly', () => {429 testModel.set('test', {'data': {name: 'abc'}});430 // When using a local obj, complete refresh of object can lead to it becoming431 // orphaned. Refresh model allows it to figure out its real version again.432 const data = testModel.get('test.data');433 testModel.set('test', {'data': {name: 'def'}});434 data.name = 'hmm';435 expect(testModel.get('test.data.name')).toBe('hmm');436 });437 test('Listener objects use proxy data not real data', () => {438 testModel.set('test.testing', {'name': 'bobbert'});439 const testing = testModel.get('test.testing');440 let count = 0;441 testing.on('update', (updated) => {442 count++;443 expect(updated.getContext()).toBe('test.testing');444 });445 testModel.set('test.testing', {'name': 'ziggy'});446 expect(count).toBe(1);447 });448});449describe('Listeners', () => {450 let testModel;451 beforeEach(() => {452 testModel = makeTestnewModel();453 });454 test('Add listener', () => {455 let count = 0;456 const events = [457 'update:name',458 'update:*',459 'change:name',460 'change:*',461 'all',462 'updated',463 ];464 const listener = {465 trigger(evt) {466 count++;467 expect(evt).toBe(events.shift());468 },469 };470 testModel.subscribe(listener);471 testModel.set('name', 'Bob');472 expect(count).toBe(6);473 });474 test('Add listener with namespace', () => {475 let count = 0;476 const events = [477 'potato:update:name',478 'potato:update:*',479 'potato:change:name',480 'potato:change:*',481 'potato:all',482 'potato:updated',483 ];484 const listener = {485 trigger(evt) {486 count++;487 expect(evt).toBe(events.shift());488 },489 };490 testModel.subscribe(listener, 'potato');491 testModel.set('name', 'Bob');492 expect(count).toBe(6);493 });494 test('remove listener', () => {495 let count = 0;496 const events = [497 // first listener498 'update:name',499 'test:update:name',500 'update:*',501 'test:update:*',502 'change:name',503 'test:change:name',504 'change:*',505 'test:change:*',506 'all',507 'test:all',508 'updated',509 'test:updated',510 // none namespaced sub removed511 'test:update:name',512 'test:update:*',513 'test:change:name',514 'test:change:*',515 'test:all',516 'test:updated',517 ];518 const listener = {519 trigger(evt) {520 count++;521 expect(evt).toBe(events.shift());522 },523 };524 testModel.subscribe(listener);525 testModel.subscribe(listener, 'test');526 testModel.set('name', 'Bob');527 expect(count).toBe(12);528 testModel.unsubscribe(listener);529 testModel.set('name', 'Jim');530 expect(count).toBe(18);531 testModel.unsubscribe(listener, 'test');532 testModel.set('name', 'Zippy');533 expect(count).toBe(18);534 });535});536describe('Native functionalty', () => {537 test('stringify', () => {538 const obj = {539 'hello': 'world',540 'test': [1, 2],541 };542 const test = newModel(obj);543 expect(JSON.stringify(test)).toBe(JSON.stringify(obj));544 expect(JSON.stringify(test.test)).toBe('[1,2]');545 });546 test('Object keys', () => {547 const obj = {548 'hello': 'world',549 'test': [1, 2],550 };551 const test = newModel(obj);552 expect(Object.keys(test)[0]).toBe('hello');553 expect(Object.keys(test)[1]).toBe('test');554 });555 test('Object values', () => {556 const obj = {557 'hello': 'world',558 'test': [1, 2],559 };560 const test = newModel(obj);561 expect(Object.values(test)[0]).toBe('world');562 });563 test('Object enteries', () => {564 const obj = {565 'hello': 'world',566 'test': [1, 2],567 };568 const test = newModel(obj);569 const result = Object.entries(test)[0];570 expect(result[0]).toBe('hello');571 expect(result[1]).toBe('world');572 });573 test('Array map', () => {574 let count = 0; let val = 1;575 const test = newModel({576 'test': [1, 2, 3],577 });578 test.test.map((v)=> {579 count++;580 expect(v).toBe(val++);581 });582 expect(count).toBe(3);583 });584 test('Spread', () => {585 const test = newModel({586 'test': [1, 2, 3],587 });588 const flat = [...test.test];589 expect(flat[0]).toBe(1);590 expect(flat[1]).toBe(2);591 expect(flat[2]).toBe(3);592 });593});594describe('Custom events', () => {595 test('Trigger custom event', () => {596 const testModel = makeTestnewModel();597 let called = 0;598 testModel.on('magic:helloworld', (d) => {599 expect(d.id).toBe(123);600 called++;601 });602 testModel.trigger('magic:helloworld', {id: 123});603 expect(called).toBe(1);604 });605 test('Trigger custom event via defer', () => {606 const testModel = makeTestnewModel();607 const stuff = testModel.get('stuff');608 let called = 0;609 stuff.on('magic', (d) => {610 expect(d.id).toBe(123);611 called++;612 });613 stuff.trigger('magic', {id: 123});614 expect(called).toBe(1);615 });616});617describe('Functions', () => {618 test('Can store functions', () => {619 const model = newModel({'name': 'bob'});620 model.set('abc', function() {621 return 'yarr';622 });623 model.set('echo', function(v) {624 return v;625 });626 expect(model.get('abc')()).toBe('yarr');627 expect(model.get('echo')('test')).toBe('test');628 expect(model.abc()).toBe('yarr');629 expect(model.echo('test')).toBe('test');630 });631 test('Can change function', () => {632 const model = newModel({'name': 'bob'});633 const method = function(v) {634 return v;635 };636 const types = [637 'CREATE',638 // No event on no change.639 'UPDATE',640 ];641 model.on('change:echo', (type, n, o) => {642 expect(type).toBe(types.shift());643 });644 model.set('echo', method);645 model.set('echo', method);646 model.set('echo', function(v) {647 return v;648 });649 });...
model-sync-rest-test.js
Source:model-sync-rest-test.js
1YUI.add('model-sync-rest-test', function (Y) {2var ArrayAssert = Y.ArrayAssert,3 Assert = Y.Assert,4 ObjectAssert = Y.ObjectAssert,5 suite,6 modelSyncRESTSuite;7// -- Global Suite -------------------------------------------------------------8suite = Y.AppTestSuite || (Y.AppTestSuite = new Y.Test.Suite('App'));9// -- ModelSync.REST Suite -----------------------------------------------------10modelSyncRESTSuite = new Y.Test.Suite('ModelSync.REST');11// -- ModelSync.REST: Lifecycle ------------------------------------------------12modelSyncRESTSuite.add(new Y.Test.Case({13 name: 'Lifecycle',14 setUp: function () {15 Y.TestModel = Y.Base.create('customModel', Y.Model, [Y.ModelSync.REST]);16 Y.TestModelList = Y.Base.create('testModelList', Y.ModelList, [Y.ModelSync.REST], {17 model: Y.TestModel18 });19 },20 tearDown: function () {21 delete Y.TestModel;22 delete Y.TestModelList;23 },24 'initializer should set the `root` property on the instance': function () {25 var model = new Y.TestModel({root: '/model/'}),26 modelList = new Y.TestModelList({root: '/list/'});27 Assert.areSame('/model/', model.root);28 Assert.areSame('/list/', modelList.root);29 },30 'initializer should set the `url` property on the instance': function () {31 var model = new Y.TestModel({url: '/model/123'}),32 modelList = new Y.TestModelList({url: '/model'});33 Assert.areSame('/model/123', model.url);34 Assert.areSame('/model', modelList.url);35 }36}));37// -- ModelSync.REST: Properties -----------------------------------------------38modelSyncRESTSuite.add(new Y.Test.Case({39 name: 'Properties',40 setUp: function () {41 Y.TestModel = Y.Base.create('customModel', Y.Model, [Y.ModelSync.REST]);42 Y.TestModelList = Y.Base.create('testModelList', Y.ModelList, [Y.ModelSync.REST], {43 model: Y.TestModel44 });45 },46 tearDown: function () {47 delete Y.TestModel;48 delete Y.TestModelList;49 },50 '`root` property should be an empty string by default': function () {51 var model = new Y.TestModel(),52 modelList = new Y.TestModelList();53 Assert.areSame('', model.root);54 Assert.areSame('', modelList.root);55 },56 '`url` property should be an empty string by default': function () {57 var model = new Y.TestModel(),58 modelList = new Y.TestModelList();59 Assert.areSame('', model.url);60 Assert.areSame('', modelList.url);61 },62 'Static `CSRF_TOKEN` should default to the value of `YUI.Env.CSRF_TOKEN`': function () {63 Assert.areSame('asdf1234', YUI.Env.CSRF_TOKEN);64 Assert.areSame(YUI.Env.CSRF_TOKEN, Y.ModelSync.REST.CSRF_TOKEN);65 }66}));67// -- ModelSync.REST: Methods --------------------------------------------------68modelSyncRESTSuite.add(new Y.Test.Case({69 name: 'Methods',70 setUp: function () {71 Y.TestModel = Y.Base.create('customModel', Y.Model, [Y.ModelSync.REST]);72 Y.TestModelList = Y.Base.create('testModelList', Y.ModelList, [Y.ModelSync.REST], {73 model: Y.TestModel74 });75 },76 tearDown: function () {77 delete Y.TestModel;78 delete Y.TestModelList;79 },80 'getURL() should return an empty string by default': function () {81 var model = new Y.TestModel(),82 modelList = new Y.TestModelList();83 Assert.isString(model.getURL());84 Assert.isString(modelList.getURL());85 Assert.areSame('', model.getURL());86 Assert.areSame('', modelList.getURL());87 },88 'getURL() of a model list should return the `root` of its model by default': function () {89 Y.TestModel.prototype.root = '/root/';90 var modelList = new Y.TestModelList();91 Assert.areSame('/root/', modelList.getURL());92 },93 'getURL() of a model list should return its `url` if defined': function () {94 Y.TestModel.prototype.root = '/root/';95 Y.TestModelList.prototype.url = '/list/';96 var modelList = new Y.TestModelList();97 Assert.areSame('/list/', modelList.getURL());98 modelList.url = '/users/';99 Assert.areSame('/users/', modelList.getURL());100 },101 'getURL() of a new model should return its `root` if defined': function () {102 Y.TestModel.prototype.root = '/root/';103 var model = new Y.TestModel();104 Assert.isTrue(model.isNew());105 Assert.areSame('/root/', model.getURL());106 model.root = '/users/';107 Assert.areSame('/users/', model.getURL());108 },109 'getURL() of a model should return its `root` when the `action` is "create"': function () {110 Y.TestModel.prototype.root = '/root/';111 var model = new Y.TestModel({id: 1});112 Assert.isFalse(model.isNew());113 Assert.areSame('/root/', model.getURL('create'));114 model.root = '/users/';115 Assert.areSame('/users/', model.getURL('create'));116 },117 'getURL() of a model should return its `root` joined with its `id` by default': function () {118 Y.TestModel.prototype.root = '/root';119 var model = new Y.TestModel({id: 1});120 Assert.isFalse(model.isNew());121 Assert.areSame('/root/1', model.getURL());122 model.root = '/users';123 Assert.areSame('/users/1', model.getURL());124 },125 'getURL() of a model should return its `root` joined with its `id` and normalize slashes': function () {126 var model = new Y.TestModel({id: 1});127 model.root = 'users';128 Assert.areSame('users/1', model.getURL());129 model.root = 'users/';130 Assert.areSame('users/1/', model.getURL());131 model.root = '/users';132 Assert.areSame('/users/1', model.getURL());133 model.root = '/users/';134 Assert.areSame('/users/1/', model.getURL());135 },136 'getURL() of a model should return its `url` if defined': function () {137 Y.TestModel.prototype.url = '/users/1';138 var model = new Y.TestModel({id: 'foo'});139 Assert.isFalse(model.isNew());140 Assert.areSame('/users/1', model.getURL());141 model.url = '/users/bar';142 Assert.areSame('/users/bar', model.getURL());143 },144 'getURL() should substitute tokenized `url`s with attribute values': function () {145 var modelList = new Y.TestModelList({url: '/{type}/'}),146 model;147 modelList.addAttr('type', {value: 'users'});148 Assert.areSame('users', modelList.get('type'));149 Assert.areSame('/users/', modelList.getURL());150 model = modelList.add({151 id : 1,152 type: modelList.get('type'),153 url : '/{type}/items/{id}/'154 });155 Assert.areSame(1, modelList.size());156 Assert.areSame('users', model.get('type'));157 Assert.areSame('/users/items/1/', model.getURL());158 },159 'getURL() should substitute tokenized `url`s with `options` values': function () {160 var model = new Y.TestModel({url: '/{type}/foo/'}),161 modelList = new Y.TestModelList({url: '/{type}/'});162 Assert.areSame('/users/foo/', model.getURL(null, {type: 'users'}));163 Assert.areSame('/users/', modelList.getURL(null, {type: 'users'}));164 },165 'getURL() should substitute tokenized `url`s with attribute and `options` values': function () {166 var modelList = new Y.TestModelList({url: '/{type}/?num={num}'}),167 model;168 modelList.addAttr('type', {value: 'users'});169 Assert.areSame('users', modelList.get('type'));170 Assert.areSame('/users/?num=10', modelList.getURL(null, {num: 10}));171 Assert.areSame('/losers/?num=10', modelList.getURL(null, {172 num : 10,173 type: 'losers'174 }));175 model = modelList.add({176 id : 1,177 url: '/{type}/items/{id}/'178 });179 Assert.areSame(1, modelList.size());180 Assert.areSame(1, model.get('id'));181 Assert.areSame('/users/items/1/', model.getURL(null, {type: 'users'}));182 Assert.areSame('/losers/items/foo/', model.getURL(null, {183 id : 'foo',184 type: 'losers'185 }));186 },187 'getURL() should URL-encode the `url` substitution values': function () {188 var model = new Y.TestModel({189 id : '123 456',190 url: '/model/{id}'191 });192 Assert.areSame('/model/123%20456', model.getURL());193 },194 'getURL() should not substitute Arrays, Objects, or Boolean values into the `url`' : function () {195 var model = new Y.TestModel({196 id : 'asdf',197 url: '/model/{foo}/{bar}/{baz}/{id}'198 });199 model.addAttrs({200 foo : {value: [1, 2, 3]},201 bar : {value: {zee: 'zee'}},202 baz : {value: true}203 });204 Assert.areSame('/model/{foo}/{bar}/{baz}/asdf', model.getURL());205 },206 'parse() should receive the full Y.io response object when `parseIOResponse is falsy': function () {207 var calls = 0,208 model = new Y.TestModel({name: 'Eric'});209 model.parseIOResponse = false;210 model.parse = function (res) {211 calls += 1;212 ObjectAssert.ownsKey('responseText', res);213 };214 // Overrides because `Y.io()` is too hard to test!215 model._sendSyncIORequest = function (config) {216 this._onSyncIOSuccess(0, {217 responseText: '{"id":1, "name":"Eric"}'218 }, {219 callback: config.callback220 });221 };222 model.save();223 Assert.areSame(1, calls);224 },225 'parseIOResponse() should alter the response passed to `parse()`': function () {226 var calls = 0,227 model = new Y.TestModel({name: 'Eric'});228 model.parseIOResponse = function () {229 return {foo: 'bar'};230 };231 model.parse = function (res) {232 calls += 1;233 ObjectAssert.ownsKey('foo', res);234 Assert.areSame('bar', res.foo);235 };236 // Overrides because `Y.io()` is too hard to test!237 model._sendSyncIORequest = function (config) {238 this._onSyncIOSuccess(0, {239 responseText: '{"id":1, "name":"Eric"}'240 }, {241 callback: config.callback242 });243 };244 model.save();245 Assert.areSame(1, calls);246 },247 'serialize() should return a JSON string by default': function () {248 var model = new Y.TestModel({id: 123});249 Assert.isString(model.serialize());250 Assert.areSame(Y.JSON.stringify(model), model.serialize());251 Assert.areSame(Y.JSON.stringify(model.toJSON()), model.serialize());252 },253 'serialize() should be passed the `sync()` `action`': function () {254 var noop = function () {},255 model = new Y.TestModel(),256 called = 0;257 // Overrides to a noop because we don't care about sending a request.258 model._sendSyncIORequest = noop;259 model.serialize = function (action) {260 called += 1;261 Assert.isTrue(this.isNew());262 Assert.areSame('create', action);263 };264 model.save();265 Assert.areSame(1, called);266 }267}));268// -- ModelSync.REST: Sync -----------------------------------------------------269modelSyncRESTSuite.add(new Y.Test.Case({270 name: 'Sync',271 setUp: function () {272 this._emulateHTTP = Y.ModelSync.REST.EMULATE_HTTP;273 Y.TestModel = Y.Base.create('customModel', Y.Model, [Y.ModelSync.REST]);274 Y.TestModelList = Y.Base.create('testModelList', Y.ModelList, [Y.ModelSync.REST], {275 model: Y.TestModel276 });277 },278 tearDown: function () {279 delete Y.TestModel;280 delete Y.TestModelList;281 Y.ModelSync.REST.EMULATE_HTTP = this._emulateHTTP;282 },283 'load() should perform a GET XHR the `url` of the model': function () {284 Y.TestModel.prototype.root = '/root/';285 var model = new Y.TestModel({id: 1});286 // Overrides because `Y.io()` is too hard to test!287 model._sendSyncIORequest = function (config) {288 Assert.areSame('read', config.action);289 Assert.areSame('application/json', config.headers['Accept']);290 Assert.areSame('GET', config.method);291 Assert.areSame(30000, config.timeout);292 Assert.areSame('/root/1/', config.url);293 Assert.isUndefined(config.entity);294 Assert.isUndefined(config.headers['Content-Type']);295 Assert.isUndefined(config.headers['X-CSRF-Token']);296 this._onSyncIOSuccess(0, {297 responseText: '{"id":1, "name":"Eric"}'298 }, {299 callback: config.callback300 });301 };302 model.load();303 Assert.areSame('Eric', model.get('name'));304 },305 'load() should perform a GET XHR the `root` of the model list': function () {306 Y.TestModel.prototype.root = '/root/';307 var modelList = new Y.TestModelList();308 // Overrides because `Y.io()` is too hard to test!309 modelList._sendSyncIORequest = function (config) {310 Assert.areSame('read', config.action);311 Assert.areSame('application/json', config.headers['Accept']);312 Assert.areSame('GET', config.method);313 Assert.areSame(30000, config.timeout);314 Assert.areSame('/root/', config.url);315 Assert.isUndefined(config.entity);316 Assert.isUndefined(config.headers['Content-Type']);317 Assert.isUndefined(config.headers['X-CSRF-Token']);318 this._onSyncIOSuccess(0, {319 responseText: '[{"id":1, "name":"Eric"}]'320 }, {321 callback: config.callback322 });323 };324 modelList.load();325 Assert.areSame(1, modelList.size());326 Assert.areSame(1, modelList.item(0).get('id'));327 Assert.areSame('Eric', modelList.item(0).get('name'));328 },329 'save() should perform a POST XHR to the `root` of a new model': function () {330 Y.TestModel.prototype.root = '/root/';331 var model = new Y.TestModel({name: 'Eric'});332 // Overrides because `Y.io()` is too hard to test!333 model._sendSyncIORequest = function (config) {334 Assert.areSame('create', config.action);335 Assert.areSame('{"name":"Eric"}', config.entity);336 Assert.areSame('application/json', config.headers['Accept']);337 Assert.areSame('application/json', config.headers['Content-Type']);338 Assert.areSame('asdf1234', config.headers['X-CSRF-Token']);339 Assert.areSame('POST', config.method);340 Assert.areSame(30000, config.timeout);341 Assert.areSame('/root/', config.url);342 this._onSyncIOSuccess(0, {343 responseText: '{"id":1, "name":"Eric"}'344 }, {345 callback: config.callback346 });347 };348 Assert.isTrue(model.isNew());349 model.save();350 Assert.isFalse(model.isNew());351 Assert.areSame(1, model.get('id'));352 },353 'save() should perform a PUT XHR to the `url` an exiting model': function () {354 Y.TestModel.prototype.root = '/root/';355 var model = new Y.TestModel({id: 1});356 // Overrides because `Y.io()` is too hard to test!357 model._sendSyncIORequest = function (config) {358 Assert.areSame('update', config.action);359 Assert.areSame('{"id":1,"name":"Eric"}', config.entity);360 Assert.areSame('application/json', config.headers['Accept']);361 Assert.areSame('application/json', config.headers['Content-Type']);362 Assert.areSame('asdf1234', config.headers['X-CSRF-Token']);363 Assert.areSame('PUT', config.method);364 Assert.areSame(30000, config.timeout);365 Assert.areSame('/root/1/', config.url);366 this._onSyncIOSuccess(0, {367 responseText: ''368 }, {369 callback: config.callback370 });371 };372 Assert.isFalse(model.isNew());373 model.set('name', 'Eric');374 model.save();375 },376 'destroy({remove: true}) should perform a DELETE XHR to the `url` an exiting model': function () {377 Y.TestModel.prototype.root = '/root/';378 var model = new Y.TestModel({id: 1});379 // Overrides because `Y.io()` is too hard to test!380 model._sendSyncIORequest = function (config) {381 Assert.areSame('delete', config.action);382 Assert.areSame('application/json', config.headers['Accept']);383 Assert.areSame('asdf1234', config.headers['X-CSRF-Token']);384 Assert.areSame('DELETE', config.method);385 Assert.areSame(30000, config.timeout);386 Assert.areSame('/root/1/', config.url);387 Assert.isUndefined(config.entity);388 Assert.isUndefined(config.headers['Content-Type']);389 this._onSyncIOSuccess(0, {390 responseText: ''391 }, {392 callback: config.callback393 });394 };395 Assert.isFalse(model.isNew());396 model.destroy({remove: true});397 },398 'EMULATE_HTTP should use POST instead of PUT or DELETE XHRs': function () {399 Y.ModelSync.REST.EMULATE_HTTP = true;400 Y.TestModel.prototype.root = '/root/';401 var model = new Y.TestModel({id: 1}),402 calls = 0;403 // Overrides because `Y.io()` is too hard to test!404 model._sendSyncIORequest = function (config) {405 var action = config.action;406 calls += 1;407 Assert.areSame('POST', config.method);408 Assert.isTrue(action === 'update' || action === 'delete');409 if (action === 'update') {410 Assert.areSame('PUT', config.headers['X-HTTP-Method-Override']);411 }412 if (action === 'delete') {413 Assert.areSame('DELETE', config.headers['X-HTTP-Method-Override']);414 }415 this._onSyncIOSuccess(0, {416 responseText: ''417 }, {418 callback: config.callback419 });420 };421 Assert.isFalse(model.isNew());422 model.set('name', 'Eric').save();423 model.destroy({remove: true});424 Assert.areSame(2, calls);425 },426 'sync() should accept `csrfToken`, `headers`, and `timeout` options': function () {427 Y.TestModel.prototype.root = '/root/';428 var model = new Y.TestModel({name: 'Eric'});429 // Overrides because `Y.io()` is too hard to test!430 model._sendSyncIORequest = function (config) {431 Assert.areSame('application/xml', config.headers['Content-Type']);432 Assert.areSame('blabla', config.headers['X-CSRF-Token']);433 Assert.areSame(10000, config.timeout);434 this._onSyncIOSuccess(0, {435 responseText: '{"id":1, "name":"Eric"}'436 }, {437 callback: config.callback438 });439 };440 Assert.isTrue(model.isNew());441 model.save({442 csrfToken: 'blabla',443 headers : {'Content-Type': 'application/xml'},444 timeout : 10000445 });446 Assert.isFalse(model.isNew());447 Assert.areSame(1, model.get('id'));448 },449 'Failed sync() calls should pass the HTTP status code and message to the callback': function () {450 Y.TestModel.prototype.root = '/root/';451 var model = new Y.TestModel({id: 1});452 // Overrides because `Y.io()` is too hard to test!453 model._sendSyncIORequest = function (config) {454 this._onSyncIOFailure(0, {455 status : 404,456 statusText: 'Not Found'457 }, {458 callback: config.callback459 });460 };461 model.load(function (err) {462 Assert.areSame(404, err.code);463 Assert.areSame('Not Found', err.msg);464 });465 Assert.isUndefined(model.get('name'));466 }467}));468suite.add(modelSyncRESTSuite);469}, '@VERSION@', {470 requires: ['model-sync-rest', 'model', 'model-list', 'test']...
SplitOpPanelModelSpec.js
Source:SplitOpPanelModelSpec.js
1describe('SplitOpPanelModel Test', () => {2 describe('fromDag() sould work', () => {3 it('Case: invalid input', () => {4 let error = null;5 try {6 const testModel = SplitOpPanelModel.fromDag(null);7 expect(testModel != null).to.equal(true);8 } catch(e) {9 error = e;10 }11 expect(error.message).to.equal("Cannot read property \'getParents\' of null");12 });13 it('Case: normal case', () => {14 const allColumns = createDefaultColumns();15 const dagNode = {16 getParents: () => {17 return [18 {19 getLineage: () => {20 return {21 getColumns: () => allColumns22 }23 }24 },25 null26 ];27 },28 getParam: () => createDefaultDagInput()29 };30 let error = null;31 try {32 const testModel = SplitOpPanelModel.fromDag(dagNode);33 expect(testModel != null).to.equal(true);34 expect(testModel._allColMap.size).to.equal(allColumns.length);35 } catch(e) {36 error = e;37 }38 expect(error == null).to.equal(true);39 });40 });41 describe('fromDagInput() should work', () => {42 it('Case: regular delimiter', () => {43 const delimiter = ',';44 const expectedModel = createDefaultModel(delimiter);45 const testDagInput = createDefaultDagInput(delimiter);46 const testModel = SplitOpPanelModel.fromDagInput(47 expectedModel._allColMap, testDagInput48 );49 expect(testModel._delimiter).to.equal(expectedModel._delimiter);50 expect(testModel._sourceColName).to.equal(expectedModel._sourceColName);51 expect(testModel._destColNames.length).to.equal(expectedModel._destColNames.length);52 expect(testModel._includeErrRow).to.equal(expectedModel._includeErrRow);53 });54 it('Case: special delimiter', () => {55 const delimiter = '\\"';56 const expectedModel = createDefaultModel(delimiter);57 const testDagInput = createDefaultDagInput(delimiter);58 const testModel = SplitOpPanelModel.fromDagInput(59 expectedModel._allColMap, testDagInput60 );61 expect(testModel._delimiter).to.equal(expectedModel._delimiter);62 expect(testModel._sourceColName).to.equal(expectedModel._sourceColName);63 expect(testModel._destColNames.length).to.equal(expectedModel._destColNames.length);64 expect(testModel._includeErrRow).to.equal(expectedModel._includeErrRow);65 });66 });67 describe('toDagInput() should work', () => {68 it('Case: regular delimiter', () => {69 const delimiter = ',';70 const testModel = createDefaultModel(delimiter);71 const testDagInput = createDefaultDagInput(delimiter);72 expect(testModel.toDagInput()).to.deep.equal(testDagInput);73 });74 it('Case: " delimiter', () => {75 const delimiter = '"';76 const testModel = createDefaultModel(delimiter);77 const testDagInput = createDefaultDagInput(delimiter);78 expect(testModel.toDagInput()).to.deep.equal(testDagInput);79 });80 it('Case: \\ delimiter', () => {81 const delimiter = '\\';82 const testModel = createDefaultModel(delimiter);83 const testDagInput = createDefaultDagInput(delimiter);84 expect(testModel.toDagInput()).to.deep.equal(testDagInput);85 });86 });87 describe('getColNameSetWithNew() should work', () => {88 it('Case: all columns + dest columns', () => {89 const model = createDefaultModel();90 const nameSet = model.getColNameSetWithNew(-1);91 const expectedSize = model._allColMap.size + model._destColNames.length;92 expect(nameSet.size).to.equal(expectedSize);93 });94 it('Case: all columns except the first dest column', () => {95 const model = createDefaultModel();96 const nameSet = model.getColNameSetWithNew(0);97 const expectedSize = model._allColMap.size + model._destColNames.length - 1;98 expect(nameSet.size).to.equal(expectedSize);99 });100 });101 describe('validateInputData() should work', () => {102 it('Case: valid data', () => {103 const model = createDefaultModel();104 let error = null;105 try {106 model.validateInputData();107 } catch(e) {108 error = e;109 }110 expect(error == null).to.equal(true);111 });112 it('Case: empty source column', () => {113 const model = createDefaultModel();114 let error;115 try {116 error = null;117 model._sourceColName = null;118 model.validateInputData();119 } catch(e) {120 error = e;121 }122 expect(error != null).to.equal(true)123 expect(error.message).to.equal('Source column cannot be empty');124 try {125 error = null;126 model._sourceColName = '';127 model.validateInputData();128 } catch(e) {129 error = e;130 }131 expect(error != null).to.equal(true)132 expect(error.message).to.equal('Source column cannot be empty');133 });134 it('Case: source column not exist', () => {135 const model = createDefaultModel();136 let error;137 try {138 error = null;139 model._sourceColName = 'colNotInColMap';140 model.validateInputData();141 } catch(e) {142 error = e;143 }144 expect(error != null).to.equal(true)145 expect(error.message).to.equal(`Source column(${model._sourceColName}) does not exist`);146 });147 it('Case: empty delimiter', () => {148 const model = createDefaultModel();149 let error;150 try {151 error = null;152 model._delimiter = null;153 model.validateInputData();154 } catch(e) {155 error = e;156 }157 expect(error != null).to.equal(true)158 expect(error.message).to.equal('Delimiter cannot be empty');159 try {160 error = null;161 model._delimiter = '';162 model.validateInputData();163 } catch(e) {164 error = e;165 }166 expect(error != null).to.equal(true)167 expect(error.message).to.equal('Delimiter cannot be empty');168 });169 it('Case: invalid dest column name', () => {170 const model = createDefaultModel();171 let error;172 // Prefixed column name173 try {174 error = null;175 model._destColNames[0] = 'testPrefix::col-split';176 model.validateInputData();177 } catch(e) {178 error = e;179 }180 expect(error != null).to.equal(true)181 expect(error.message).to.equal(`Dest column(${model._destColNames[0]}) cannot have prefix`);182 // Dup column name183 try {184 error = null;185 model._destColNames[0] = 'col#1';186 model.validateInputData();187 } catch(e) {188 error = e;189 }190 expect(error != null).to.equal(true)191 expect(error.message).to.equal(`Duplicate column "${model._destColNames[0]}"`);192 });193 });194 describe('autofillEmptyColNames() should work', () => {195 it('Case: all dest names are empty', () => {196 const model = createDefaultModel();197 for (let i = 0; i < model._destColNames.length; i ++) {198 model._destColNames[i] = '';199 }200 model.autofillEmptyColNames();201 for (const name of model._destColNames) {202 expect(name.length > 0).to.equal(true);203 }204 });205 it ('Case: some of dest names are empty', () => {206 const model = createDefaultModel();207 model._destColNames[0] = '';208 model.autofillEmptyColNames();209 for (const name of model._destColNames) {210 expect(name.length > 0).to.equal(true);211 }212 });213 });214 describe('setter/getter should work', () => {215 let testModel;216 before(() => {217 testModel = createDefaultModel();218 });219 afterEach(() => {220 testModel = createDefaultModel();221 });222 it('title', () => {223 testModel._title = 'test title';224 expect(testModel.getTitle()).to.equal('test title');225 });226 it('instrStr', () => {227 testModel._instrStr = 'test instr';228 expect(testModel.getInstrStr()).to.equal('test instr');229 });230 it('delimiter', () => {231 testModel.setDelimiter('test delimiter');232 expect(testModel._delimiter).to.equal('test delimiter');233 expect(testModel.getDelimiter()).to.equal('test delimiter');234 });235 it('column map', () => {236 expect(testModel.getColumnMap().size).to.equal(testModel._allColMap.size);237 });238 it('source column name', () => {239 testModel.setSourceColName('test col name');240 expect(testModel._sourceColName).to.equal('test col name');241 expect(testModel.getSourceColName()).to.equal(testModel._sourceColName);242 });243 it('dest column names', () => {244 // Get number245 expect(testModel.getNumDestCols()).to.equal(testModel._destColNames.length);246 const originDestNames = testModel._destColNames.map((v) => v);247 // Set new number == current number248 testModel.setNumDestCols(originDestNames.length);249 expect(testModel.getNumDestCols()).to.equal(originDestNames.length);250 for (let i = 0; i < originDestNames.length; i ++) {251 expect(testModel._destColNames[i]).to.equal(originDestNames[i]);252 }253 testModel._destColNames = originDestNames.map((v) => v);254 // Set new number < current number255 testModel.setNumDestCols(originDestNames.length - 1);256 expect(testModel.getNumDestCols()).to.equal(originDestNames.length - 1);257 for (let i = 0; i < originDestNames.length - 1; i ++) {258 expect(testModel._destColNames[i]).to.equal(originDestNames[i]);259 }260 testModel._destColNames = originDestNames.map((v) => v);261 // Set new number > current number262 testModel.setNumDestCols(originDestNames.length + 1);263 expect(testModel.getNumDestCols()).to.equal(originDestNames.length + 1);264 for (let i = 0; i < originDestNames.length; i ++) {265 expect(testModel._destColNames[i]).to.equal(originDestNames[i]);266 }267 testModel._destColNames = originDestNames.map((v) => v);268 // Get by index269 for (let i = 0; i < originDestNames.length; i ++) {270 expect(testModel.getDestColNameByIndex(i)).to.equal(testModel._destColNames[i]);271 }272 testModel._destColNames = originDestNames.map((v) => v);273 // Get all dest names274 const allDestNames = testModel.getDestColNames();275 expect(allDestNames.length).to.equal(testModel._destColNames.length);276 for (let i = 0; i < allDestNames.length; i ++) {277 expect(allDestNames[i]).to.equal(testModel._destColNames[i]);278 }279 allDestNames[0] = allDestNames[0] + "mod";280 expect(allDestNames[0]).to.not.equal(testModel._destColNames[0]);281 testModel._destColNames = originDestNames.map((v) => v);282 // Set one column name283 const oneColName = testModel._destColNames[0];284 testModel.setDestColName(0, oneColName + 'mod');285 expect(testModel._destColNames[0]).to.equal(oneColName + 'mod');286 for (let i = 1; i < originDestNames.length; i ++) {287 expect(testModel._destColNames[i]).to.equal(originDestNames[i]);288 }289 testModel._destColNames = originDestNames.map((v) => v);290 });291 it('icv', () => {292 testModel.setIncludeErrRow(true);293 expect(testModel.isIncludeErrRow()).to.equal(true);294 testModel.setIncludeErrRow(false);295 expect(testModel.isIncludeErrRow()).to.equal(false);296 });297 });298 function genProgCols(colPrefix, count, sep='#') {299 const cols = new Array(count);300 for (let i = 0; i < count; i ++) {301 const colName = `${colPrefix}${sep}${i + 1}`;302 const frontName = xcHelper.parsePrefixColName(colName).name;303 cols[i] = ColManager.newPullCol(frontName, colName, ColumnType.string);304 }305 return cols;306 }307 function createDefaultColumns() {308 return genProgCols('prefix::col', 2).concat(genProgCols('col', 2));309 }310 function createDefaultModel(delimiter = '/') {311 const allColumns = createDefaultColumns().reduce((map, progCol) => {312 map.set(progCol.getBackColName(), progCol);313 return map;314 }, new Map());315 const model = new SplitOpPanelModel();316 model._delimiter = delimiter;317 model._sourceColName = 'col#1';318 model._destColNames = ['col-split-1', 'col-split-2'];319 model._allColMap = allColumns;320 return model;321 }322 function createDefaultDagInput(delimiter = '/') {323 delimiter = delimiter.replace(/\\/g, '\\\\').replace(/\"/g, '\\"');324 return {325 eval: [326 { evalString: `cut(col#1,1,"${delimiter}")`, newField: 'col-split-1' },327 { evalString: `cut(col#1,2,"${delimiter}")`, newField: 'col-split-2' },328 ],329 icv: false,330 "outputTableName":""331 };332 }...
async-observer.test.js
Source:async-observer.test.js
1// Copyright IBM Corp. 2015,2016. All Rights Reserved.2// Node module: loopback-datasource-juggler3// This file is licensed under the MIT License.4// License text available at https://opensource.org/licenses/MIT5'use strict';6const ModelBuilder = require('../').ModelBuilder;7const should = require('./init');8const Promise = require('bluebird');9describe('async observer', function() {10 let TestModel;11 beforeEach(function defineTestModel() {12 const modelBuilder = new ModelBuilder();13 TestModel = modelBuilder.define('TestModel', {name: String});14 });15 it('calls registered async observers', function(done) {16 const notifications = [];17 TestModel.observe('before', pushAndNext(notifications, 'before'));18 TestModel.observe('after', pushAndNext(notifications, 'after'));19 TestModel.notifyObserversOf('before', {}, function(err) {20 if (err) return done(err);21 notifications.push('call');22 TestModel.notifyObserversOf('after', {}, function(err) {23 if (err) return done(err);24 notifications.should.eql(['before', 'call', 'after']);25 done();26 });27 });28 });29 it('allows multiple observers for the same operation', function(done) {30 const notifications = [];31 TestModel.observe('event', pushAndNext(notifications, 'one'));32 TestModel.observe('event', pushAndNext(notifications, 'two'));33 TestModel.notifyObserversOf('event', {}, function(err) {34 if (err) return done(err);35 notifications.should.eql(['one', 'two']);36 done();37 });38 });39 it('allows multiple operations to be notified in one call', function(done) {40 const notifications = [];41 TestModel.observe('event1', pushAndNext(notifications, 'one'));42 TestModel.observe('event2', pushAndNext(notifications, 'two'));43 TestModel.notifyObserversOf(['event1', 'event2'], {}, function(err) {44 if (err) return done(err);45 notifications.should.eql(['one', 'two']);46 done();47 });48 });49 it('inherits observers from base model', function(done) {50 const notifications = [];51 TestModel.observe('event', pushAndNext(notifications, 'base'));52 const Child = TestModel.extend('Child');53 Child.observe('event', pushAndNext(notifications, 'child'));54 Child.notifyObserversOf('event', {}, function(err) {55 if (err) return done(err);56 notifications.should.eql(['base', 'child']);57 done();58 });59 });60 it('allow multiple operations to be notified with base models', function(done) {61 const notifications = [];62 TestModel.observe('event1', pushAndNext(notifications, 'base1'));63 TestModel.observe('event2', pushAndNext(notifications, 'base2'));64 const Child = TestModel.extend('Child');65 Child.observe('event1', pushAndNext(notifications, 'child1'));66 Child.observe('event2', pushAndNext(notifications, 'child2'));67 Child.notifyObserversOf(['event1', 'event2'], {}, function(err) {68 if (err) return done(err);69 notifications.should.eql(['base1', 'child1', 'base2', 'child2']);70 done();71 });72 });73 it('does not modify observers in the base model', function(done) {74 const notifications = [];75 TestModel.observe('event', pushAndNext(notifications, 'base'));76 const Child = TestModel.extend('Child');77 Child.observe('event', pushAndNext(notifications, 'child'));78 TestModel.notifyObserversOf('event', {}, function(err) {79 if (err) return done(err);80 notifications.should.eql(['base']);81 done();82 });83 });84 it('always calls inherited observers', function(done) {85 const notifications = [];86 TestModel.observe('event', pushAndNext(notifications, 'base'));87 const Child = TestModel.extend('Child');88 // Important: there are no observers on the Child model89 Child.notifyObserversOf('event', {}, function(err) {90 if (err) return done(err);91 notifications.should.eql(['base']);92 done();93 });94 });95 it('can remove observers', function(done) {96 const notifications = [];97 function call(ctx, next) {98 notifications.push('call');99 process.nextTick(next);100 }101 TestModel.observe('event', call);102 TestModel.removeObserver('event', call);103 TestModel.notifyObserversOf('event', {}, function(err) {104 if (err) return done(err);105 notifications.should.eql([]);106 done();107 });108 });109 it('can clear all observers', function(done) {110 const notifications = [];111 function call(ctx, next) {112 notifications.push('call');113 process.nextTick(next);114 }115 TestModel.observe('event', call);116 TestModel.observe('event', call);117 TestModel.observe('event', call);118 TestModel.clearObservers('event');119 TestModel.notifyObserversOf('event', {}, function(err) {120 if (err) return done(err);121 notifications.should.eql([]);122 done();123 });124 });125 it('handles no observers', function(done) {126 TestModel.notifyObserversOf('no-observers', {}, function(err) {127 // the test passes when no error was raised128 done(err);129 });130 });131 it('passes context to final callback', function(done) {132 const context = {};133 TestModel.notifyObserversOf('event', context, function(err, ctx) {134 (ctx || 'null').should.equal(context);135 done();136 });137 });138 describe('notifyObserversAround', function() {139 let notifications;140 beforeEach(function() {141 notifications = [];142 TestModel.observe('before execute',143 pushAndNext(notifications, 'before execute'));144 TestModel.observe('after execute',145 pushAndNext(notifications, 'after execute'));146 });147 it('should notify before/after observers', function(done) {148 const context = {};149 function work(done) {150 process.nextTick(function() {151 done(null, 1);152 });153 }154 TestModel.notifyObserversAround('execute', context, work,155 function(err, result) {156 notifications.should.eql(['before execute', 'after execute']);157 result.should.eql(1);158 done();159 });160 });161 it('should allow work with context', function(done) {162 const context = {};163 function work(context, done) {164 process.nextTick(function() {165 done(null, 1);166 });167 }168 TestModel.notifyObserversAround('execute', context, work,169 function(err, result) {170 notifications.should.eql(['before execute', 'after execute']);171 result.should.eql(1);172 done();173 });174 });175 it('should notify before/after observers with multiple results',176 function(done) {177 const context = {};178 function work(done) {179 process.nextTick(function() {180 done(null, 1, 2);181 });182 }183 TestModel.notifyObserversAround('execute', context, work,184 function(err, r1, r2) {185 r1.should.eql(1);186 r2.should.eql(2);187 notifications.should.eql(['before execute', 'after execute']);188 done();189 });190 });191 it('should allow observers to skip other ones',192 function(done) {193 TestModel.observe('before invoke',194 function(context, next) {195 notifications.push('before invoke');196 context.end(null, 0);197 });198 TestModel.observe('after invoke',199 pushAndNext(notifications, 'after invoke'));200 const context = {};201 function work(done) {202 process.nextTick(function() {203 done(null, 1, 2);204 });205 }206 TestModel.notifyObserversAround('invoke', context, work,207 function(err, r1) {208 r1.should.eql(0);209 notifications.should.eql(['before invoke']);210 done();211 });212 });213 it('should allow observers to tweak results',214 function(done) {215 TestModel.observe('after invoke',216 function(context, next) {217 notifications.push('after invoke');218 context.results = [3];219 next();220 });221 const context = {};222 function work(done) {223 process.nextTick(function() {224 done(null, 1, 2);225 });226 }227 TestModel.notifyObserversAround('invoke', context, work,228 function(err, r1) {229 r1.should.eql(3);230 notifications.should.eql(['after invoke']);231 done();232 });233 });234 });235 it('resolves promises returned by observers', function(done) {236 TestModel.observe('event', function(ctx) {237 return Promise.resolve('value-to-ignore');238 });239 TestModel.notifyObserversOf('event', {}, function(err, ctx) {240 // the test times out when the promises are not supported241 done();242 });243 });244 it('handles rejected promise returned by an observer', function(done) {245 const testError = new Error('expected test error');246 TestModel.observe('event', function(ctx) {247 return Promise.reject(testError);248 });249 TestModel.notifyObserversOf('event', {}, function(err, ctx) {250 err.should.eql(testError);251 done();252 });253 });254 it('returns a promise when no callback is provided', function() {255 const context = {value: 'a-test-context'};256 const p = TestModel.notifyObserversOf('event', context);257 (p !== undefined).should.be.true;258 return p.then(function(result) {259 result.should.eql(context);260 });261 });262 it('returns a rejected promise when no callback is provided', function() {263 const testError = new Error('expected test error');264 TestModel.observe('event', function(ctx, next) { next(testError); });265 const p = TestModel.notifyObserversOf('event', context);266 return p.then(267 function(result) {268 throw new Error('The promise should have been rejected.');269 },270 function(err) {271 err.should.eql(testError);272 }273 );274 });275});276function pushAndNext(array, value) {277 return function(ctx, next) {278 array.push(value);279 process.nextTick(next);280 };...
Using AI Code Generation
1const { testModel } = require('qawolf');2const { launch } = require('qawolf');3const { testModel } = require('qawolf');4const { launch } = require('qawolf');5const { testModel } = require('qawolf');6const { launch } = require('qawolf');7const { testModel } = require('qawolf');8const { launch } = require('qawolf');9const { testModel } = require('qawolf');10const { launch } = require('qawolf');11const { testModel } = require('qawolf');12const { launch } = require('qawolf');13const { testModel } = require('qawolf');14const { launch } = require('qawolf');15const { testModel } = require('qawolf');16const { launch } = require('qawolf');17const { testModel } = require('qawolf');18const { launch } = require('qawolf');19const { testModel } = require('qawolf');20const { launch } = require('qawolf');21const { testModel } = require('qawolf');22const { launch } = require('qawolf');23const { testModel } = require('qawolf');24const { launch } = require('qawolf');25const { testModel } = require('qawolf');26const { launch } = require('qawolf');27const { testModel } = require('qawolf');28const { launch } = require('qawolf');29const { testModel } = require('q
Using AI Code Generation
1const { testModel } = require("qawolf");2test("test", async () => {3 const browser = await chromium.launch();4 const context = await browser.newContext();5 const page = await context.newPage();6 await testModel(page, "testModel");7 await browser.close();8});9const { testModel } = require("qawolf");10test("test", async () => {11 const browser = await chromium.launch();12 const context = await browser.newContext();13 const page = await context.newPage();14 await testModel(page, "testModel");15 await browser.close();16});
Using AI Code Generation
1const { testModel } = require('qawolf');2const { launch } = require('qawolf');3const { devices } = require('qawolf');4const iPhone = devices['iPhone 11 Pro'];5test('test', async () => {6 await testModel(browser);7});8test('test', async () => {9 await testModel(browser);10});11test('test', async () => {12 await testModel(browser);13});14test('test', async () => {15 await testModel(browser, { name: 'my test' });16});17test('test', async () => {18 await testModel(browser, { name: 'my test', recordVideo: true });19});20test('test', async () => {21 await testModel(browser, { name: 'my test', recordVideo: true, videoSize: { width: 100, height: 100 } });22});23testModel(browser: Browser, options?: { name?: string; recordVideo?: boolean; videoSize?: { width: number; height
Using AI Code Generation
1const testModel = require('./testModel.js');2(async () => {3 const browser = await qawolf.launch();4 await testModel(page);5 await qawolf.stopVideos();6 await browser.close();7})();8const qawolf = require("qawolf");9module.exports = async function testModel(page) {10 await page.click("#gb > div.gb_Qb > a");11 await page.type("#identifierId", "
Using AI Code Generation
1const { testModel } = require("qawolf");2test("Test", async () => {3 const browser = await testModel({4 });5 await browser.close();6});7const { testModel } = require("qawolf");8test("Test", async () => {9 const browser = await testModel({10 });11 await browser.close();12});13const { testModel } = require("qawolf");14test("Test", async () => {15 const browser = await testModel({16 });17 await browser.close();18});19const { testModel } = require("qawolf");20test("Test", async () => {21 const browser = await testModel({22 });23 await browser.close();24});25const { testModel } = require("qawolf");26test("Test", async () => {27 const browser = await testModel({28 });29 await browser.close();30});31const { testModel } = require("qawolf");32test("Test", async () => {33 const browser = await testModel({34 });35 await browser.close();36});37const { testModel } = require
Using AI Code Generation
1const { testModel } = require("qawolf");2const { launch } = require("qawolf");3const { testModel } = require("qawolf");4const { launch } = require("qawolf");5const { testModel } = require("qawolf");6const { launch } = require("qawolf");7const { testModel } = require("qawolf");8const { launch } = require("qawolf");9const { testModel } = require("qawolf");10const { launch } = require("qawolf");11const { testModel } = require("qawolf");12const { launch } = require("qawolf");13const { testModel } = require("qawolf");14const { launch } = require("qawolf");15const { testModel } = require("qawolf");16const { launch } = require("qawolf");17const { testModel } = require("qawolf");18const { launch } = require("qawolf");19const { testModel } = require("qawolf");20const { launch } = require("qawolf");21const { testModel } = require("qawolf");22const { launch } = require("qawolf");23const { testModel } = require("qawolf");24const { launch } = require("qawolf");25const { testModel } = require("qawolf");26const { launch } = require("qawolf");27const { testModel } = require("qawolf");28const { launch } = require("qawolf");
Using AI Code Generation
1const testModel = require('./models/qawolf');2testModel.testModel();3const testModel = () => {4 console.log("This is a test model");5};6module.exports = {7};8const qawolf = require("qawolf");9const testModel = () => {10 console.log("This is a test model");11};12module.exports = {13};14const qawolf = require("qawolf");15const testModel = () => {16 console.log("This is a test model");17};18module.exports = {19};
Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!