Best JavaScript code snippet using wpt
test.js
Source:test.js
1// Copyright 2013 Google Inc.2// Licensed under the Apache License, Version 2.0 (the "License");3// you may not use this file except in compliance with the License.4// You may obtain a copy of the License at5//6// http://www.apache.org/licenses/LICENSE-2.07//8// Unless required by applicable law or agreed to in writing, software9// distributed under the License is distributed on an "AS IS" BASIS,10// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.11// See the License for the specific language governing permissions and12// limitations under the License.13var observer;14var callbackArgs = undefined;15var callbackInvoked = false;16function callback() {17 callbackArgs = Array.prototype.slice.apply(arguments);18 callbackInvoked = true;19}20function doSetup() {}21function doTeardown() {22 callbackInvoked = false;23 callbackArgs = undefined;24}25function assertNoChanges() {26 if (observer)27 observer.deliver();28 assert.isFalse(callbackInvoked);29 assert.isUndefined(callbackArgs);30}31var createObject = ('__proto__' in {}) ?32 function(obj) { return obj; } :33 function(obj) {34 var proto = obj.__proto__;35 if (!proto)36 return obj;37 var newObject = Object.create(proto);38 Object.getOwnPropertyNames(obj).forEach(function(name) {39 Object.defineProperty(newObject, name,40 Object.getOwnPropertyDescriptor(obj, name));41 });42 return newObject;43 };44suite('Basic Tests', function() {45 test('Exception Doesnt Stop Notification', function() {46 var model = [1];47 var count = 0;48 var observer1 = new ObjectObserver(model, function() {49 count++;50 });51 var observer2 = new PathObserver(model, '0', function() {52 count++;53 });54 var observer3 = new ArrayObserver(model, function() {55 count++;56 });57 model[0] = 2;58 model[1] = 2;59 observer1.deliver();60 observer2.deliver();61 observer3.deliver();62 assert.equal(3, count);63 observer1.close();64 observer2.close();65 observer3.close();66 });67 test('No Object.observe performMicrotaskCheckpoint', function() {68 if (typeof Object.observe == 'function')69 return;70 var model = [1];71 var count = 0;72 var observer1 = new ObjectObserver(model, function() {73 count++;74 });75 var observer2 = new PathObserver(model, '0', function() {76 count++;77 });78 var observer3 = new ArrayObserver(model, function() {79 count++;80 });81 model[0] = 2;82 model[1] = 2;83 Platform.performMicrotaskCheckpoint();84 assert.equal(3, count);85 observer1.close();86 observer2.close();87 observer3.close();88 });89});90suite('PathObserver Tests', function() {91 setup(doSetup);92 teardown(doTeardown);93 function assertPathChanges(expectNewValue, expectOldValue) {94 observer.deliver();95 assert.isTrue(callbackInvoked);96 var newValue = callbackArgs[0];97 var oldValue = callbackArgs[1];98 assert.deepEqual(expectNewValue, newValue);99 assert.deepEqual(expectOldValue, oldValue);100 callbackArgs = undefined;101 callbackInvoked = false;102 }103 test('Close Invokes Unobserved', function() {104 var called = false;105 var obj = { foo: 1, unobserved: function() { called = true }};106 var observer = new PathObserver(obj, 'foo', function() {});107 observer.close();108 assert.isTrue(called);109 });110 test('Optional target for callback', function() {111 var returnedToken;112 var target = {113 changed: function(value, oldValue, token) {114 this.called = true;115 returnedToken = token;116 }117 };118 var obj = { foo: 1 };119 var observer = new PathObserver(obj, 'foo', target.changed, target, 'token');120 obj.foo = 2;121 observer.deliver();122 assert.isTrue(target.called);123 assert.strictEqual('token', returnedToken)124 observer.close();125 });126 test('Delivery Until No Changes', function() {127 var obj = { foo: { bar: 5 }};128 var callbackCount = 0;129 var observer = new PathObserver(obj, 'foo.bar', function() {130 callbackCount++;131 if (!obj.foo.bar)132 return;133 obj.foo.bar--;134 });135 obj.foo.bar--;136 observer.deliver();137 assert.equal(5, callbackCount);138 observer.close();139 });140 test('Path disconnect', function() {141 var arr = {};142 arr.foo = 'bar';143 observer = new PathObserver(arr, 'foo', callback);144 arr.foo = 'baz';145 assertPathChanges('baz', 'bar');146 arr.foo = 'bar';147 observer.close();148 arr.foo = 'boo';149 assertNoChanges();150 });151 test('Path reset', function() {152 var arr = {};153 arr.foo = 'bar';154 observer = new PathObserver(arr, 'foo', callback);155 arr.foo = 'baz';156 assertPathChanges('baz', 'bar');157 arr.foo = 'bat';158 observer.reset();159 assertNoChanges();160 arr.foo = 'bag';161 assertPathChanges('bag', 'bat');162 observer.close();163 });164 test('Degenerate Values', function() {165 observer = new PathObserver(null, '', callback);166 assert.equal(null, observer.value);167 assert.equal(null, PathObserver.getValueAtPath(null, ''));168 observer.close();169 var foo = {};170 observer = new PathObserver(foo, '', callback);171 assert.equal(foo, observer.value);172 assert.equal(foo, PathObserver.getValueAtPath(foo, ''));173 observer.close();174 observer = new PathObserver(3, '', callback);175 assert.equal(3, observer.value);176 assert.equal(3, PathObserver.getValueAtPath(3, ''));177 observer.close();178 observer = new PathObserver(undefined, 'a', callback);179 assert.equal(undefined, observer.value);180 assert.equal(undefined, PathObserver.getValueAtPath(undefined, 'a'));181 observer.close();182 var bar = { id: 23 };183 observer = new PathObserver(undefined, 'a/3!', callback);184 assert.equal(undefined, observer.value);185 assert.equal(undefined, PathObserver.getValueAtPath(bar, 'a/3!'));186 observer.close();187 });188 test('Path NaN', function() {189 var foo = { val: 1 };190 observer = new PathObserver(foo, 'val', callback);191 foo.val = 0/0;192 // Can't use assertSummary because deepEqual() will fail with NaN193 observer.deliver();194 assert.isTrue(callbackInvoked);195 assert.isTrue(isNaN(callbackArgs[0]));196 assert.strictEqual(1, callbackArgs[1]);197 observer.close();198 });199 test('Path GetValueAtPath', function() {200 var obj = {201 a: {202 b: {203 c: 1204 }205 }206 };207 assert.strictEqual(obj.a, PathObserver.getValueAtPath(obj, 'a'));208 assert.strictEqual(obj.a.b, PathObserver.getValueAtPath(obj, 'a.b'));209 assert.strictEqual(1, PathObserver.getValueAtPath(obj, 'a.b.c'));210 obj.a.b.c = 2;211 assert.strictEqual(2, PathObserver.getValueAtPath(obj, 'a.b.c'));212 obj.a.b = {213 c: 3214 };215 assert.strictEqual(3, PathObserver.getValueAtPath(obj, 'a.b.c'));216 obj.a = {217 b: 4218 };219 assert.strictEqual(undefined, PathObserver.getValueAtPath(obj, 'a.b.c'));220 assert.strictEqual(4, PathObserver.getValueAtPath(obj, 'a.b'));221 });222 test('Path SetValueAtPath', function() {223 var obj = {};224 PathObserver.setValueAtPath(obj, 'foo', 3);225 assert.equal(3, obj.foo);226 var bar = { baz: 3 };227 PathObserver.setValueAtPath(obj, 'bar', bar);228 assert.equal(bar, obj.bar);229 PathObserver.setValueAtPath(obj, 'bar.baz.bat', 'not here');230 assert.equal(undefined, PathObserver.getValueAtPath(obj, 'bar.baz.bat'));231 });232 test('Path Set Value Back To Same', function() {233 var obj = {};234 PathObserver.setValueAtPath(obj, 'foo', 3);235 assert.equal(3, obj.foo);236 observer = new PathObserver(obj, 'foo', callback);237 assert.equal(3, observer.value);238 PathObserver.setValueAtPath(obj, 'foo', 2);239 observer.reset();240 assert.equal(2, observer.value);241 PathObserver.setValueAtPath(obj, 'foo', 3);242 observer.reset();243 assert.equal(3, observer.value);244 assertNoChanges();245 observer.close();246 });247 test('Path Triple Equals', function() {248 var model = { };249 observer = new PathObserver(model, 'foo', callback);250 model.foo = null;251 assertPathChanges(null, undefined);252 model.foo = undefined;253 assertPathChanges(undefined, null);254 observer.close();255 });256 test('Path Simple', function() {257 var model = { };258 observer = new PathObserver(model, 'foo', callback);259 model.foo = 1;260 assertPathChanges(1, undefined);261 model.foo = 2;262 assertPathChanges(2, 1);263 delete model.foo;264 assertPathChanges(undefined, 2);265 observer.close();266 });267 test('Path With Indices', function() {268 var model = [];269 observer = new PathObserver(model, '0', callback);270 model.push(1);271 assertPathChanges(1, undefined);272 observer.close();273 });274 test('Path Observation', function() {275 var model = {276 a: {277 b: {278 c: 'hello, world'279 }280 }281 };282 observer = new PathObserver(model, 'a.b.c', callback);283 model.a.b.c = 'hello, mom';284 assertPathChanges('hello, mom', 'hello, world');285 model.a.b = {286 c: 'hello, dad'287 };288 assertPathChanges('hello, dad', 'hello, mom');289 model.a = {290 b: {291 c: 'hello, you'292 }293 };294 assertPathChanges('hello, you', 'hello, dad');295 model.a.b = 1;296 assertPathChanges(undefined, 'hello, you');297 // Stop observing298 observer.close();299 model.a.b = {c: 'hello, back again -- but not observing'};300 assertNoChanges();301 // Resume observing302 observer = new PathObserver(model, 'a.b.c', callback);303 model.a.b.c = 'hello. Back for reals';304 assertPathChanges('hello. Back for reals',305 'hello, back again -- but not observing');306 observer.close();307 });308 test('Path Set To Same As Prototype', function() {309 var model = createObject({310 __proto__: {311 id: 1312 }313 });314 observer = new PathObserver(model, 'id', callback);315 model.id = 1;316 assertNoChanges();317 observer.close();318 });319 test('Path Set Read Only', function() {320 var model = {};321 Object.defineProperty(model, 'x', {322 configurable: true,323 writable: false,324 value: 1325 });326 observer = new PathObserver(model, 'x', callback);327 model.x = 2;328 assertNoChanges();329 observer.close();330 });331 test('Path Set Shadows', function() {332 var model = createObject({333 __proto__: {334 x: 1335 }336 });337 observer = new PathObserver(model, 'x', callback);338 model.x = 2;339 assertPathChanges(2, 1);340 observer.close();341 });342 test('Delete With Same Value On Prototype', function() {343 var model = createObject({344 __proto__: {345 x: 1,346 },347 x: 1348 });349 observer = new PathObserver(model, 'x', callback);350 delete model.x;351 assertNoChanges();352 observer.close();353 });354 test('Delete With Different Value On Prototype', function() {355 var model = createObject({356 __proto__: {357 x: 1,358 },359 x: 2360 });361 observer = new PathObserver(model, 'x', callback);362 delete model.x;363 assertPathChanges(1, 2);364 observer.close();365 });366 test('Value Change On Prototype', function() {367 var proto = {368 x: 1369 }370 var model = createObject({371 __proto__: proto372 });373 observer = new PathObserver(model, 'x', callback);374 model.x = 2;375 assertPathChanges(2, 1);376 delete model.x;377 assertPathChanges(1, 2);378 proto.x = 3;379 assertPathChanges(3, 1);380 observer.close();381 });382 // FIXME: Need test of observing change on proto.383 test('Delete Of Non Configurable', function() {384 var model = {};385 Object.defineProperty(model, 'x', {386 configurable: false,387 value: 1388 });389 observer = new PathObserver(model, 'x', callback);390 delete model.x;391 assertNoChanges();392 observer.close();393 });394 test('Notify', function() {395 if (typeof Object.getNotifier !== 'function')396 return;397 var model = {398 a: {}399 }400 var _b = 2;401 Object.defineProperty(model.a, 'b', {402 get: function() { return _b; },403 set: function(b) {404 Object.getNotifier(this).notify({405 type: 'updated',406 name: 'b',407 oldValue: _b408 });409 _b = b;410 }411 });412 observer = new PathObserver(model, 'a.b', callback);413 _b = 3; // won't be observed.414 assertNoChanges();415 model.a.b = 4; // will be observed.416 assertPathChanges(4, 2);417 observer.close();418 });419 test('DefineProperty Cascade', function() {420 var root = {421 value: 1,422 a: {423 b: {}424 },425 c: {}426 };427 var a = {};428 var b = {};429 var c = {};430 root.a.observer = PathObserver.defineProperty(root.a, 'value', {431 object: root,432 path: 'value'433 });434 root.a.b.observer = PathObserver.defineProperty(root.a.b, 'value', {435 object: root.a,436 path: 'value'437 });438 root.c.observer = PathObserver.defineProperty(root.c, 'value', {439 object: root,440 path: 'value'441 });442 root.c.value = 2;443 assert.strictEqual(2, root.a.b.value);444 root.a.observer.close();445 root.a.b.observer.close();446 root.c.observer.close();447 });448 test('DefineProperty', function() {449 var source = { foo: { bar: 1 }};450 var target = {};451 var changeRecords;452 var callback;453 if (typeof Object.observe === 'function') {454 changeRecords = [];455 callback = function(records) {456 Array.prototype.push.apply(changeRecords, records);457 };458 Object.observe(target, callback);459 }460 var observer = PathObserver.defineProperty(target, 'computed', {461 object: source,462 path: 'foo.bar'463 });464 assert.isTrue(target.hasOwnProperty('computed'));465 assert.strictEqual(1, target.computed);466 target.computed = 2;467 assert.strictEqual(2, source.foo.bar);468 source.foo.bar = 3;469 assert.strictEqual(3, target.computed);470 source.foo.bar = 4;471 target.computed = 5;472 assert.strictEqual(5, target.computed);473 target.computed = 6;474 source.foo.bar = 7;475 assert.strictEqual(7, target.computed);476 delete source.foo;477 target.computed = 8;478 assert.isUndefined(target.computed);479 source.foo = { bar: 9 };480 assert.strictEqual(9, target.computed);481 observer.close();482 assert.isTrue(target.hasOwnProperty('computed'));483 assert.strictEqual(9, target.computed);484 if (!changeRecords)485 return;486 Object.deliverChangeRecords(callback);487 assert.deepEqual(changeRecords, [488 {489 object: target,490 name: 'computed',491 type: 'new'492 },493 {494 object: target,495 name: 'computed',496 type: 'updated',497 oldValue: 1498 },499 {500 object: target,501 name: 'computed',502 type: 'deleted'503 // TODO(rafaelw): When notifer.performChange() is implemented, this can504 // a synthetic record can be sent with the correct value.505 // oldValue: 9506 }507 ]);508 Object.unobserve(target, callback);509 });510 test('DefineProperty - empty path', function() {511 var target = {}512 var observer = PathObserver.defineProperty(target, 'foo', {513 object: 1,514 path: ''515 });516 assert.isTrue(target.hasOwnProperty('foo'));517 assert.strictEqual(1, target.foo);518 var obj = {};519 var observer2 = PathObserver.defineProperty(target, 'bar', {520 object: obj,521 path: ''522 });523 assert.isTrue(target.hasOwnProperty('bar'));524 assert.strictEqual(obj, target.bar);525 });526});527suite('ArrayObserver Tests', function() {528 setup(doSetup);529 teardown(doTeardown);530 function ensureNonSparse(arr) {531 for (var i = 0; i < arr.length; i++) {532 if (i in arr)533 continue;534 arr[i] = undefined;535 }536 }537 function assertArrayChanges(expectSplices) {538 observer.deliver();539 var splices = callbackArgs[0];540 assert.isTrue(callbackInvoked);541 splices.forEach(function(splice) {542 ensureNonSparse(splice.removed);543 });544 expectSplices.forEach(function(splice) {545 ensureNonSparse(splice.removed);546 });547 assert.deepEqual(expectSplices, splices);548 callbackArgs = undefined;549 callbackInvoked = false;550 }551 function applySplicesAndAssertDeepEqual(orig, copy) {552 observer.deliver();553 if (callbackInvoked) {554 var splices = callbackArgs[0];555 ArrayObserver.applySplices(copy, orig, splices);556 }557 ensureNonSparse(orig);558 ensureNonSparse(copy);559 assert.deepEqual(orig, copy);560 callbackArgs = undefined;561 callbackInvoked = false;562 }563 function assertEditDistance(orig, expectDistance) {564 observer.deliver();565 var splices = callbackArgs[0];566 var actualDistance = 0;567 if (callbackInvoked) {568 splices.forEach(function(splice) {569 actualDistance += splice.addedCount + splice.removed.length;570 });571 }572 assert.deepEqual(expectDistance, actualDistance);573 callbackArgs = undefined;574 callbackInvoked = false;575 }576 function arrayMutationTest(arr, operations) {577 var copy = arr.slice();578 observer = new ArrayObserver(arr, callback);579 operations.forEach(function(op) {580 switch(op.name) {581 case 'delete':582 delete arr[op.index];583 break;584 case 'update':585 arr[op.index] = op.value;586 break;587 default:588 arr[op.name].apply(arr, op.args);589 break;590 }591 });592 applySplicesAndAssertDeepEqual(arr, copy);593 observer.close();594 }595 test('Close Invokes Unobserved', function() {596 var called = false;597 var obj = [];598 obj.unobserved = function() { called = true };599 var observer = new ArrayObserver(obj, function() {});600 observer.close();601 assert.isTrue(called);602 });603 test('Optional target for callback', function() {604 var returnedToken;605 var target = {606 changed: function(splices, token) {607 this.called = true;608 returnedToken = token;609 }610 };611 var obj = [];612 var observer = new ArrayObserver(obj, target.changed, target, 'token');613 obj.length = 1;614 observer.deliver();615 assert.isTrue(target.called);616 assert.strictEqual('token', returnedToken);617 observer.close();618 });619 test('Delivery Until No Changes', function() {620 var arr = [0, 1, 2, 3, 4];621 var callbackCount = 0;622 var observer = new ArrayObserver(arr, function() {623 callbackCount++;624 arr.shift();625 });626 arr.shift();627 observer.deliver();628 assert.equal(5, callbackCount);629 observer.close();630 });631 test('Array disconnect', function() {632 var arr = [ 0 ];633 observer = new ArrayObserver(arr, callback);634 arr[0] = 1;635 assertArrayChanges([{636 index: 0,637 removed: [0],638 addedCount: 1639 }]);640 observer.close();641 arr[1] = 2;642 assertNoChanges();643 });644 test('Array reset', function() {645 var arr = [];646 arr.push(1);647 observer = new ArrayObserver(arr, callback);648 arr.push(2);649 assertArrayChanges([{650 index: 1,651 removed: [],652 addedCount: 1653 }]);654 arr.push(3);655 observer.reset();656 assertNoChanges();657 arr.pop();658 assertArrayChanges([{659 index: 2,660 removed: [3],661 addedCount: 0662 }]);663 observer.close();664 });665 test('Array', function() {666 var model = [0, 1];667 observer = new ArrayObserver(model, callback);668 model[0] = 2;669 assertArrayChanges([{670 index: 0,671 removed: [0],672 addedCount: 1673 }]);674 model[1] = 3;675 assertArrayChanges([{676 index: 1,677 removed: [1],678 addedCount: 1679 }]);680 observer.close();681 });682 test('Array observe non-array throws', function() {683 assert.throws(function () {684 observer = new ArrayObserver({}, callback);685 });686 });687 test('Array Set Same', function() {688 var model = [1];689 observer = new ArrayObserver(model, callback);690 model[0] = 1;691 observer.close();692 });693 test('Array Splice', function() {694 var model = [0, 1]695 observer = new ArrayObserver(model, callback);696 model.splice(1, 1, 2, 3); // [0, 2, 3]697 assertArrayChanges([{698 index: 1,699 removed: [1],700 addedCount: 2701 }]);702 model.splice(0, 1); // [2, 3]703 assertArrayChanges([{704 index: 0,705 removed: [0],706 addedCount: 0707 }]);708 model.splice();709 assertNoChanges();710 model.splice(0, 0);711 assertNoChanges();712 model.splice(0, -1);713 assertNoChanges();714 model.splice(-1, 0, 1.5); // [2, 1.5, 3]715 assertArrayChanges([{716 index: 1,717 removed: [],718 addedCount: 1719 }]);720 model.splice(3, 0, 0); // [2, 1.5, 3, 0]721 assertArrayChanges([{722 index: 3,723 removed: [],724 addedCount: 1725 }]);726 model.splice(0); // []727 assertArrayChanges([{728 index: 0,729 removed: [2, 1.5, 3, 0],730 addedCount: 0731 }]);732 observer.close();733 });734 test('Array Splice Truncate And Expand With Length', function() {735 var model = ['a', 'b', 'c', 'd', 'e'];736 observer = new ArrayObserver(model, callback);737 model.length = 2;738 assertArrayChanges([{739 index: 2,740 removed: ['c', 'd', 'e'],741 addedCount: 0742 }]);743 model.length = 5;744 assertArrayChanges([{745 index: 2,746 removed: [],747 addedCount: 3748 }]);749 observer.close();750 });751 test('Array Splice Delete Too Many', function() {752 var model = ['a', 'b', 'c'];753 observer = new ArrayObserver(model, callback);754 model.splice(2, 3); // ['a', 'b']755 assertArrayChanges([{756 index: 2,757 removed: ['c'],758 addedCount: 0759 }]);760 observer.close();761 });762 test('Array Length', function() {763 var model = [0, 1];764 observer = new ArrayObserver(model, callback);765 model.length = 5; // [0, 1, , , ,];766 assertArrayChanges([{767 index: 2,768 removed: [],769 addedCount: 3770 }]);771 model.length = 1;772 assertArrayChanges([{773 index: 1,774 removed: [1, , , ,],775 addedCount: 0776 }]);777 model.length = 1;778 assertNoChanges();779 observer.close();780 });781 test('Array Push', function() {782 var model = [0, 1];783 observer = new ArrayObserver(model, callback);784 model.push(2, 3); // [0, 1, 2, 3]785 assertArrayChanges([{786 index: 2,787 removed: [],788 addedCount: 2789 }]);790 model.push();791 assertNoChanges();792 observer.close();793 });794 test('Array Pop', function() {795 var model = [0, 1];796 observer = new ArrayObserver(model, callback);797 model.pop(); // [0]798 assertArrayChanges([{799 index: 1,800 removed: [1],801 addedCount: 0802 }]);803 model.pop(); // []804 assertArrayChanges([{805 index: 0,806 removed: [0],807 addedCount: 0808 }]);809 model.pop();810 assertNoChanges();811 observer.close();812 });813 test('Array Shift', function() {814 var model = [0, 1];815 observer = new ArrayObserver(model, callback);816 model.shift(); // [1]817 assertArrayChanges([{818 index: 0,819 removed: [0],820 addedCount: 0821 }]);822 model.shift(); // []823 assertArrayChanges([{824 index: 0,825 removed: [1],826 addedCount: 0827 }]);828 model.shift();829 assertNoChanges();830 observer.close();831 });832 test('Array Unshift', function() {833 var model = [0, 1];834 observer = new ArrayObserver(model, callback);835 model.unshift(-1); // [-1, 0, 1]836 assertArrayChanges([{837 index: 0,838 removed: [],839 addedCount: 1840 }]);841 model.unshift(-3, -2); // []842 assertArrayChanges([{843 index: 0,844 removed: [],845 addedCount: 2846 }]);847 model.unshift();848 assertNoChanges();849 observer.close();850 });851 test('Array Tracker Contained', function() {852 arrayMutationTest(853 ['a', 'b'],854 [855 { name: 'splice', args: [1, 1] },856 { name: 'unshift', args: ['c', 'd', 'e'] },857 { name: 'splice', args: [1, 2, 'f'] }858 ]859 );860 });861 test('Array Tracker Delete Empty', function() {862 arrayMutationTest(863 [],864 [865 { name: 'delete', index: 0 },866 { name: 'splice', args: [0, 0, 'a', 'b', 'c'] }867 ]868 );869 });870 test('Array Tracker Right Non Overlap', function() {871 arrayMutationTest(872 ['a', 'b', 'c', 'd'],873 [874 { name: 'splice', args: [0, 1, 'e'] },875 { name: 'splice', args: [2, 1, 'f', 'g'] }876 ]877 );878 });879 test('Array Tracker Left Non Overlap', function() {880 arrayMutationTest(881 ['a', 'b', 'c', 'd'],882 [883 { name: 'splice', args: [3, 1, 'f', 'g'] },884 { name: 'splice', args: [0, 1, 'e'] }885 ]886 );887 });888 test('Array Tracker Right Adjacent', function() {889 arrayMutationTest(890 ['a', 'b', 'c', 'd'],891 [892 { name: 'splice', args: [1, 1, 'e'] },893 { name: 'splice', args: [2, 1, 'f', 'g'] }894 ]895 );896 });897 test('Array Tracker Left Adjacent', function() {898 arrayMutationTest(899 ['a', 'b', 'c', 'd'],900 [901 { name: 'splice', args: [2, 2, 'e'] },902 { name: 'splice', args: [1, 1, 'f', 'g'] }903 ]904 );905 });906 test('Array Tracker Right Overlap', function() {907 arrayMutationTest(908 ['a', 'b', 'c', 'd'],909 [910 { name: 'splice', args: [1, 1, 'e'] },911 { name: 'splice', args: [1, 1, 'f', 'g'] }912 ]913 );914 });915 test('Array Tracker Left Overlap', function() {916 arrayMutationTest(917 ['a', 'b', 'c', 'd'],918 [919 // a b [e f g] d920 { name: 'splice', args: [2, 1, 'e', 'f', 'g'] },921 // a [h i j] f g d922 { name: 'splice', args: [1, 2, 'h', 'i', 'j'] }923 ]924 );925 });926 test('Array Tracker Prefix And Suffix One In', function() {927 arrayMutationTest(928 ['a', 'b', 'c', 'd'],929 [930 { name: 'unshift', args: ['z'] },931 { name: 'push', arg: ['z'] }932 ]933 );934 });935 test('Array Tracker Shift One', function() {936 arrayMutationTest(937 [16, 15, 15],938 [939 { name: 'shift', args: ['z'] }940 ]941 );942 });943 test('Array Tracker Update Delete', function() {944 arrayMutationTest(945 ['a', 'b', 'c', 'd'],946 [947 { name: 'splice', args: [2, 1, 'e', 'f', 'g'] },948 { name: 'update', index: 0, value: 'h' },949 { name: 'delete', index: 1 }950 ]951 );952 });953 test('Array Tracker Update After Delete', function() {954 arrayMutationTest(955 ['a', 'b', undefined, 'd'],956 [957 { name: 'update', index: 2, value: 'e' }958 ]959 );960 });961 test('Array Tracker Delete Mid Array', function() {962 arrayMutationTest(963 ['a', 'b', 'c', 'd'],964 [965 { name: 'delete', index: 2 }966 ]967 );968 });969 test('Array Random Case 1', function() {970 var model = ['a','b'];971 var copy = model.slice();972 observer = new ArrayObserver(model, callback);973 model.splice(0, 1, 'c', 'd', 'e');974 model.splice(4,0,'f');975 model.splice(3,2);976 applySplicesAndAssertDeepEqual(model, copy);977 });978 test('Array Random Case 2', function() {979 var model = [3,4];980 var copy = model.slice();981 observer = new ArrayObserver(model, callback);982 model.splice(2,0,8);983 model.splice(0,1,0,5);984 model.splice(2,2);985 applySplicesAndAssertDeepEqual(model, copy);986 });987 test('Array Random Case 3', function() {988 var model = [1,3,6];989 var copy = model.slice();990 observer = new ArrayObserver(model, callback);991 model.splice(1,1);992 model.splice(0,2,1,7);993 model.splice(1,0,3,7);994 applySplicesAndAssertDeepEqual(model, copy);995 });996 test('Array Tracker Fuzzer', function() {997 var testCount = 64;998 console.log('Fuzzing spliceProjection ' + testCount +999 ' passes with ' + ArrayFuzzer.operationCount + ' operations each.');1000 for (var i = 0; i < testCount; i++) {1001 console.log('pass: ' + i);1002 var fuzzer = new ArrayFuzzer();1003 fuzzer.go();1004 ensureNonSparse(fuzzer.arr);1005 ensureNonSparse(fuzzer.copy);1006 assert.deepEqual(fuzzer.arr, fuzzer.copy);1007 }1008 });1009 test('Array Tracker No Proxies Edits', function() {1010 model = [];1011 observer = new ArrayObserver(model, callback);1012 model.length = 0;1013 model.push(1, 2, 3);1014 assertEditDistance(model, 3);1015 observer.close();1016 model = ['x', 'x', 'x', 'x', '1', '2', '3'];1017 observer = new ArrayObserver(model, callback);1018 model.length = 0;1019 model.push('1', '2', '3', 'y', 'y', 'y', 'y');1020 assertEditDistance(model, 8);1021 observer.close();1022 model = ['1', '2', '3', '4', '5'];1023 observer = new ArrayObserver(model, callback);1024 model.length = 0;1025 model.push('a', '2', 'y', 'y', '4', '5', 'z', 'z');1026 assertEditDistance(model, 7);1027 observer.close();1028 });1029});1030suite('ObjectObserver Tests', function() {1031 setup(doSetup);1032 teardown(doTeardown);1033 function assertObjectChanges(expect) {1034 observer.deliver();1035 assert.isTrue(callbackInvoked);1036 var added = callbackArgs[0];1037 var removed = callbackArgs[1];1038 var changed = callbackArgs[2];1039 var getOldValue = callbackArgs[3];1040 var oldValues = {};1041 function collectOldValues(type) {1042 Object.keys(type).forEach(function(prop) {1043 oldValues[prop] = getOldValue(prop);1044 });1045 };1046 collectOldValues(added);1047 collectOldValues(removed);1048 collectOldValues(changed);1049 assert.deepEqual(expect.added, added);1050 assert.deepEqual(expect.removed, removed);1051 assert.deepEqual(expect.changed, changed);1052 assert.deepEqual(expect.oldValues, oldValues);1053 callbackArgs = undefined;1054 callbackInvoked = false;1055 }1056 test('Close Invokes Unobserved', function() {1057 var called = false;1058 var obj = {};1059 obj.unobserved = function() { called = true };1060 var observer = new ObjectObserver(obj, function() {});1061 observer.close();1062 assert.isTrue(called);1063 });1064 test('Optional target for callback', function() {1065 var returnedToken;1066 var target = {1067 changed: function(value, oldValue, token) {1068 this.called = true;1069 returnedToken = token;1070 }1071 };1072 var obj = { foo: 1 };1073 var observer = new PathObserver(obj, 'foo', target.changed, target, 'token');1074 obj.foo = 2;1075 observer.deliver();1076 assert.isTrue(target.called);1077 assert.strictEqual('token', returnedToken)1078 observer.close();1079 });1080 test('Optional target for callback', function() {1081 var returnedToken;1082 var target = {1083 changed: function(added, removed, changed, oldValues, token) {1084 this.called = true;1085 returnedToken = token;1086 }1087 };1088 var obj = {};1089 var observer = new ObjectObserver(obj, target.changed, target, 'token');1090 obj.foo = 1;1091 observer.deliver();1092 assert.isTrue(target.called);1093 assert.strictEqual('token', returnedToken)1094 observer.close();1095 });1096 test('Delivery Until No Changes', function() {1097 var obj = { foo: 5 };1098 var callbackCount = 0;1099 var observer = new ObjectObserver(obj, function() {1100 callbackCount++;1101 if (!obj.foo)1102 return;1103 obj.foo--;1104 });1105 obj.foo--;1106 observer.deliver();1107 assert.equal(5, callbackCount);1108 observer.close();1109 });1110 test('Object disconnect', function() {1111 var obj = {};1112 obj.foo = 'bar';1113 observer = new ObjectObserver(obj, callback);1114 obj.foo = 'baz';1115 obj.bat = 'bag';1116 obj.blaz = 'foo';1117 delete obj.foo;1118 delete obj.blaz;1119 assertObjectChanges({1120 added: {1121 'bat': 'bag'1122 },1123 removed: {1124 'foo': undefined1125 },1126 changed: {},1127 oldValues: {1128 'foo': 'bar',1129 'bat': undefined1130 }1131 });1132 obj.foo = 'blarg';1133 observer.close();1134 obj.bar = 'blaz';1135 assertNoChanges();1136 });1137 test('Object reset', function() {1138 var obj = {};1139 obj.foo = 'bar';1140 observer = new ObjectObserver(obj, callback);1141 obj.foo = 'baz';1142 assertObjectChanges({1143 added: {},1144 removed: {},1145 changed: {1146 foo: 'baz'1147 },1148 oldValues: {1149 foo: 'bar'1150 }1151 });1152 obj.blaz = 'bat';1153 observer.reset();1154 assertNoChanges();1155 obj.bat = 'bag';1156 assertObjectChanges({1157 added: {1158 bat: 'bag'1159 },1160 removed: {},1161 changed: {},1162 oldValues: {1163 bat: undefined1164 }1165 });1166 observer.close();1167 });1168 test('Object observe array', function() {1169 var arr = [];1170 observer = new ObjectObserver(arr, callback);1171 arr.length = 5;1172 arr.foo = 'bar';1173 arr[3] = 'baz';1174 assertObjectChanges({1175 added: {1176 foo: 'bar',1177 '3': 'baz'1178 },1179 removed: {},1180 changed: {1181 'length': 51182 },1183 oldValues: {1184 length: 0,1185 foo: undefined,1186 '3': undefined1187 }1188 });1189 observer.close();1190 });1191 test('Object', function() {1192 var model = {};1193 observer = new ObjectObserver(model, callback);1194 model.id = 0;1195 assertObjectChanges({1196 added: {1197 id: 01198 },1199 removed: {},1200 changed: {},1201 oldValues: {1202 id: undefined1203 }1204 });1205 delete model.id;1206 assertObjectChanges({1207 added: {},1208 removed: {1209 id: undefined1210 },1211 changed: {},1212 oldValues: {1213 id: 01214 }1215 });1216 // Stop observing -- shouldn't see an event1217 observer.close();1218 model.id = 101;1219 assertNoChanges();1220 // Re-observe -- should see an new event again.1221 observer = new ObjectObserver(model, callback);1222 model.id2 = 202;;1223 assertObjectChanges({1224 added: {1225 id2: 2021226 },1227 removed: {},1228 changed: {},1229 oldValues: {1230 id2: undefined1231 }1232 });1233 observer.close();1234 });1235 test('Object Delete Add Delete', function() {1236 var model = { id: 1 };1237 observer = new ObjectObserver(model, callback);1238 // If mutation occurs in seperate "runs", two events fire.1239 delete model.id;1240 assertObjectChanges({1241 added: {},1242 removed: {1243 id: undefined1244 },1245 changed: {},1246 oldValues: {1247 id: 11248 }1249 });1250 model.id = 1;1251 assertObjectChanges({1252 added: {1253 id: 11254 },1255 removed: {},1256 changed: {},1257 oldValues: {1258 id: undefined1259 }1260 });1261 // If mutation occurs in the same "run", no events fire (nothing changed).1262 delete model.id;1263 model.id = 1;1264 assertNoChanges();1265 observer.close();1266 });1267 test('Object Set Undefined', function() {1268 var model = {};1269 observer = new ObjectObserver(model, callback);1270 model.x = undefined;1271 assertObjectChanges({1272 added: {1273 x: undefined1274 },1275 removed: {},1276 changed: {},1277 oldValues: {1278 x: undefined1279 }1280 });1281 observer.close();1282 });...
observer.js
Source:observer.js
1/* */ 2"format cjs";3 /**4 * Supports push-style iteration over an observable sequence.5 */6 var Observer = Rx.Observer = function () { };7 /**8 * Creates a notification callback from an observer.9 * @returns The action that forwards its input notification to the underlying observer.10 */11 Observer.prototype.toNotifier = function () {12 var observer = this;13 return function (n) { return n.accept(observer); };14 };15 /**16 * Hides the identity of an observer.17 * @returns An observer that hides the identity of the specified observer.18 */19 Observer.prototype.asObserver = function () {20 return new AnonymousObserver(this.onNext.bind(this), this.onError.bind(this), this.onCompleted.bind(this));21 };22 /**23 * Checks access to the observer for grammar violations. This includes checking for multiple OnError or OnCompleted calls, as well as reentrancy in any of the observer methods.24 * If a violation is detected, an Error is thrown from the offending observer method call.25 * @returns An observer that checks callbacks invocations against the observer grammar and, if the checks pass, forwards those to the specified observer.26 */27 Observer.prototype.checked = function () { return new CheckedObserver(this); };28 /**29 * Creates an observer from the specified OnNext, along with optional OnError, and OnCompleted actions.30 * @param {Function} [onNext] Observer's OnNext action implementation.31 * @param {Function} [onError] Observer's OnError action implementation.32 * @param {Function} [onCompleted] Observer's OnCompleted action implementation.33 * @returns {Observer} The observer object implemented using the given actions.34 */35 var observerCreate = Observer.create = function (onNext, onError, onCompleted) {36 onNext || (onNext = noop);37 onError || (onError = defaultError);38 onCompleted || (onCompleted = noop);39 return new AnonymousObserver(onNext, onError, onCompleted);40 };41 /**42 * Creates an observer from a notification callback.43 *44 * @static45 * @memberOf Observer46 * @param {Function} handler Action that handles a notification.47 * @returns The observer object that invokes the specified handler using a notification corresponding to each message it receives.48 */49 Observer.fromNotifier = function (handler, thisArg) {50 return new AnonymousObserver(function (x) {51 return handler.call(thisArg, notificationCreateOnNext(x));52 }, function (e) {53 return handler.call(thisArg, notificationCreateOnError(e));54 }, function () {55 return handler.call(thisArg, notificationCreateOnCompleted());56 });57 };58 /**59 * Schedules the invocation of observer methods on the given scheduler.60 * @param {Scheduler} scheduler Scheduler to schedule observer messages on.61 * @returns {Observer} Observer whose messages are scheduled on the given scheduler.62 */63 Observer.prototype.notifyOn = function (scheduler) {64 return new ObserveOnObserver(scheduler, this);65 };66 Observer.prototype.makeSafe = function(disposable) {67 return new AnonymousSafeObserver(this._onNext, this._onError, this._onCompleted, disposable);...
index.ts
Source:index.ts
1import { IObserver, Middleware, ObserverCandidate, ObserverProps, PartialObserver, Update } from './types';2// TODO clear up some of the terminology here and look at merging more generally with Reaction3export class Observer implements IObserver {4 private isActive = true;5 private observer: PartialObserver;6 private updateObserver: Update;7 private onComplete: Function;8 constructor({ middleware, onComplete }: ObserverProps, observer: PartialObserver) {9 this.observer = observer;10 this.updateObserver = (v: any) => observer.update(v);11 this.onComplete = onComplete;12 if (observer.update && middleware && middleware.length) {13 middleware.forEach((m: Middleware) => this.updateObserver = m(this.updateObserver, this.complete));14 }15 }16 update = (v: any) => {17 if (this.observer.update) this.updateObserver(v);18 }19 complete = () => {20 if (this.observer.complete && this.isActive) this.observer.complete();21 if (this.onComplete) this.onComplete();22 this.isActive = false;23 }24 error = (err: any) => {25 if (this.observer.error && this.isActive) this.observer.error(err);26 this.isActive = false;27 }28}29export default (observerCandidate: ObserverCandidate, { middleware }: ObserverProps, onComplete?: Function) => {30 if (typeof observerCandidate === 'function') {31 return new Observer({ middleware, onComplete }, { update: observerCandidate });32 } else {33 return new Observer({ middleware, onComplete }, observerCandidate);34 }...
Using AI Code Generation
1var observer = new MutationObserver(function(mutations) {2 mutations.forEach(function(mutation) {3 console.log(mutation.type);4 }); 5});6var config = { attributes: true, childList: true, characterData: true };7observer.observe(target, config);8observer.disconnect();9var target = document.querySelector('body');10function callback(mutationsList, observer) {11 for(var mutation of mutationsList) {12 if (mutation.type == 'childList') {13 console.log('A child node has been added or removed.');14 }15 else if (mutation.type == 'attributes') {16 console.log('The ' + mutation.attributeName + ' attribute was modified.');17 }18 }19}20var observer = new MutationObserver(callback);21var config = { attributes: true, childList: true, subtree: true };22observer.observe(target, config);23observer.disconnect();24var target = document.querySelector('body');25var observer = new MutationObserver(function(mutations) {26 mutations.forEach(function(mutation) {27 console.log(mutation.type);28 }); 29});30var config = { attributes: true, childList: true, characterData: true };31observer.observe(target, config);32setInterval(function() {33 observer.takeRecords();34}, 1000);35observer.disconnect();36var target = document.querySelector('body');37var observer = new MutationObserver(function(mutations) {38 mutations.forEach(function(mutation) {39 console.log(mutation.type);40 }); 41});42var config = { attributes: true, childList: true, characterData: true };43observer.observe(target, config);44setTimeout(function() {45 observer.takeRecords();46}, 1000);47observer.disconnect();48var target = document.querySelector('body');49var observer = new MutationObserver(function(mutations) {50 mutations.forEach(function(mutation) {51 console.log(mutation.type);52 }); 53});54var config = { attributes: true, childList: true, characterData: true };55observer.observe(target, config);
Using AI Code Generation
1window.onload = function() {2 var wptObserver = new MutationObserver(function(mutations) {3 var wptStatus = document.getElementById('wpt-status');4 if (wptStatus) {5 wptObserver.disconnect();6 wptStatus.innerHTML = 'done';7 }8 });9 wptObserver.observe(document, {10 });11};
Using AI Code Generation
1function callWPT() {2 var request = new XMLHttpRequest();3 request.onload = function() {4 if (request.status >= 200 && request.status < 400) {5 var data = JSON.parse(request.responseText);6 console.log(data);7 } else {8 console.log('error');9 }10 };11 request.onerror = function() {12 console.log('error');13 };14 request.send();15}16callWPT();17function checkStatus() {18 var request = new XMLHttpRequest();19 request.onload = function() {20 if (request.status >= 200 && request.status < 400) {21 var data = JSON.parse(request.responseText);22 console.log(data);23 } else {24 console.log('error');25 }26 };27 request.onerror = function() {28 console.log('error');29 };30 request.send();31}32checkStatus();33function getResults() {34 var request = new XMLHttpRequest();35 request.onload = function() {36 if (request.status >= 200 && request.status < 400) {37 var data = JSON.parse(request.responseText);38 console.log(data);39 } else {40 console.log('error');41 }42 };43 request.onerror = function() {44 console.log('error');45 };46 request.send();47}48getResults();
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!!