Best JavaScript code snippet using playwright-internal
StoreDispatcher.js
Source:StoreDispatcher.js
...44 name: 'store1',45 constructor: DataStore46 }47 };48 var locator = createLocator(stores),49 context = {hello: 'world'},50 dispatcher = locator.resolve('storeDispatcher');51 dispatcher.setState({}, context);52 dispatcher.getStoreData(stores.store1.name)53 .then(function (data) {54 assert.strictEqual(data.name, stores.store1.name);55 assert.strictEqual(data.hello, context.hello);56 done();57 })58 .catch(done);59 });60 it('should properly get store data from $context', function (done) {61 function Store1() {}62 Store1.prototype.load = function () {63 return this.$context.getStoreData('store2');64 };65 function Store2() {}66 Store2.prototype.load = function () {67 return 'hello';68 };69 var stores = {70 store1: {71 name: 'store1',72 constructor: Store173 },74 store2: {75 name: 'store2',76 constructor: Store277 }78 };79 var locator = createLocator(stores),80 context = {hello: 'world'},81 dispatcher = locator.resolve('storeDispatcher');82 dispatcher.setState({}, context);83 dispatcher.getStoreData(stores.store1.name)84 .then(function (data) {85 assert.strictEqual(data, 'hello');86 done();87 })88 .catch(done);89 });90 it('should return null if store name equals ' +91 'current in $context', function (done) {92 function Store1() {}93 Store1.prototype.load = function () {94 return this.$context.getStoreData('store1');95 };96 var stores = {97 store1: {98 name: 'store1',99 constructor: Store1100 }101 };102 var locator = createLocator(stores),103 context = {hello: 'world'},104 dispatcher = locator.resolve('storeDispatcher');105 dispatcher.setState({}, context);106 dispatcher.getStoreData(stores.store1.name)107 .then(function (data) {108 assert.strictEqual(data, null);109 done();110 })111 .catch(done);112 });113 it('should pass error from store', function (done) {114 var stores = {115 store1: {116 name: 'store1',117 constructor: ErrorStore118 }119 };120 var locator = createLocator(stores),121 context = {hello: 'world'},122 dispatcher = locator.resolve('storeDispatcher');123 dispatcher.setState({}, context);124 dispatcher.getStoreData(stores.store1.name)125 .then(function () {126 done(new Error('Should fail'));127 })128 .catch(function (reason) {129 assert.strictEqual(reason.message, stores.store1.name);130 done();131 });132 });133 it('should pass error from store asynchronously', function (done) {134 var stores = {135 store1: {136 name: 'store1',137 constructor: ErrorAsyncStore138 }139 };140 var locator = createLocator(stores),141 context = {hello: 'world'},142 dispatcher = locator.resolve('storeDispatcher');143 dispatcher.setState({}, context);144 dispatcher.getStoreData(stores.store1.name)145 .then(function () {146 done(new Error('Should fail'));147 })148 .catch(function (reason) {149 assert.strictEqual(reason.message, stores.store1.name);150 done();151 });152 });153 it('should properly get store data asynchronously', function (done) {154 var stores = {155 store1: {156 name: 'store1',157 constructor: DataAsyncStore158 }159 };160 var locator = createLocator(stores),161 context = {hello: 'world'},162 dispatcher = locator.resolve('storeDispatcher');163 dispatcher.setState({}, context);164 dispatcher.getStoreData(stores.store1.name)165 .then(function (data) {166 assert.strictEqual(data.name, stores.store1.name);167 assert.strictEqual(data.hello, context.hello);168 done();169 })170 .catch(done);171 });172 it('should return null if store name is not a string', function (done) {173 var locator = createLocator({}),174 context = {hello: 'world'},175 dispatcher = locator.resolve('storeDispatcher');176 dispatcher.setState({}, context);177 dispatcher.getStoreData(100500)178 .then(function (data) {179 assert.strictEqual(data, null);180 done();181 })182 .catch(done);183 });184 it('should reject promise if there is no such store', function (done) {185 var locator = createLocator({}),186 context = {hello: 'world'},187 dispatcher = locator.resolve('storeDispatcher');188 dispatcher.setState({}, context);189 dispatcher.getStoreData('wrong')190 .then(function () {191 done(new Error('Should fail'));192 })193 .catch(function (reason) {194 assert.strictEqual(195 reason.message, 'Store "wrong" not found'196 );197 done();198 });199 });200 it('should not invoke store\'s load method ' +201 'many times concurrently', function (done) {202 var counter = 0;203 function Store() {}204 Store.prototype.load = function () {205 counter++;206 return new Promise(function (fulfill) {207 setTimeout(function () {208 fulfill('hello');209 }, 10);210 });211 };212 var stores = {213 store1: {214 name: 'store1',215 constructor: Store216 }217 };218 var locator = createLocator(stores),219 context = {hello: 'world'},220 dispatcher = locator.resolve('storeDispatcher');221 dispatcher.setState({}, context);222 Promise.all([223 dispatcher.getStoreData(stores.store1.name),224 dispatcher.getStoreData(stores.store1.name),225 dispatcher.getStoreData(stores.store1.name),226 dispatcher.getStoreData(stores.store1.name),227 dispatcher.getStoreData(stores.store1.name)228 ])229 .then(function (results) {230 assert.strictEqual(counter, 1);231 results.forEach(function (result) {232 assert.strictEqual(result, 'hello');233 });234 done();235 })236 .catch(done);237 });238 it('should not invoke store\'s load method ' +239 'if store is not changed', function (done) {240 var counter = 0;241 function Store() {}242 Store.prototype.load = function () {243 counter++;244 return new Promise(function (fulfill) {245 setTimeout(function () {246 fulfill('hello');247 }, 10);248 });249 };250 var stores = {251 store1: {252 name: 'store1',253 constructor: Store254 }255 };256 var locator = createLocator(stores),257 context = {hello: 'world'},258 dispatcher = locator.resolve('storeDispatcher');259 dispatcher.setState({}, context);260 dispatcher.getStoreData(stores.store1.name)261 .then(function (result) {262 assert.strictEqual(result, 'hello');263 return dispatcher.getStoreData(stores.store1.name);264 })265 .then(function (result) {266 assert.strictEqual(counter, 1);267 assert.strictEqual(result, 'hello');268 done();269 })270 .catch(done);271 });272 it('should invoke store\'s load method ' +273 'if store is changed', function (done) {274 var counter = 0;275 function Store() {}276 Store.prototype.load = function () {277 counter++;278 var self = this;279 return new Promise(function (fulfill) {280 fulfill('hello');281 setTimeout(function () {282 if (counter === 1) {283 self.$context.changed();284 }285 }, 10);286 });287 };288 var stores = {289 store1: {290 name: 'store1',291 constructor: Store292 }293 };294 var locator = createLocator(stores),295 context = {hello: 'world'},296 eventBus = locator.resolve('eventBus'),297 dispatcher = locator.resolve('storeDispatcher');298 dispatcher.setState({}, context);299 dispatcher.getStoreData(stores.store1.name)300 .then(function (result) {301 assert.strictEqual(counter, 1);302 assert.strictEqual(result, 'hello');303 });304 eventBus.on('storeChanged', function (storeName) {305 assert.strictEqual(storeName, stores.store1.name);306 dispatcher.getStoreData(stores.store1.name)307 .then(function (result) {308 assert.strictEqual(counter, 2);309 assert.strictEqual(result, 'hello');310 done();311 })312 .catch(done);313 });314 });315 it('should invoke store\'s load method ' +316 'if store is changed after state changing', function (done) {317 var counter = 0;318 function Store() {}319 Store.prototype.load = function () {320 counter++;321 return new Promise(function (fulfill) {322 setTimeout(function () {323 fulfill('hello');324 }, 10);325 });326 };327 var stores = {328 store1: {329 name: 'store1',330 constructor: Store331 }332 };333 var locator = createLocator(stores),334 context = {hello: 'world'},335 eventBus = locator.resolve('eventBus'),336 dispatcher = locator.resolve('storeDispatcher');337 dispatcher.setState({}, context);338 dispatcher.getStoreData(stores.store1.name)339 .then(function (result) {340 assert.strictEqual(counter, 1);341 assert.strictEqual(result, 'hello');342 eventBus.on('storeChanged', function (storeName) {343 assert.strictEqual(storeName, stores.store1.name);344 dispatcher.getStoreData(stores.store1.name)345 .then(function (result) {346 assert.strictEqual(counter, 2);347 assert.strictEqual(result, 'hello');348 done();349 })350 .catch(done);351 });352 dispatcher.setState({store1: {}}, context);353 });354 });355 it('should emit store\'s changed ' +356 'for dependant store ', function (done) {357 var loads = [];358 function Store1() {}359 Store1.prototype.load = function () {360 loads.push(this.$context.name);361 var self = this;362 if (loads.length === 1) {363 setTimeout(function () {364 self.$context.changed();365 }, 10);366 }367 return new Promise(function (fulfill) {368 fulfill('hello');369 });370 };371 function Store2() {372 this.$context.setDependency('store1');373 }374 Store2.prototype.load = function () {375 loads.push(this.$context.name);376 };377 function Store3() {378 this.$context.setDependency('store2');379 }380 Store3.prototype.load = function () {381 loads.push(this.$context.name);382 };383 var stores = {384 store1: {385 name: 'store1',386 constructor: Store1387 },388 store2: {389 name: 'store2',390 constructor: Store2391 },392 store3: {393 name: 'store3',394 constructor: Store3395 }396 };397 var locator = createLocator(stores),398 context = {hello: 'world'},399 eventBus = locator.resolve('eventBus'),400 dispatcher = locator.resolve('storeDispatcher');401 dispatcher.setState({}, context);402 Promise.all([403 dispatcher.getStoreData(stores.store1.name),404 dispatcher.getStoreData(stores.store2.name),405 dispatcher.getStoreData(stores.store3.name)406 ])407 .catch(done);408 eventBus.on('storeChanged', function (storeName) {409 if (storeName !== 'store3') {410 return;411 }412 return Promise.all([413 dispatcher.getStoreData(stores.store1.name),414 dispatcher.getStoreData(stores.store2.name),415 dispatcher.getStoreData(stores.store3.name)416 ])417 .then(function () {418 assert.strictEqual(loads[0], 'store1');419 assert.strictEqual(loads[1], 'store2');420 assert.strictEqual(loads[2], 'store3');421 assert.strictEqual(loads[3], 'store1');422 assert.strictEqual(loads[4], 'store2');423 assert.strictEqual(loads[5], 'store3');424 done();425 })426 .catch(done);427 });428 });429 it('should not cache store\'s data ' +430 'if there was an error loading data', function (done) {431 var counter = 0;432 function Store() {}433 Store.prototype.load = function () {434 counter++;435 if (counter === 1) {436 throw new Error('error');437 }438 return new Promise(function (fulfill) {439 setTimeout(function () {440 fulfill('hello');441 }, 10);442 });443 };444 var stores = {445 store1: {446 name: 'store1',447 constructor: Store448 }449 };450 var locator = createLocator(stores),451 context = {hello: 'world'},452 dispatcher = locator.resolve('storeDispatcher');453 dispatcher.setState({}, context);454 dispatcher.getStoreData(stores.store1.name)455 .catch(function (error) {456 assert.strictEqual(error.message, 'error');457 return dispatcher.getStoreData(stores.store1.name);458 })459 .then(function (result) {460 assert.strictEqual(counter, 2);461 assert.strictEqual(result, 'hello');462 done();463 })464 .catch(done);465 });466 it('should cache store\'s data ' +467 'only for it\'s lifetime', function (done) {468 var counter = 0;469 function Store() {470 this.$lifetime = 50;471 }472 Store.prototype.load = function () {473 counter++;474 return new Promise(function (fulfill) {475 setTimeout(function () {476 fulfill('hello' + counter);477 }, 10);478 });479 };480 var stores = {481 store1: {482 name: 'store1',483 constructor: Store484 }485 };486 var locator = createLocator(stores),487 context = {hello: 'world'},488 dispatcher = locator.resolve('storeDispatcher');489 dispatcher.setState({}, context);490 dispatcher.getStoreData(stores.store1.name)491 .then(function (data) {492 assert.strictEqual(data, 'hello1');493 return new Promise(function (fulfill) {494 setTimeout(function () {495 fulfill();496 }, 100);497 });498 })499 .then(function () {500 return dispatcher.getStoreData(stores.store1.name);501 })502 .then(function (result) {503 assert.strictEqual(counter, 2);504 assert.strictEqual(result, 'hello2');505 done();506 })507 .catch(done);508 });509 it('should reject promise when initial state ' +510 'is not set', function (done) {511 var stores = {512 store1: {513 name: 'store1',514 constructor: DataStore515 }516 };517 var locator = createLocator(stores),518 dispatcher = locator.resolve('storeDispatcher');519 dispatcher.getStoreData(stores.store1.name)520 .then(function () {521 done(new Error('Should fail'));522 })523 .catch(function (reason) {524 assert.strictEqual(525 reason.message, 'State should be set before any request'526 );527 done();528 });529 });530 });531 describe('#setState', function () {532 it('should set initial state and return empty array', function (done) {533 var stores = {534 store1: {535 name: 'store1',536 constructor: DataStore537 },538 store2: {539 name: 'store2',540 constructor: DataStore541 }542 };543 var locator = createLocator(stores),544 context = {hello: 'world'},545 eventBus = locator.resolve('eventBus'),546 dispatcher = locator.resolve('storeDispatcher');547 var names = dispatcher.setState({}, context);548 assert.strictEqual(names.length, 0);549 done();550 });551 it('should return names of changed stores', function (done) {552 var stores = {553 store1: {554 name: 'store1',555 constructor: DataStore556 },557 store2: {558 name: 'store2',559 constructor: DataStore560 },561 store3: {562 name: 'store3',563 constructor: DataStore564 },565 store4: {566 name: 'store4',567 constructor: DataStore568 },569 store5: {570 name: 'store5',571 constructor: DataStore572 }573 };574 var locator = createLocator(stores),575 context = {hello: 'world'},576 eventBus = locator.resolve('eventBus'),577 dispatcher = locator.resolve('storeDispatcher');578 var initState = {579 // to remove580 store1: {581 some: 'value'582 },583 // to change value584 store2: {585 some1: 'value1',586 some2: 2587 },588 // to change count of properties589 store3: {590 some1: 'value1',591 some2: 2,592 some3: true593 },594 // to keep the same595 store4: {596 some: 'value'597 }598 // store5 is absent at all599 };600 var newState = {601 store2: {602 some1: 'value2',603 some2: 1604 },605 store3: {606 some1: 'value1',607 some2: 3608 },609 store4: {610 some: 'value'611 },612 store5: {613 some: 'value'614 }615 };616 var names = dispatcher.setState(initState, context);617 assert.strictEqual(names.length, 0);618 dispatcher.getStoreData(stores.store2.name)619 .then(function () {620 var newContext = {hello: 'world2'},621 updatedNames = dispatcher.setState(622 newState, newContext623 );624 assert.strictEqual(updatedNames.length, 4);625 assert.deepEqual(updatedNames, [626 'store1', 'store2', 'store3', 'store5'627 ]);628 done();629 });630 });631 });632 describe('#sendAction', function () {633 it('should send action to store if it has handler', function (done) {634 function Store() {}635 Store.prototype.handleSomeAction = function (args) {636 return {637 args: args,638 result: 'result'639 };640 };641 var stores = {642 store1: {643 name: 'store1',644 constructor: Store645 }646 };647 var actionParameters = {},648 locator = createLocator(stores),649 dispatcher = locator.resolve('storeDispatcher');650 dispatcher.setState({}, {});651 dispatcher.sendAction(652 stores.store1.name, 'some-action', actionParameters653 )654 .then(function (result) {655 assert.strictEqual(result.args, actionParameters);656 assert.strictEqual(result.result, 'result');657 done();658 })659 .catch(done);660 });661 it('should send action to store if it has handler', function (done) {662 function Store1() {}663 Store1.prototype.handleHello = function (name) {664 return this.$context.sendAction('store2', 'world', name);665 };666 function Store2() {}667 Store2.prototype.handleWorld = function (name) {668 return 'hello, ' + name;669 };670 var stores = {671 store1: {672 name: 'store1',673 constructor: Store1674 },675 store2: {676 name: 'store2',677 constructor: Store2678 }679 };680 var locator = createLocator(stores),681 dispatcher = locator.resolve('storeDispatcher');682 dispatcher.setState({}, {});683 dispatcher.sendAction(684 stores.store1.name, 'hello', 'catberry'685 )686 .then(function (result) {687 assert.strictEqual(result, 'hello, catberry');688 done();689 })690 .catch(done);691 });692 it('should response with undefined ' +693 'if there is no such action handler', function (done) {694 var stores = {695 store1: {696 name: 'store1',697 constructor: DataStore698 }699 };700 var actionParameters = {},701 locator = createLocator(stores),702 dispatcher = locator.resolve('storeDispatcher');703 dispatcher.setState({}, {});704 dispatcher.sendAction(705 stores.store1.name, 'some-action', actionParameters706 )707 .then(function (result) {708 assert.strictEqual(result, undefined);709 done();710 })711 .catch(done);712 });713 it('should pass error from action handler', function (done) {714 function Store() {}715 Store.prototype.handleSomeAction = function () {716 throw new Error('error');717 };718 var stores = {719 store1: {720 name: 'store1',721 constructor: Store722 }723 };724 var actionParameters = {},725 locator = createLocator(stores),726 dispatcher = locator.resolve('storeDispatcher');727 dispatcher.setState({}, {});728 dispatcher.sendAction(729 stores.store1.name, 'some-action', actionParameters730 )731 .then(function () {732 done(new Error('Should fail'));733 })734 .catch(function (reason) {735 assert.strictEqual(reason.message, 'error');736 done();737 });738 });739 });740 describe('#sendBroadcastAction', function () {741 it('should send action to all stores with handlers', function (done) {742 function Store() {}743 Store.prototype.handleSomeAction = function (args) {744 return {745 args: args,746 result: this.$context.name747 };748 };749 var stores = {750 store1: {751 name: 'store1',752 constructor: Store753 },754 store2: {755 name: 'store2',756 constructor: DataStore757 },758 store3: {759 name: 'store3',760 constructor: Store761 }762 };763 var actionParameters = {},764 locator = createLocator(stores),765 dispatcher = locator.resolve('storeDispatcher');766 dispatcher.setState({}, {});767 dispatcher.sendBroadcastAction(768 'some-action', actionParameters769 )770 .then(function (results) {771 assert.strictEqual(results.length, 2);772 assert.strictEqual(results[0].args, actionParameters);773 assert.strictEqual(results[0].result, 'store1');774 assert.strictEqual(results[1].args, actionParameters);775 assert.strictEqual(results[1].result, 'store3');776 done();777 })778 .catch(done);779 });780 it('should send action to all stores ' +781 'with handlers from $context', function (done) {782 function Store1() {}783 Store1.prototype.handleSome = function (name) {784 return this.$context.sendBroadcastAction('action', name);785 };786 function Store2() {}787 Store2.prototype.handleAction = function (name) {788 return 'hello from store2, ' + name;789 };790 function Store3() {}791 Store3.prototype.handleAction = function (name) {792 return 'hello from store3, ' + name;793 };794 var stores = {795 store1: {796 name: 'store1',797 constructor: Store1798 },799 store2: {800 name: 'store2',801 constructor: Store2802 },803 store3: {804 name: 'store3',805 constructor: Store3806 }807 };808 var locator = createLocator(stores),809 dispatcher = locator.resolve('storeDispatcher');810 dispatcher.setState({}, {});811 dispatcher.sendAction('store1', 'some', 'catberry')812 .then(function (results) {813 assert.strictEqual(results.length, 2);814 assert.strictEqual(815 results[0], 'hello from store2, catberry'816 );817 assert.strictEqual(818 results[1], 'hello from store3, catberry'819 );820 done();821 })822 .catch(done);823 });824 });825});826function createLocator(stores, config) {827 var locator = new ServiceLocator(),828 eventBus = new events.EventEmitter();829 eventBus.on('error', function () {});830 locator.registerInstance('serviceLocator', locator);831 locator.registerInstance('eventBus', eventBus);832 locator.registerInstance('config', config || {});833 locator.registerInstance('storeLoader', {834 load: function () {835 return Promise.resolve(stores);836 },837 getStoresByNames: function () {838 return stores;839 }840 });...
LocalizationLoader.js
Source:LocalizationLoader.js
...60 describe('#constructor', () => {61 it('should throw exception when default locale is not specified',62 () => {63 assert.throws(() => {64 const locator = createLocator();65 const localizationLoader = new LocalizationLoader(locator);66 }, 'Error expected');67 });68 it('should throw exception when default locale is wrong',69 () => {70 assert.throws(() => {71 const config = {72 l10n: {73 defaultLocale: 'china'74 }75 };76 const locator = createLocator();77 locator.registerInstance('config', config);78 const localizationLoader = new LocalizationLoader(locator);79 }, 'Error expected');80 });81 it('should throw exception when default localization can not be loaded',82 done => {83 const locator = createLocator(components);84 const eventBus = locator.resolve('eventBus');85 const config = {86 l10n: {87 defaultLocale: 'ch'88 }89 };90 locator.registerInstance('config', config);91 const localizationLoader = new LocalizationLoader(locator);92 eventBus93 .on('error', error => {94 assert.strictEqual(95 error.message, 'Can not load default locale ch'96 );97 done();98 });99 eventBus.emit('allComponentsLoaded');100 });101 it('should not throw exception when default locale is specified',102 () => {103 assert.doesNotThrow(() => {104 const locator = createLocator();105 locator.registerInstance('config', defaultConfig);106 const localizationLoader = new LocalizationLoader(locator);107 });108 });109 });110 describe('#load', () => {111 it('should throw exception on wrong locale', () => {112 const locator = createLocator();113 locator.registerInstance('config', defaultConfig);114 const localizationLoader = new LocalizationLoader(locator);115 assert.throws(() => loader.load('wrong'), 'Error expected');116 });117 it('should return default localization when argument is default locale',118 done => {119 const locator = createLocator();120 const eventBus = locator.resolve('eventBus');121 locator.registerInstance('config', defaultConfig);122 const loader = new LocalizationLoader(locator);123 eventBus124 .on('error', done)125 .on('l10nLoaded', () => {126 const localization = loader.load(defaultLocale);127 assert.deepEqual(128 localization, localizations[defaultLocale],129 'Localization do not match'130 );131 done();132 });133 eventBus.emit('allComponentsLoaded');134 });135 it('should return non-default localization merged with default',136 done => {137 const locator = createLocator();138 const eventBus = locator.resolve('eventBus');139 locator.registerInstance('config', defaultConfig);140 const loader = new LocalizationLoader(locator);141 eventBus142 .on('error', done)143 .on('l10nLoaded', () => {144 const enLocalization = localizations.en;145 const localization = loader.load('en');146 assert.strictEqual(147 localization.FIRST_VALUE,148 enLocalization.FIRST_VALUE,149 'Localization do not match'150 );151 assert.strictEqual(152 localization.SECOND_VALUE,153 enLocalization.SECOND_VALUE,154 'Localization do not match'155 );156 assert.strictEqual(157 localization.THIRD_VALUE,158 defaultLocalization.THIRD_VALUE,159 'Localization do not match'160 );161 done();162 });163 eventBus.emit('allComponentsLoaded');164 });165 it('should return localization merged with default using full name',166 done => {167 const locator = createLocator();168 const eventBus = locator.resolve('eventBus');169 locator.registerInstance('config', defaultConfig);170 const loader = new LocalizationLoader(locator);171 eventBus172 .on('error', done)173 .on('l10nLoaded', () => {174 const enUsLocalization = localizations['en-us'];175 const localization = loader.load('en-us');176 assert.strictEqual(177 localization.FIRST_VALUE,178 enUsLocalization.FIRST_VALUE,179 'Localization do not match'180 );181 assert.strictEqual(182 localization.SECOND_VALUE,183 enUsLocalization.SECOND_VALUE,184 'Localization do not match'185 );186 assert.strictEqual(187 localization.THIRD_VALUE,188 defaultLocalization.THIRD_VALUE,189 'Localization do not match'190 );191 assert.strictEqual(192 localization.FOURTH_VALUE,193 enUsLocalization.FOURTH_VALUE,194 'Localization do not match'195 );196 assert.strictEqual(197 localization.FIFTH_VALUE,198 enUsLocalization.FIFTH_VALUE,199 'Localization do not match'200 );201 done();202 });203 eventBus.emit('allComponentsLoaded');204 });205 it('should return localization merged with components localization',206 done => {207 const locator = createLocator(components);208 const eventBus = locator.resolve('eventBus');209 locator.registerInstance('config', defaultConfig);210 const loader = new LocalizationLoader(locator);211 eventBus212 .on('error', done)213 .on('l10nLoaded', () => {214 const localization = loader.load('en-us');215 const expectedLocalization = {216 FIRST_VALUE: 'en-us locale first by module1',217 SECOND_VALUE: 'en-us locale second',218 THIRD_VALUE: 'ru locale third',219 FOURTH_VALUE: 'en-us locale fourth by module2',220 FIFTH_VALUE: 'en-us locale fifth',221 SIXTH_VALUE: 'en-us locale sixth by module1',222 SEVENTH_VALUE: 'en-us locale seventh by module2',223 EIGHTH_VALUE: 'en-us locale eighth by module2',224 $pluralization: localizations['en-us'].$pluralization225 };226 assert.deepEqual(localization, expectedLocalization,227 'Localization do not match'228 );229 done();230 });231 eventBus.emit('allComponentsLoaded');232 }233 );234 it('should return same localization on short or full name',235 done => {236 const locator = createLocator(components);237 const eventBus = locator.resolve('eventBus');238 locator.registerInstance('config', defaultConfig);239 const loader = new LocalizationLoader(locator);240 eventBus241 .on('error', done)242 .on('l10nLoaded', () => {243 const enLocalization = loader.load('en');244 const enGbLocalization = loader.load('en-gb');245 assert.deepEqual(enLocalization, enGbLocalization,246 'Localization do not match'247 );248 done();249 });250 eventBus.emit('allComponentsLoaded');251 });252 });253 describe('#getMiddleware', () => {254 it('should set browser locale if it is absent in cookie',255 done => {256 const locator = createLocator();257 locator.registerInstance('config', defaultConfig);258 const loader = new LocalizationLoader(locator);259 const server = createServer(loader.getMiddleware());260 server.listen(8081, () => {261 const request = http.request({262 port: 8081,263 agent: false,264 headers: {265 'Accept-Language': 'en-US,ru;q=0.8,en;q=0.4'266 }267 },268 response => {269 assert.strictEqual(response.statusCode, 200,270 'Wrong status');271 assert.strictEqual(272 response.headers['set-cookie'] instanceof273 Array,274 true,275 'Response should have cookies');276 assert.strictEqual(277 response.headers['set-cookie'].length,278 1,279 'Response should have one cookie setup'280 );281 assert.strictEqual(/^locale=en-us/282 .test(response.headers['set-cookie'][0]),283 true,284 'Response cookie should have locale'285 );286 server.close(() => done());287 });288 request.end();289 });290 });291 it('should set browser locale with specified cookie parameters',292 done => {293 const locator = createLocator();294 const config = Object.create(defaultConfig);295 config.l10n.cookie = {296 name: 'testName',297 path: '/some/path',298 domain: 'some.domain.org',299 secure: true,300 httpOnly: true,301 maxAge: 500302 };303 locator.registerInstance('config', config);304 const loader = new LocalizationLoader(locator);305 const server = createServer(loader.getMiddleware());306 server.listen(8091, () => {307 let expireDate = '';308 const request = http.request({309 port: 8091,310 agent: false,311 headers: {312 'Accept-Language': 'en-US,ru;q=0.8,en;q=0.4'313 }314 },315 response => {316 assert.strictEqual(317 response.statusCode, 200, 'Wrong status'318 );319 assert.strictEqual(320 response.headers['set-cookie'] instanceof321 Array,322 true,323 'Response should have cookies');324 assert.strictEqual(325 response.headers['set-cookie'].length,326 1,327 'Response should have one cookie setup'328 );329 assert.strictEqual(330 response.headers['set-cookie'][0],331 `testName=en-us\332; Max-Age=${config.l10n.cookie.maxAge}\333; Expires=${expireDate.toUTCString()}\334; Path=${config.l10n.cookie.path}\335; Domain=${config.l10n.cookie.domain}\336; Secure; HttpOnly`,337 'Response cookie should have locale'338 );339 server.close(() => done());340 });341 expireDate = new Date((new Date()).getTime() +342 config.l10n.cookie.maxAge * 1000);343 request.end();344 });345 });346 it('should set default locale if browser locale is absent',347 done => {348 const locator = createLocator();349 locator.registerInstance('config', defaultConfig);350 const loader = new LocalizationLoader(locator);351 const server = createServer(loader.getMiddleware());352 server.listen(8082, () => {353 const request = http.request({354 port: 8082,355 agent: false356 },357 response => {358 assert.strictEqual(response.statusCode, 200,359 'Wrong status');360 assert.strictEqual(361 response.headers['set-cookie'] instanceof362 Array,363 true,364 'Response should have cookies');365 assert.strictEqual(366 response.headers['set-cookie'].length,367 1,368 'Response should have one cookie setup'369 );370 // TODO: refactoring, old value 'locale'371 assert.strictEqual(/^testName=ru/372 .test(response.headers['set-cookie'][0]),373 true,374 'Response cookie should have locale'375 );376 server.close(() => done());377 });378 request.end();379 });380 });381 it('should set default locale if wrong locale is used in cookies',382 done => {383 const locator = createLocator();384 locator.registerInstance('config', defaultConfig);385 const loader = new LocalizationLoader(locator);386 const server = createServer(loader.getMiddleware());387 server.listen(8083, () => {388 const request = http.request({389 port: 8083,390 agent: false,391 headers: {392 Cookie: 'locale=wrong'393 }394 },395 response => {396 assert.strictEqual(response.statusCode, 200,397 'Wrong status');398 assert.strictEqual(response.headers['set-cookie'],399 undefined,400 'Response should not have cookies');401 server.close(() => done());402 });403 request.end();404 });405 });406 it('should return localization file using cookie locale',407 done => {408 const locator = createLocator();409 const eventBus = locator.resolve('eventBus');410 locator.registerInstance('config', defaultConfig);411 const loader = new LocalizationLoader(locator);412 const server = createServer(loader.getMiddleware());413 const enUsLocalization = localizations['en-us'];414 const mergedLocalization = {};415 mergedLocalization.FIRST_VALUE =416 enUsLocalization.FIRST_VALUE;417 mergedLocalization.SECOND_VALUE =418 enUsLocalization.SECOND_VALUE;419 mergedLocalization.THIRD_VALUE =420 defaultLocalization.THIRD_VALUE;421 mergedLocalization.FOURTH_VALUE =422 enUsLocalization.FOURTH_VALUE;423 mergedLocalization.FIFTH_VALUE =424 enUsLocalization.FIFTH_VALUE;425 mergedLocalization.$pluralization =426 localizations['en-us'].$pluralization;427 eventBus428 .on('error', done)429 .on('l10nLoaded', () => {430 const request = http.request({431 port: 8084,432 agent: false,433 path: '/l10n.js',434 headers: {435 Cookie: 'locale=en-us'436 }437 },438 response => {439 assert.strictEqual(440 response.statusCode, 200, 'Wrong status'441 );442 let data = '';443 response.setEncoding('utf8');444 response445 .on('data', chunk => {446 data += chunk;447 })448 .on('end', () => {449 /* eslint no-eval: 0*/450 const window = {};451 eval(data);452 assert.deepEqual(453 window.localization,454 mergedLocalization,455 'Localization do not match'456 );457 server.close(() => done());458 });459 });460 request.end();461 });462 server.listen(8084, () => eventBus.emit('allComponentsLoaded'));463 });464 it('should return localization file using cookie short locale',465 done => {466 const locator = createLocator();467 const eventBus = locator.resolve('eventBus');468 locator.registerInstance('config', defaultConfig);469 const loader = new LocalizationLoader(locator);470 const server = createServer(loader.getMiddleware());471 const enLocalization = localizations.en;472 const mergedLocalization = {};473 mergedLocalization.FIRST_VALUE =474 enLocalization.FIRST_VALUE;475 mergedLocalization.SECOND_VALUE =476 enLocalization.SECOND_VALUE;477 mergedLocalization.THIRD_VALUE =478 defaultLocalization.THIRD_VALUE;479 mergedLocalization.$pluralization =480 localizations.en.$pluralization;481 eventBus482 .on('error', done)483 .on('l10nLoaded', () => {484 const request = http.request({485 port: 8085,486 agent: false,487 path: '/l10n.js',488 headers: {489 Cookie: 'locale=en-au'490 }491 },492 response => {493 assert.strictEqual(494 response.statusCode, 200, 'Wrong status'495 );496 let data = '';497 response.setEncoding('utf8');498 response499 .on('data', chunk => {500 data += chunk;501 })502 .on('end', () => {503 /* eslint no-eval: 0*/504 const window = {};505 eval(data);506 assert.deepEqual(507 window.localization,508 mergedLocalization,509 'Localization do not match'510 );511 server.close(() => done());512 });513 });514 request.end();515 });516 server.listen(8085, () => eventBus.emit('allComponentsLoaded'));517 });518 it('should return default localization file using cookie wrong locale',519 done => {520 const locator = createLocator();521 const eventBus = locator.resolve('eventBus');522 locator.registerInstance('config', defaultConfig);523 const loader = new LocalizationLoader(locator);524 const server = createServer(loader.getMiddleware());525 eventBus526 .on('error', done)527 .on('l10nLoaded', () => {528 const request = http.request({529 port: 8086,530 agent: false,531 path: '/l10n.js',532 headers: {533 Cookie: 'locale=ch'534 }535 },536 response => {537 assert.strictEqual(538 response.statusCode, 200, 'Wrong status'539 );540 let data = '';541 response.setEncoding('utf8');542 response543 .on('data', chunk => {544 data += chunk;545 })546 .on('end', () => {547 /* eslint no-eval: 0*/548 const window = {};549 eval(data);550 assert.deepEqual(551 window.localization,552 defaultLocalization,553 'Localization do not match'554 );555 server.close(() => done());556 });557 });558 request.end();559 });560 server.listen(8086, () => eventBus.emit('allComponentsLoaded'));561 });562 });563});564/**565 * Create ServiceLocator object566 * @param components567 * @returns {ServiceLocator}568 */569function createLocator(components) {570 components = components || {};571 const locator = new ServiceLocator();572 locator.registerInstance('serviceLocator', locator);573 const componentFinder = new events.EventEmitter();574 componentFinder.find = () => Promise.resolve(components);575 locator.registerInstance('componentFinder', componentFinder);576 locator.registerInstance('eventBus', new events.EventEmitter());577 return locator;578}579/**580 * Create server581 * @param middleware582 * @param endCallback583 * @returns {*}...
LocalizationProvider.js
Source:LocalizationProvider.js
...12describe('LocalizationProvider', () => {13 describe('constructor', () => {14 it('should throw error if l10n config is not specified',15 () => {16 const locator = createLocator({});17 assert.throws(() => {18 const provider = new LocalizationProvider(locator);19 });20 });21 it('should throw error if default locale is not specified',22 () => {23 const config = {24 l10n: {}25 };26 const locator = createLocator(config);27 assert.throws(() => {28 const provider = new LocalizationProvider(locator);29 });30 });31 });32 describe('#getCurrentLocale', () => {33 it('should get current locale value from context', () => {34 const config = {35 l10n: {36 defaultLocale: 'en-us',37 cookie: {38 name: 'coolLocale'39 }40 }41 };42 const locator = createLocator(config);43 const provider = new LocalizationProvider(locator);44 const locale = provider.getCurrentLocale({45 cookie: {46 get: name => {47 if (name === config.l10n.cookie.name) {48 return 'some-locale';49 }50 return null;51 }52 }53 });54 assert.strictEqual(55 locale, 'some-locale', 'Wrong localized value'56 );57 });58 it('should get current locale as default locale if cookie is empty',59 () => {60 const config = {61 l10n: {62 defaultLocale: 'en-us',63 cookie: {64 name: 'coolLocale'65 }66 }67 };68 const locator = createLocator(config);69 const provider = new LocalizationProvider(locator);70 const locale = provider.getCurrentLocale({71 cookie: {72 get: () => { }73 }74 });75 assert.strictEqual(76 locale, config.l10n.defaultLocale, 'Wrong localized value'77 );78 });79 });80 describe('#get', () => {81 it('should get value from localization', () => {82 const localizations = {83 en: {84 TEST_VALUE: 'en test'85 },86 ru: {87 TEST_VALUE: 'ru test'88 }89 };90 const locator = createLocator({91 l10n: {92 defaultLocale: 'en'93 },94 localizations95 });96 locator.registerInstance('localizations', localizations);97 const provider = new LocalizationProvider(locator);98 assert.strictEqual(99 provider.get('en', 'TEST_VALUE'), localizations.en.TEST_VALUE,100 'Wrong localized value'101 );102 assert.strictEqual(103 provider.get('ru', 'TEST_VALUE'), localizations.ru.TEST_VALUE,104 'Wrong localized value'105 );106 });107 it('should return empty string if localization value is absent',108 () => {109 const locator = createLocator({110 l10n: {111 defaultLocale: 'en'112 },113 localizations: {}114 });115 const provider = new LocalizationProvider(locator);116 assert.strictEqual(117 provider.get('en', 'TEST_VALUE'), '',118 'Wrong localized value'119 );120 assert.strictEqual(121 provider.get('ru', 'TEST_VALUE'), '',122 'Wrong localized value'123 );124 });125 it('should return key instead of empty string when allowed placeholders',126 () => {127 const locator = createLocator({128 l10n: {129 defaultLocale: 'en',130 placeholder: true131 },132 localizations: {}133 });134 const provider = new LocalizationProvider(locator);135 const key = 'TEST_VALUE';136 assert.strictEqual(137 provider.get('en', key), key,138 'Wrong localized value'139 );140 assert.strictEqual(141 provider.get('ru', key), key,142 'Wrong localized value'143 );144 });145 it('should return first plural form if value is array',146 done => {147 const config = {148 l10n: {149 defaultLocale: 'ru',150 path: localizationPath151 }152 };153 const locator = createLocator(config);154 const eventBus = locator.resolve('eventBus');155 locator.register('localizationLoader', LocalizationLoader);156 const provider = new LocalizationProvider(locator);157 eventBus158 .on('error', done)159 .on('l10nLoaded', () => {160 assert.strictEqual(161 provider.get('en', 'TEST_VALUE'),162 'en form1',163 'Wrong localized value'164 );165 assert.strictEqual(166 provider.get('ru', 'TEST_VALUE'),167 'ru form1',168 'Wrong localized value'169 );170 done();171 });172 eventBus.emit('allComponentsLoaded');173 });174 });175 describe('#pluralize', () => {176 it('should return plural form from locale', done => {177 const config = {178 l10n: {179 defaultLocale: 'ru',180 path: localizationPath181 }182 };183 const locator = createLocator(config);184 const eventBus = locator.resolve('eventBus');185 locator.register('localizationLoader', LocalizationLoader);186 const provider = new LocalizationProvider(locator);187 eventBus188 .on('error', done)189 .on('l10nLoaded', () => {190 assert.strictEqual(191 provider.pluralize('en', 'TEST_VALUE', 1),192 'en form1',193 'Wrong localized value'194 );195 assert.strictEqual(196 provider.pluralize('en', 'TEST_VALUE', 2),197 'en form2',198 'Wrong localized value'199 );200 assert.strictEqual(201 provider.pluralize('ru', 'TEST_VALUE', 1),202 'ru form1',203 'Wrong localized value'204 );205 assert.strictEqual(206 provider.pluralize('ru', 'TEST_VALUE', 2),207 'ru form2',208 'Wrong localized value'209 );210 assert.strictEqual(211 provider.pluralize('ru', 'TEST_VALUE', 5),212 'ru form3',213 'Wrong localized value'214 );215 done();216 });217 eventBus.emit('allComponentsLoaded');218 });219 it('should return plural form from default locale if not found',220 done => {221 const config = {222 l10n: {223 defaultLocale: 'ru',224 path: localizationPath225 }226 };227 const locator = createLocator(config);228 const eventBus = locator.resolve('eventBus');229 locator.register('localizationLoader', LocalizationLoader);230 const provider = new LocalizationProvider(locator);231 eventBus232 .on('error', done)233 .on('l10nLoaded', () => {234 assert.strictEqual(235 provider.pluralize('en', 'TEST_VALUE_ONLY_RU', 5),236 'ru-only form3',237 'Wrong localized value'238 );239 assert.strictEqual(240 provider.pluralize('ru', 'TEST_VALUE_ONLY_RU', 5),241 'ru-only form3',242 'Wrong localized value'243 );244 done();245 });246 eventBus.emit('allComponentsLoaded');247 });248 it('should return string value if not array specified',249 done => {250 const config = {251 l10n: {252 defaultLocale: 'ru',253 path: localizationPath254 }255 };256 const locator = createLocator(config);257 const eventBus = locator.resolve('eventBus');258 locator.register('localizationLoader', LocalizationLoader);259 const provider = new LocalizationProvider(locator);260 eventBus261 .on('error', done)262 .on('l10nLoaded', () => {263 assert.strictEqual(264 provider.pluralize('en', 'TEST_VALUE3', 5),265 'en form1',266 'Wrong localized value'267 );268 assert.strictEqual(269 provider.pluralize('ru', 'TEST_VALUE3', 5),270 'ru form1',271 'Wrong localized value'272 );273 done();274 });275 eventBus.emit('allComponentsLoaded');276 });277 it('should return empty string if incorrect count of forms',278 done => {279 const config = {280 l10n: {281 defaultLocale: 'ru',282 path: localizationPath283 }284 };285 const locator = createLocator(config);286 const eventBus = locator.resolve('eventBus');287 locator.register('localizationLoader', LocalizationLoader);288 const provider = new LocalizationProvider(locator);289 eventBus290 .on('error', done)291 .on('l10nLoaded', () => {292 assert.strictEqual(293 provider.pluralize('en', 'TEST_VALUE2', 5),294 '',295 'Wrong localized value'296 );297 assert.strictEqual(298 provider.pluralize('ru', 'TEST_VALUE2', 5),299 '',300 'Wrong localized value'301 );302 done();303 });304 eventBus.emit('allComponentsLoaded');305 });306 it('should return key if incorrect count of forms and placeholders allowed',307 done => {308 const config = {309 l10n: {310 defaultLocale: 'ru',311 path: localizationPath,312 placeholder: true313 }314 };315 const locator = createLocator(config);316 const eventBus = locator.resolve('eventBus');317 locator.register('localizationLoader', LocalizationLoader);318 const provider = new LocalizationProvider(locator);319 eventBus320 .on('error', done)321 .on('l10nLoaded', () => {322 const key = 'TEST_VALUE2';323 assert.strictEqual(324 provider.pluralize('en', key, 5),325 key,326 'Wrong localized value'327 );328 assert.strictEqual(329 provider.pluralize('ru', key, 5),330 key,331 'Wrong localized value'332 );333 done();334 });335 eventBus.emit('allComponentsLoaded');336 });337 it('should return key if localization absent and placeholders allowed',338 done => {339 const config = {340 l10n: {341 defaultLocale: 'ru',342 path: localizationPath,343 placeholder: true344 }345 };346 const locator = createLocator(config);347 const eventBus = locator.resolve('eventBus');348 locator.register('localizationLoader', LocalizationLoader);349 const provider = new LocalizationProvider(locator);350 eventBus351 .on('error', done)352 .on('l10nLoaded', () => {353 const key = 'TEST_VALUE4';354 assert.strictEqual(355 provider.pluralize('en', key, 5),356 key,357 'Wrong localized value'358 );359 assert.strictEqual(360 provider.pluralize('ru', key, 5),361 key,362 'Wrong localized value'363 );364 done();365 });366 eventBus.emit('allComponentsLoaded');367 });368 });369});370/**371 * Create ServiceLocator object372 * @param {Object} config373 * @returns {ServiceLocator}374 */375function createLocator(config) {376 const locator = new ServiceLocator();377 locator.registerInstance('config', config);378 locator.registerInstance('eventBus', new events.EventEmitter());379 const componentFinder = new events.EventEmitter();380 componentFinder.find = () => Promise.resolve({});381 locator.registerInstance('componentFinder', componentFinder);382 locator.registerInstance('localizationLoader', new LocalizationLoaderMock(config.localizations));383 locator.register('localizationProvider', LocalizationProvider);384 return locator;...
ModuleApiProvider.js
Source:ModuleApiProvider.js
...7var ModuleApiProvider = require('../../../lib/providers/ModuleApiProvider');8lab.experiment('lib/providers/ModuleApiProvider', function () {9 lab.experiment('#on', function () {10 lab.test('should throw error if handler is not a function', function (done) {11 var locator = createLocator();12 var api = new ModuleApiProvider(locator);13 assert.throws(function () {14 api.on('some', {});15 }, Error);16 done();17 });18 lab.test('should throw error if event name is not a string', function (done) {19 var locator = createLocator();20 var api = new ModuleApiProvider(locator);21 assert.throws(function () {22 api.on({}, function () {});23 }, Error);24 done();25 });26 lab.test('should properly register handler on event', function (done) {27 var locator = createLocator();28 var bus = locator.resolve('eventBus');29 var api = new ModuleApiProvider(locator);30 api.on('event', function (arg) {31 assert.strictEqual(arg, 'hello');32 done();33 });34 bus.emit('event', 'hello');35 });36 });37 lab.experiment('#once', function () {38 lab.test('should throw error if handler is not a function', function (done) {39 var locator = createLocator();40 var api = new ModuleApiProvider(locator);41 assert.throws(function () {42 api.once('some', {});43 }, Error);44 done();45 });46 lab.test('should throw error if event name is not a string', function (done) {47 var locator = createLocator();48 var api = new ModuleApiProvider(locator);49 assert.throws(function () {50 api.once({}, function () {});51 }, Error);52 done();53 });54 lab.test('should properly register handler on event', function (done) {55 var locator = createLocator();56 var bus = locator.resolve('eventBus');57 var api = new ModuleApiProvider(locator);58 var was = false;59 api.once('event', function (arg) {60 if (was) {61 assert.fail();62 }63 was = true;64 assert.strictEqual(arg, 'hello');65 });66 bus.emit('event', 'hello');67 assert.strictEqual(was, true);68 done();69 });70 });71 lab.experiment('#removeListener', function () {72 lab.test('should throw error if handler is not a function', function (done) {73 var locator = createLocator();74 var api = new ModuleApiProvider(locator);75 assert.throws(function () {76 api.removeListener('some', {});77 }, Error);78 done();79 });80 lab.test('should throw error if event name is not a string', function (done) {81 var locator = createLocator();82 var api = new ModuleApiProvider(locator);83 assert.throws(function () {84 api.removeListener({}, function () {});85 }, Error);86 done();87 });88 lab.test('should properly remove listener', function (done) {89 var locator = createLocator();90 var bus = locator.resolve('eventBus');91 var api = new ModuleApiProvider(locator);92 var was = false,93 handler = function () {94 was = true;95 };96 api.on('event', handler);97 api.removeListener('event', handler);98 bus.emit('event', 'hello');99 assert.strictEqual(was, false);100 done();101 });102 });103 lab.experiment('#removeAllListeners', function () {104 lab.test('should throw error if event name is not a string', function (done) {105 var locator = createLocator();106 var api = new ModuleApiProvider(locator);107 assert.throws(function () {108 api.removeAllListeners({});109 }, Error);110 done();111 });112 lab.test('should properly remove all listeners', function (done) {113 var locator = createLocator();114 var bus = locator.resolve('eventBus');115 var api = new ModuleApiProvider(locator);116 var was = false,117 handler1 = function () {118 was = true;119 },120 handler2 = function () {121 was = true;122 };123 api.on('event', handler1);124 api.on('event', handler2);125 api.removeAllListeners('event');126 bus.emit('event', 'hello');127 assert.strictEqual(was, false);128 done();129 });130 });131 lab.experiment('#redirect', function () {132 lab.test('should save last redirected URI', function (done) {133 var locator = createLocator();134 var api = new ModuleApiProvider(locator);135 assert.strictEqual(api.redirect('/some1') instanceof Promise, true);136 assert.strictEqual(api.redirect('/some2') instanceof Promise, true);137 assert.strictEqual(api.actions.redirectedTo, '/some2');138 done();139 });140 });141 lab.experiment('#clearFragment', function () {142 lab.test('should save flag that hash has been cleared', function (done) {143 var locator = createLocator();144 var api = new ModuleApiProvider(locator);145 assert.strictEqual(api.actions.isFragmentCleared, false);146 assert.strictEqual(api.clearFragment() instanceof Promise, true);147 assert.strictEqual(api.actions.isFragmentCleared, true);148 done();149 });150 });151 lab.experiment('#getInlineScript', function () {152 lab.test('should return browser script for redirection', function (done) {153 var locator = createLocator();154 var api = new ModuleApiProvider(locator);155 api.redirect('http://some');156 var expected = '<script>' +157 'window.location.assign(\'http://some\');' +158 '</script>';159 assert.strictEqual(api.getInlineScript(), expected);160 done();161 });162 lab.test('should return browser script for cookies', function (done) {163 var locator = createLocator();164 var api = new ModuleApiProvider(locator);165 api.cookie.set({166 key: 'some1',167 value: 'value1'168 });169 api.cookie.set({170 key: 'some2',171 value: 'value2'172 });173 var expected = '<script>' +174 'window.document.cookie = \'some1=value1\';' +175 'window.document.cookie = \'some2=value2\';' +176 '</script>';177 assert.strictEqual(api.getInlineScript(), expected);178 done();179 });180 lab.test('should return browser script for clearing fragment', function (done) {181 var locator = createLocator();182 var api = new ModuleApiProvider(locator);183 api.clearFragment();184 var expected = '<script>' +185 'window.location.hash = \'\';' +186 '</script>';187 assert.strictEqual(api.getInlineScript(), expected);188 done();189 });190 });191});192function createLocator() {193 var locator = new ServiceLocator();194 locator.register('cookieWrapper', CookieWrapper);195 locator.registerInstance('serviceLocator', locator);196 locator.registerInstance('eventBus', new events.EventEmitter());197 return locator;...
StoreLoader.js
Source:StoreLoader.js
...17 name: 'Test1',18 path: 'test/cases/lib/loaders/StoreLoader/Test1.js'19 }20 };21 const locator = createLocator(stores);22 const loader = locator.resolve('storeLoader');23 loader24 .load()25 .then(loadedStores => {26 assert.strictEqual(loadedStores, loader.getStoresByNames());27 const storeNames = Object.keys(loadedStores);28 assert.strictEqual(storeNames.length, 1);29 const store = loadedStores[storeNames[0]];30 assert.strictEqual(store.name, stores.Test1.name);31 assert.strictEqual(typeof (store.constructor), 'function');32 })33 .then(done)34 .catch(done);35 });36 it('should load nothing if an error occurs', function(done) {37 const stores = {38 Test1: {39 name: 'Test1',40 path: 'test/cases/lib/loaders/StoreLoader/Test1.js'41 }42 };43 const locator = createLocator(stores, () => done());44 const eventBus = locator.resolve('eventBus');45 const loader = locator.resolve('storeLoader');46 eventBus.on('storeLoaded', () => {47 throw new Error('TestError');48 });49 loader50 .load()51 .then(loadedStores => assert.deepEqual(loadedStores, {}))52 .catch(done);53 });54 it('should properly transform stores', function(done) {55 const stores = {56 Test1: {57 name: 'Test1',58 path: 'test/cases/lib/loaders/StoreLoader/Test1.js'59 }60 };61 const locator = createLocator(stores);62 locator.registerInstance('storeTransform', {63 transform: store => {64 store.name += '!';65 return store;66 }67 });68 locator.registerInstance('storeTransform', {69 transform: store => {70 store.name += '?';71 return Promise.resolve(store);72 }73 });74 const loader = locator.resolve('storeLoader');75 loader76 .load()77 .then(loadedStores => {78 assert.strictEqual(loadedStores, loader.getStoresByNames());79 const storeNames = Object.keys(loadedStores);80 assert.strictEqual(storeNames.length, 1);81 const store = loadedStores[storeNames[0]];82 assert.strictEqual(store.name, `${stores.Test1.name}!?`);83 assert.strictEqual(typeof (store.constructor), 'function');84 })85 .then(done)86 .catch(done);87 });88 it('should skip transform errors', function(done) {89 const stores = {90 Test1: {91 name: 'Test1',92 path: 'test/cases/lib/loaders/StoreLoader/Test1.js'93 }94 };95 const locator = createLocator(stores, () => {});96 locator.registerInstance('storeTransform', {97 transform: store => {98 store.name += '!';99 return store;100 }101 });102 locator.registerInstance('storeTransform', {103 transform: store => Promise.reject(new Error('Wrong!'))104 });105 locator.registerInstance('storeTransform', {106 transform: store => {107 throw new Error('Wrong!');108 }109 });110 const loader = locator.resolve('storeLoader');111 loader112 .load()113 .then(loadedStores => assert.strictEqual(loadedStores['Test1!'].name, 'Test1!'))114 .then(done)115 .catch(done);116 });117 it('should throw error if transform returns a bad result', function(done) {118 const stores = {119 Test1: {120 name: 'Test1',121 path: 'test/cases/lib/loaders/StoreLoader/Test1.js'122 }123 };124 const locator = createLocator(stores, () => done());125 locator.registerInstance('storeTransform', {126 transform: store => null127 });128 const loader = locator.resolve('storeLoader');129 loader130 .load()131 .catch(done);132 });133 it('should emit error when constructor is not a function', function(done) {134 const stores = {135 Wrong: {136 name: 'Wrong',137 path: 'test/cases/lib/loaders/StoreLoader/Wrong.js'138 }139 };140 const errorHandler = error => {141 assert.strictEqual(error instanceof Error, true);142 done();143 };144 const locator = createLocator(stores, errorHandler);145 const loader = locator.resolve('storeLoader');146 loader147 .load()148 .then(loadedStores => {149 assert.strictEqual(loadedStores, loader.getStoresByNames());150 const storeNames = Object.keys(loadedStores);151 assert.strictEqual(storeNames.length, 0);152 })153 .catch(done);154 });155 it('should emit error when wrong path', function(done) {156 const stores = {157 Wrong: {158 name: 'Wrong',159 path: 'wrong/path'160 }161 };162 const errorHandler = error => {163 assert.strictEqual(error instanceof Error, true);164 done();165 };166 const locator = createLocator(stores, errorHandler);167 const loader = locator.resolve('storeLoader');168 loader169 .load()170 .then(loadedStores => {171 assert.strictEqual(loadedStores, loader.getStoresByNames());172 const storeNames = Object.keys(loadedStores);173 assert.strictEqual(storeNames.length, 0);174 })175 .catch(done);176 });177});178function createLocator(stores, errorHandler) {179 const locator = new ServiceLocator();180 locator.registerInstance('serviceLocator', locator);181 locator.registerInstance('config', {isRelease: true});182 const eventBus = new events.EventEmitter();183 if (errorHandler) {184 eventBus.on('error', errorHandler);185 }186 locator.registerInstance('eventBus', eventBus);187 locator.registerInstance('storeFinder', new StoreFinder(stores));188 locator.register('contextFactory', ContextFactory);189 locator.register('moduleApiProvider', ModuleApiProvider);190 locator.register('cookieWrapper', CookieWrapper);191 locator.register('storeLoader', StoreLoader);192 return locator;...
CookieWrapper.js
Source:CookieWrapper.js
...5var CookieWrapper = require('../../browser/CookieWrapper');6lab.experiment('browser/CookieWrapper', function () {7 lab.experiment('#get', function () {8 lab.test('should return empty string if cookie string is null', function (done) {9 var locator = createLocator(null);10 var cookieWrapper = new CookieWrapper(locator);11 assert.strictEqual(cookieWrapper.get('some'), '');12 done();13 });14 lab.test('should return empty string if cookie key is not a string', function (done) {15 var locator = createLocator(null);16 var cookieWrapper = new CookieWrapper(locator);17 assert.strictEqual(cookieWrapper.get({}), '');18 done();19 });20 lab.test('should return value if cookie string is right', function (done) {21 var locator = createLocator('some=value; some2=value2');22 var cookieWrapper = new CookieWrapper(locator);23 assert.strictEqual(cookieWrapper.get('some'), 'value');24 assert.strictEqual(cookieWrapper.get('some2'), 'value2');25 done();26 });27 lab.test('should return empty string if cookie string is wrong', function (done) {28 var locator = createLocator('fasdfa/gafg-sgafga');29 var cookieWrapper = new CookieWrapper(locator);30 assert.strictEqual(cookieWrapper.get('fasdfa/gafg-sgafga'), '');31 done();32 });33 });34 lab.experiment('#set', function () {35 lab.test('should set cookie by specified parameters', function (done) {36 var locator = createLocator(null);37 var cookieWrapper = new CookieWrapper(locator);38 var expiration = new Date();39 var window = locator.resolve('window');40 var expected = 'some=value' +41 '; Max-Age=100' +42 '; Expires=' +43 expiration.toUTCString() +44 '; Path=/some' +45 '; Domain=.new.domain' +46 '; Secure; HttpOnly';47 cookieWrapper.set({48 key: 'some',49 value: 'value',50 maxAge: 100,51 expires: expiration,52 domain: '.new.domain',53 path: '/some',54 secure: true,55 httpOnly: true56 });57 assert.strictEqual(window.document.cookie, expected);58 done();59 });60 lab.test('should set default expire date by max age', function (done) {61 var locator = createLocator(null);62 var cookieWrapper = new CookieWrapper(locator);63 var expiration = new Date(Date.now() + 3600000);64 var window = locator.resolve('window');65 var expected = 'some=value' +66 '; Max-Age=3600' +67 '; Expires=' +68 expiration.toUTCString();69 cookieWrapper.set({70 key: 'some',71 value: 'value',72 maxAge: 360073 });74 assert.strictEqual(window.document.cookie, expected);75 done();76 });77 lab.test('should throw error if wrong key', function (done) {78 var locator = createLocator(null);79 var cookieWrapper = new CookieWrapper(locator);80 assert.throws(function () {81 cookieWrapper.set({82 key: {}83 });84 }, Error);85 done();86 });87 lab.test('should throw error if wrong value', function (done) {88 var locator = createLocator(null);89 var cookieWrapper = new CookieWrapper(locator);90 assert.throws(function () {91 cookieWrapper.set({92 key: 'some',93 value: {}94 });95 }, Error);96 done();97 });98 });99 lab.experiment('#getCookieString', function () {100 lab.test('should return right cookie string', function (done) {101 var locator = createLocator('some=value; some2=value2');102 var cookieWrapper = new CookieWrapper(locator);103 assert.strictEqual(104 cookieWrapper.getCookieString(),105 'some=value; some2=value2'106 );107 done();108 });109 });110 lab.experiment('#getAll', function () {111 lab.test('should return right cookie string', function (done) {112 var locator = createLocator('some=value; some2=value2');113 var cookieWrapper = new CookieWrapper(locator);114 assert.deepEqual(115 cookieWrapper.getAll(), {116 some: 'value',117 some2: 'value2'118 }119 );120 done();121 });122 });123});124function createLocator(cookieString) {125 var locator = new ServiceLocator();126 locator.registerInstance('window', {127 document: {128 cookie: cookieString129 }130 });131 return locator;...
StateProvider.js
Source:StateProvider.js
...11describe('lib/providers/StateProvider', function() {12 describe('#getStateByUri', function() {13 testCases.getStateByUri.forEach(testCase => {14 it(testCase.name, function() {15 const locator = createLocator(testCase.routes);16 const provider = new StateProvider(locator);17 const uri = new URI(testCase.uri);18 const state = provider.getStateByUri(uri);19 assert.deepEqual(state, testCase.expectedState);20 });21 });22 it('should get the state using regular expression', function() {23 const locator = createLocator([24 {25 expression: /^\/some\/(.+)?some$/i,26 map: uri => {27 return {28 param: uri.path29 };30 }31 }32 ]);33 const provider = new StateProvider(locator);34 const uri = new URI('http://localhost:9090/some/value?some');35 const state = provider.getStateByUri(uri);36 assert.deepEqual(state, {37 param: '/some/value'38 });39 });40 it('should throw an error in case of wrong syntax', function() {41 const locator = createLocator([42 '/:wrong[some'43 ]);44 assert.throws(() => {45 const provider = new StateProvider(locator);46 }, /Illegal/);47 });48 });49 describe('#getRouteURI', function() {50 testCases.getRouteURI.forEach(testCase => {51 it(testCase.name, function() {52 const locator = createLocator(testCase.routes);53 const provider = new StateProvider(locator);54 if (testCase.expectedError) {55 assert.throws(56 () => provider.getRouteURI(testCase.arguments.name, testCase.arguments.parameters),57 error => error.message === testCase.expectedError58 );59 } else {60 const uri = provider.getRouteURI(testCase.arguments.name, testCase.arguments.parameters);61 assert.strictEqual(uri, testCase.expectedURI);62 }63 });64 });65 });66});67function createLocator(routeDefinitions) {68 var locator = new ServiceLocator();69 locator.registerInstance('serviceLocator', locator);70 routeDefinitions.forEach(function(routeDefinition) {71 if (typeof (routeDefinition) === 'object' && typeof (routeDefinition.expression) === 'string') {72 routeDefinition.map = state => state;73 }74 locator.registerInstance('routeDefinition', routeDefinition);75 });76 return locator;...
URLArgsProvider.js
Source:URLArgsProvider.js
...9lab.experiment('lib/providers/URLArgsProvider', () => {10 lab.experiment('#getArgsByUri', () => {11 testCases.getArgsByUri.forEach((testCase) => {12 lab.test(testCase.name, (done) => {13 var locator = createLocator(testCase.routes);14 var provider = new URLArgsProvider(locator);15 var uri = new URI(testCase.uri);16 var args = provider.getArgsByUri(uri);17 assert.deepEqual(args, testCase.expectedArgs);18 done();19 });20 });21 lab.test('Should map args if method map passed', function (done) {22 var locator = createLocator([23 {24 expression: '/',25 map: function (args) {26 args.x = 1;27 return args;28 }29 }30 ]);31 var provider = new URLArgsProvider(locator);32 var uri = new URI('/');33 var args = provider.getArgsByUri(uri);34 assert.deepEqual(args, { x: 1 });35 done();36 });37 lab.test('should match regex expression', function (done) {38 var locator = createLocator([39 {40 expression: /^\/foo-\d+$/,41 map: function (args) {42 args.x = 1;43 return args;44 }45 }46 ]);47 var provider = new URLArgsProvider(locator);48 var uri = new URI('/foo-42');49 var args = provider.getArgsByUri(uri);50 assert.deepEqual(args, { x: 1 });51 done();52 });53 });54});55function createLocator(routeDefinitions) {56 var locator = new ServiceLocator();57 locator.registerInstance('serviceLocator', locator);58 routeDefinitions.forEach(function (routeDefinition) {59 locator.registerInstance('routeDefinition', routeDefinition);60 });61 return locator;...
Using AI Code Generation
1const { createLocator } = require('@playwright/test/lib/server/locator');2const { Locator } = require('@playwright/test/lib/server/locator');3const { LocatorChannel } = require('@playwright/test/lib/server/channels');4const { ElementHandleChannel } = require('@playwright/test/lib/server/channels');5const { ElementHandle } = require('@playwright/test/lib/server/dom');6const { JSHandleChannel } = require('@playwright/test/lib/server/channels');7const { JSHandle } = require('@playwright/test/lib/server/jsHandle');8const { Page } = require('@playwright/test/lib/server/page');9const { PageChannel } = require('@playwright/test/lib/server/channels');10const { createTestState } = require('@playwright/test/lib/server/test');11const { TestState } = require('@playwright/test/lib/server/test');12const { TestStateChannel } = require('@playwright/test/lib/server/channels');13const { createTestFixtures } = require('@playwright/test/lib/server/test');14const { TestFixtures } = require('@playwright/test/lib/server/test');15const { TestFixturesChannel } = require('@playwright/test/lib/server/channels');16const { createLocator } = require('@playwright/test/lib/server/locator');17const { Locator } = require('@playwright/test/lib/server/locator');18const { LocatorChannel } = require('@playwright/test/lib/server/channels');19const { ElementHandleChannel } = require('@playwright/test/lib/server/channels');20const { ElementHandle } = require('@playwright/test/lib/server/dom');21const { JSHandleChannel } = require('@playwright/test/lib/server/channels');22const { JSHandle } = require('@playwright/test/lib/server/jsHandle');23const { Page } = require('@playwright/test/lib/server/page');24const { PageChannel } = require('@playwright/test/lib/server/channels');25const { createTestState } = require('@playwright/test/lib/server/test');26const { TestState } = require('@playwright/test/lib/server/test');27const { TestStateChannel } = require('@playwright/test/lib/server/channels');28const { createTestFixtures } = require('@playwright/test/lib/server/test');29const { TestFixtures } = require('@playwright/test/lib/server/test');30const { TestFixturesChannel } = require('@playwright/test/lib/server/channels');31const {
Using AI Code Generation
1const { createLocator } = require("playwright/lib/server/locator");2const { Locator } = require("playwright/lib/server/locator");3const { ElementHandle } = require("playwright/lib/server/dom");4const { JSHandle } = require("playwright/lib/server/jsHandle");5const locator = createLocator("xpath", "xpath", "xpath", (page, selector) => {6 return page.evaluateHandle(7 (selector) => document.evaluate(selector, document, null, XPathResult.FIRST_ORDERED_NODE_TYPE, null).singleNodeValue,8 );9});10(async () => {11 const browser = await chromium.launch();12 const page = await browser.newPage();13 await page.waitForSelector("te
Using AI Code Generation
1const { createLocator } = require('playwright');2const locator = createLocator('css=div');3console.log(locator.toString());4const { createLocator } = require('playwright');5const locator = createLocator('css=div');6console.log(locator.toString());7const { createLocator } = require('playwright');8const locator = createLocator('css=div');9console.log(locator.toString());10const { createLocator } = require('playwright');11const locator = createLocator('css=div');12console.log(locator.toString());13const { createLocator } = require('playwright');14const locator = createLocator('css=div');15console.log(locator.toString());16const { createLocator } = require('playwright');17const locator = createLocator('css=div');18console.log(locator.toString());19const { createLocator } = require('playwright');20const locator = createLocator('css=div');21console.log(locator.toString());22const { createLocator } = require('playwright');23const locator = createLocator('css=div');24console.log(locator.toString());25const { createLocator } = require('playwright');26const locator = createLocator('css=div');27console.log(locator.toString());28const { createLocator } = require('playwright');29const locator = createLocator('css=div');30console.log(locator.toString());31const { createLocator } = require('playwright');32const locator = createLocator('css=div');33console.log(locator.toString());34const { createLocator } = require('playwright');35const locator = createLocator('css=div');36console.log(locator.toString());
Using AI Code Generation
1const { Locator } = require('@playwright/test');2const { createLocator } = require('@playwright/test/lib/server/locator');3const locator = createLocator('css', 'div');4const locator2 = createLocator('css', 'div', locator);5const locator3 = new Locator('css', 'div');6const locator4 = new Locator('css', 'div', locator3);7const locator5 = new Locator('css', 'div');8const locator6 = new Locator('css', 'div', locator5);9const locator7 = new Locator('css', 'div');10const locator8 = new Locator('css', 'div', locator7);11const locator9 = new Locator('css', 'div');12const locator10 = new Locator('css', 'div', locator9);13const locator11 = new Locator('css', 'div');14const locator12 = new Locator('css', 'div', locator11);15const locator13 = new Locator('css', 'div');16const locator14 = new Locator('css', 'div', locator13);17const locator15 = new Locator('css', 'div');18const locator16 = new Locator('css', 'div', locator15);19const locator17 = new Locator('css', 'div');20const locator18 = new Locator('css', 'div', locator17);21const locator19 = new Locator('css', 'div');22const locator20 = new Locator('css', 'div', locator19);23const locator21 = new Locator('css', 'div');24const locator22 = new Locator('css', 'div', locator21);25const locator23 = new Locator('css', 'div');26const locator24 = new Locator('css', 'div', locator23);
Using AI Code Generation
1const { createLocator } = require('@playwright/test');2const locator = createLocator('css=div');3const { createLocator } = require('@playwright/test');4const locator = createLocator('css=div', { timeout: 5000, visibility: 'hidden' });5const { createLocator } = require('@playwright/test');6const locator = createLocator('css=div', { timeout: 5000, visibility: 'hidden' }, (element) => element.id === 'foo');7const { createLocator } = require('@playwright/test');8const locator = createLocator('css=div', (element) => element.id === 'foo');9const { createLocator } = require('@playwright/test');10const locator = createLocator('css=div', { timeout: 5000, visibility: 'hidden' }, (element) => element.id === 'foo', (element) => element.id === 'bar');11const { createLocator } = require('@playwright/test');12const locator = createLocator('css=div', (element) => element.id === 'foo', (element) => element.id === 'bar');13const { createLocator } = require('@playwright/test');14const locator = createLocator('css=div', { timeout: 5000, visibility: 'hidden' }, (element) => element.id === 'foo');15const { createLocator } = require('@playwright/test');16const locator = createLocator('css=div', (element) => element.id === 'foo');17const { createLocator } = require('@playwright/test');18const locator = createLocator('css=div', { timeout
Using AI Code Generation
1const { Locator } = require('@playwright/test');2const locator = Locator.createLocator(browser, 'css=button');3await locator.click();4const { Locator } = require('@playwright/test');5const locator = Locator.createLocator(browser, 'css=button');6await locator.click();
Using AI Code Generation
1const { createLocator } = require('playwright/lib/protocol/locator');2const { Locator } = require('playwright/lib/locator');3const locator = new Locator();4locator._createLocator = createLocator;5locator._createLocator({ selector: 'div' });6locator._createLocator({ selector: 'div' });7 at Locator._createLocator (...\node_modules\playwright\lib\locator.js:41:48)8 at Object.<anonymous> (...\test.js:10:19)9 at Module._compile (internal/modules/cjs/loader.js:1123:30)10 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)11 at Module.load (internal/modules/cjs/loader.js:986:32)12 at Function.Module._load (internal/modules/cjs/loader.js:879:14)13 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)14const { createLocator } = require('playwright');15createLocator({ selector: 'div' });16 at Object.<anonymous> (...\test.js:6:21)17 at Module._compile (internal/modules/cjs/loader.js:1123:30)18 at Object.Module._extensions..js (internal/modules/cjs/loader.js:1158:10)19 at Module.load (internal/modules/cjs/loader.js:986:32)20 at Function.Module._load (internal/modules/cjs/loader.js:879:14)21 at Function.executeUserEntryPoint [as runMain] (internal/modules/run_main.js:71:12)
Using AI Code Generation
1const { createLocator } = require('@playwright/test');2const locator = createLocator(page, 'someLocator', async () => {3 return new Locator(page, 'someLocator', async () => {4 return await page.$('someLocator');5 });6});7locator.click();8module.exports = {9 use: {10 locator: require('./test.js'),11 },12};13const { createLocator } = require('@playwright/test');14const locator = createLocator(page, 'someLocator', async () => {15 return new Locator(page, 'someLocator', async () => {16 return await page.$('someLocator');17 });18});19locator.click();20module.exports = {21 use: {22 locator: require('./test.js'),23 },24};25const { createLocator } = require('@playwright/test');26const locator = createLocator(page, 'someLocator', async () => {27 return new Locator(page, 'someLocator', async () => {28 return await page.$('someLocator');29 });30});31locator.click();
LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!