How to use fakePlugin method in Appium Base Driver

Best JavaScript code snippet using appium-base-driver

cms.structureboard.test.js

Source:cms.structureboard.test.js Github

copy

Full Screen

1'use strict';2import StructureBoard from '../../../static/cms/js/modules/cms.structureboard';3import Plugin from '../../../static/cms/js/modules/cms.plugins';4var CMS = require('../../../static/cms/js/modules/cms.base').default;5var $ = require('jquery');6var keyboard = require('../../../static/cms/js/modules/keyboard').default;7var showLoader;8var hideLoader;9window.CMS = window.CMS || CMS;10CMS.StructureBoard = StructureBoard;11CMS.Plugin = Plugin;12CMS.API = CMS.API || {};13CMS.API.Helpers = StructureBoard.__GetDependency__('Helpers');14CMS.KEYS = StructureBoard.__GetDependency__('KEYS');15CMS.$ = $;16const pluginConstructor = jasmine.createSpy();17const originalPlugin = StructureBoard.__GetDependency__('Plugin');18class FakePlugin {19 constructor(container, opts) {20 this.options = opts;21 const el = $('<div></div>');22 el.data('cms', []);23 this.ui = {24 container: el25 };26 pluginConstructor(container, opts);27 }28}29FakePlugin._updateRegistry = jasmine.createSpy();30FakePlugin._updateClipboard = jasmine.createSpy().and.callFake(() => {31 originalPlugin._updateClipboard();32});33FakePlugin.aliasPluginDuplicatesMap = {};34FakePlugin._refreshPlugins = jasmine.createSpy().and.callFake(() => {35 originalPlugin._refreshPlugins();36});37FakePlugin.prototype._setupUI = jasmine.createSpy();38FakePlugin.prototype._ensureData = jasmine.createSpy();39FakePlugin.prototype._setGeneric = jasmine.createSpy();40FakePlugin.prototype._setPlaceholder = jasmine.createSpy();41FakePlugin.prototype._collapsables = jasmine.createSpy();42FakePlugin.prototype._setPluginContentEvents = jasmine.createSpy();43FakePlugin.prototype._setPluginStructureEvents = jasmine.createSpy();44describe('CMS.StructureBoard', function() {45 fixture.setBase('cms/tests/frontend/unit/fixtures');46 beforeEach(() => {47 CMS.API.Clipboard = {48 populate: jasmine.createSpy()49 };50 showLoader = jasmine.createSpy();51 hideLoader = jasmine.createSpy();52 StructureBoard.__Rewire__('showLoader', showLoader);53 StructureBoard.__Rewire__('hideLoader', hideLoader);54 });55 afterEach(() => {56 FakePlugin.aliasPluginDuplicatesMap = {};57 FakePlugin.prototype._setupUI.calls.reset();58 FakePlugin.prototype._ensureData.calls.reset();59 FakePlugin.prototype._setGeneric.calls.reset();60 FakePlugin.prototype._setPlaceholder.calls.reset();61 FakePlugin.prototype._collapsables.calls.reset();62 FakePlugin.prototype._setPluginContentEvents.calls.reset();63 FakePlugin.prototype._setPluginStructureEvents.calls.reset();64 FakePlugin._refreshPlugins.calls.reset();65 StructureBoard.__ResetDependency__('showLoader');66 StructureBoard.__ResetDependency__('hideLoader');67 });68 it('creates a StructureBoard class', function() {69 expect(CMS.StructureBoard).toBeDefined();70 });71 it('has public API', function() {72 expect(CMS.StructureBoard.prototype.show).toEqual(jasmine.any(Function));73 expect(CMS.StructureBoard.prototype.hide).toEqual(jasmine.any(Function));74 expect(CMS.StructureBoard.prototype.getId).toEqual(jasmine.any(Function));75 expect(CMS.StructureBoard.prototype.getIds).toEqual(jasmine.any(Function));76 });77 describe('instance', function() {78 var board;79 beforeEach(function(done) {80 fixture.load('plugins.html');81 CMS.settings = {82 mode: 'edit'83 };84 CMS.config = {85 settings: {86 mode: 'edit',87 structure: 'structure'88 },89 mode: 'edit'90 };91 $(function() {92 CMS.StructureBoard._initializeGlobalHandlers();93 jasmine.clock().install();94 board = new CMS.StructureBoard();95 done();96 });97 });98 afterEach(function() {99 jasmine.clock().uninstall();100 fixture.cleanup();101 });102 it('has ui', function() {103 expect(board.ui).toEqual(jasmine.any(Object));104 expect(Object.keys(board.ui)).toContain('container');105 expect(Object.keys(board.ui)).toContain('content');106 expect(Object.keys(board.ui)).toContain('doc');107 expect(Object.keys(board.ui)).toContain('window');108 expect(Object.keys(board.ui)).toContain('html');109 expect(Object.keys(board.ui)).toContain('toolbar');110 expect(Object.keys(board.ui)).toContain('sortables');111 expect(Object.keys(board.ui)).toContain('plugins');112 expect(Object.keys(board.ui)).toContain('render_model');113 expect(Object.keys(board.ui)).toContain('placeholders');114 expect(Object.keys(board.ui)).toContain('dragitems');115 expect(Object.keys(board.ui)).toContain('dragareas');116 expect(Object.keys(board.ui)).toContain('toolbarModeSwitcher');117 expect(Object.keys(board.ui)).toContain('toolbarModeLinks');118 expect(Object.keys(board.ui).length).toEqual(14);119 });120 it('has no options', function() {121 expect(board.options).not.toBeDefined();122 });123 it('applies correct classes to empty placeholder dragareas', function() {124 $('.cms-dragarea').removeClass('cms-dragarea-empty');125 board = new CMS.StructureBoard();126 expect('.cms-dragarea-1').not.toHaveClass('cms-dragarea-empty');127 expect('.cms-dragarea-2').toHaveClass('cms-dragarea-empty');128 expect('.cms-dragarea-10').toHaveClass('cms-dragarea-empty');129 });130 it('initially shows or hides board based on settings', function() {131 spyOn(CMS.StructureBoard.prototype, 'show');132 spyOn(CMS.StructureBoard.prototype, 'hide');133 expect(CMS.config.settings.mode).toEqual('edit');134 board = new CMS.StructureBoard();135 expect(board.show).not.toHaveBeenCalled();136 expect(board.hide).toHaveBeenCalled();137 });138 it('initially shows or hides board based on settings 2', function() {139 spyOn(CMS.StructureBoard.prototype, 'show');140 spyOn(CMS.StructureBoard.prototype, 'hide');141 CMS.config.settings.mode = 'structure';142 board = new CMS.StructureBoard();143 expect(board.show).toHaveBeenCalled();144 expect(board.hide).not.toHaveBeenCalled();145 });146 it('does not show or hide structureboard if there are no dragareas', function() {147 board.ui.dragareas.remove();148 board = new CMS.StructureBoard();149 spyOn(board, 'show');150 spyOn(board, 'hide');151 expect(board.show).not.toHaveBeenCalled();152 expect(board.hide).not.toHaveBeenCalled();153 jasmine.clock().tick(200);154 expect(board.show).not.toHaveBeenCalled();155 expect(board.hide).not.toHaveBeenCalled();156 });157 it('does not show or hide structureboard if there is no board mode switcher', function() {158 board.ui.toolbarModeSwitcher.remove();159 board = new CMS.StructureBoard();160 spyOn(board, 'show');161 spyOn(board, 'hide');162 expect(board.show).not.toHaveBeenCalled();163 expect(board.hide).not.toHaveBeenCalled();164 jasmine.clock().tick(200);165 expect(board.show).not.toHaveBeenCalled();166 expect(board.hide).not.toHaveBeenCalled();167 });168 it('enables board mode switcher if there are placeholders', function() {169 expect(board.ui.placeholders.length > 0).toEqual(true);170 board.ui.toolbarModeSwitcher.find('.cms-btn').addClass('cms-btn-disabled');171 new CMS.StructureBoard();172 jasmine.clock().tick(100);173 expect(board.ui.toolbarModeSwitcher.find('.cms-btn')).not.toHaveClass('cms-btn-disabled');174 });175 it('does not enable board mode switcher if there are no placeholders', function() {176 expect(board.ui.placeholders.length > 0).toEqual(true);177 expect(board.ui.dragareas.length > 0).toEqual(true);178 board.ui.placeholders.remove();179 board.ui.dragareas.remove();180 board.ui.toolbarModeSwitcher.find('.cms-btn').addClass('cms-btn-disabled');181 board = new CMS.StructureBoard();182 expect(board.ui.placeholders.length).toEqual(0);183 expect(board.ui.dragareas.length).toEqual(0);184 jasmine.clock().tick(100);185 expect(board.ui.toolbarModeSwitcher.find('.cms-btn')).toHaveClass('cms-btn-disabled');186 });187 it('sets loaded content and structure flags if it is a legacy renderer', () => {188 CMS.config.settings.legacy_mode = true;189 board = new CMS.StructureBoard();190 expect(board._loadedStructure).toEqual(true);191 expect(board._loadedContent).toEqual(true);192 });193 });194 describe('.show()', function() {195 var board;196 beforeEach(function(done) {197 fixture.load('plugins.html');198 CMS.settings = {199 mode: 'edit'200 };201 CMS.API.Toolbar = {202 _refreshMarkup: jasmine.createSpy()203 };204 CMS.config = {205 settings: {206 mode: 'edit',207 structure: 'structure'208 },209 mode: 'edit'210 };211 $(function() {212 spyOn(CMS.API.Helpers, 'setSettings').and.callFake(function(input) {213 return input;214 });215 CMS.StructureBoard._initializeGlobalHandlers();216 board = new CMS.StructureBoard();217 spyOn(board, '_loadStructure').and.returnValue(Promise.resolve());218 done();219 });220 });221 afterEach(function() {222 fixture.cleanup();223 });224 it('shows the board', function(done) {225 spyOn(board, '_showBoard').and.callThrough();226 expect(board.ui.container).not.toBeVisible();227 board.show().then(function() {228 expect(board.ui.container).toBeVisible();229 expect(board._showBoard).toHaveBeenCalled();230 done();231 });232 });233 it('does not show the board if we are viewing published page', function(done) {234 CMS.config.mode = 'live';235 spyOn(board, '_showBoard').and.callThrough();236 expect(board.ui.container).not.toBeVisible();237 board.show().then(r => {238 expect(r).toEqual(false);239 expect(board.ui.container).not.toBeVisible();240 expect(board._showBoard).not.toHaveBeenCalled();241 done();242 });243 });244 it('highlights correct trigger', function(done) {245 expect(board.ui.toolbarModeLinks).not.toHaveClass('cms-btn-active');246 board.show().then(() => {247 expect(board.ui.toolbarModeLinks).toHaveClass('cms-btn-active');248 done();249 });250 });251 it('adds correct classes to the root of the document', function(done) {252 board.ui.html.removeClass('cms-structure-mode-structure');253 expect(board.ui.html).not.toHaveClass('cms-structure-mode-structure');254 board.show().then(() => {255 expect(board.ui.html).toHaveClass('cms-structure-mode-structure');256 done();257 });258 });259 it('does set state through settings', function(done) {260 CMS.API.Helpers.setSettings.and.callFake(function(input) {261 return input;262 });263 expect(CMS.settings.mode).toEqual('edit');264 board.show().then(() => {265 expect(CMS.settings.mode).toEqual('structure');266 expect(CMS.API.Helpers.setSettings).toHaveBeenCalled();267 done();268 });269 });270 it('saves the state in the url');271 });272 describe('highlights', function() {273 var board;274 beforeEach(function(done) {275 fixture.load('plugins.html', 'clipboard.html');276 CMS.settings = {277 mode: 'edit'278 };279 CMS.config = {280 settings: {281 mode: 'edit',282 structure: 'structure'283 },284 mode: 'edit'285 };286 $(function() {287 spyOn(CMS.API.Helpers, 'setSettings').and.callFake(function(input) {288 return input;289 });290 CMS.API.Tooltip = {291 domElem: {292 is: function() {293 return true;294 },295 data: function() {296 return 1;297 }298 }299 };300 CMS.StructureBoard._initializeGlobalHandlers();301 board = new CMS.StructureBoard();302 spyOn(board, 'show').and.returnValue(Promise.resolve());303 spyOn(board, 'hide').and.returnValue(Promise.resolve());304 spyOn(Plugin, '_highlightPluginStructure');305 spyOn(Plugin, '_highlightPluginContent');306 done();307 });308 });309 afterEach(function() {310 fixture.cleanup();311 });312 describe('._showAndHighlightPlugin()', function() {313 it('returns false if tooltip does not exist', function(done) {314 CMS.API.Tooltip = false;315 board._showAndHighlightPlugin().then(r => {316 expect(r).toEqual(false);317 expect(board.show).not.toHaveBeenCalled();318 done();319 });320 });321 it('returns false if in live mode', function(done) {322 CMS.config.mode = 'live';323 board._showAndHighlightPlugin().then(r => {324 expect(r).toEqual(false);325 expect(board.show).not.toHaveBeenCalled();326 done();327 });328 });329 it('returns false if no plugin is hovered', function(done) {330 CMS.API.Tooltip.domElem.is = function() {331 return false;332 };333 board._showAndHighlightPlugin().then(r => {334 expect(r).toEqual(false);335 expect(board.show).not.toHaveBeenCalled();336 done();337 });338 });339 it('shows board if plugin is hovered', function(done) {340 jasmine.clock().install();341 board._showAndHighlightPlugin().then(() => {342 expect(board.show).toHaveBeenCalledTimes(1);343 expect(Plugin._highlightPluginStructure).not.toHaveBeenCalled();344 jasmine.clock().tick(201);345 expect(Plugin._highlightPluginStructure).toHaveBeenCalledTimes(1);346 jasmine.clock().uninstall();347 done();348 });349 });350 });351 });352 describe('.hide()', function() {353 var board;354 beforeEach(function(done) {355 fixture.load('plugins.html');356 $(function() {357 CMS.settings = {358 mode: 'edit'359 };360 CMS.config = {361 settings: {362 mode: 'edit',363 structure: 'structure'364 },365 mode: 'edit'366 };367 spyOn(CMS.API.Helpers, 'setSettings').and.callFake(function(input) {368 return input;369 });370 CMS.StructureBoard._initializeGlobalHandlers();371 board = new CMS.StructureBoard();372 spyOn(board, '_loadContent').and.returnValue(Promise.resolve());373 spyOn(board, '_loadStructure').and.returnValue(Promise.resolve());374 done();375 });376 });377 afterEach(function() {378 fixture.cleanup();379 });380 it('hides the board', function(done) {381 spyOn(board, '_hideBoard').and.callThrough();382 board383 .show()384 .then(() => {385 expect(board.ui.container).toBeVisible();386 return board.hide();387 })388 .then(() => {389 expect(board.ui.container).not.toBeVisible();390 expect(board._hideBoard).toHaveBeenCalled();391 done();392 });393 });394 it('does not hide the board if we are viewing published page', function() {395 CMS.config.mode = 'live';396 spyOn(board, '_hideBoard');397 expect(board.ui.container).not.toBeVisible();398 expect(board.hide()).toEqual(false);399 expect(board.ui.container).not.toBeVisible();400 expect(board._hideBoard).not.toHaveBeenCalled();401 });402 it('deactivates the button', function(done) {403 board.hide().then(() => {404 expect(board.ui.toolbarModeLinks).not.toHaveClass('cms-btn-active');405 done();406 });407 });408 it('does not remember the state in localstorage', function() {409 board.show();410 expect(CMS.settings.mode).toEqual('structure');411 CMS.API.Helpers.setSettings.and.callFake(function(input) {412 return input;413 });414 CMS.API.Helpers.setSettings.calls.reset();415 board.hide();416 expect(CMS.settings.mode).toEqual('edit');417 expect(CMS.API.Helpers.setSettings).not.toHaveBeenCalled();418 });419 it('remembers the state in the url');420 it('triggers `resize` event on the window', function(done) {421 var spy = jasmine.createSpy();422 board423 .show()424 .then(() => {425 $(window).on('resize', spy);426 return board.hide();427 })428 .then(() => {429 expect(spy).toHaveBeenCalledTimes(1);430 $(window).off('resize', spy);431 done();432 });433 });434 });435 describe('.getId()', function() {436 var board;437 beforeEach(function(done) {438 fixture.load('plugins.html');439 CMS.settings = {440 mode: 'edit'441 };442 CMS.config = {443 settings: {444 mode: 'edit',445 structure: 'structure'446 },447 mode: 'edit'448 };449 $(function() {450 CMS.StructureBoard._initializeGlobalHandlers();451 board = new CMS.StructureBoard();452 done();453 });454 });455 afterEach(function() {456 fixture.cleanup();457 });458 it('returns the id of passed element', function() {459 [460 {461 from: 'cms-plugin cms-plugin-1',462 result: '1'463 },464 {465 from: 'cms-plugin cms-plugin-125',466 result: '125'467 },468 {469 from: 'cms-draggable cms-draggable-1',470 result: '1'471 },472 {473 from: 'cms-draggable cms-draggable-125',474 result: '125'475 },476 {477 from: 'cms-placeholder cms-placeholder-1',478 result: '1'479 },480 {481 from: 'cms-placeholder cms-placeholder-125',482 result: '125'483 },484 {485 from: 'cms-dragbar cms-dragbar-1',486 result: '1'487 },488 {489 from: 'cms-dragbar cms-dragbar-125',490 result: '125'491 },492 {493 from: 'cms-dragarea cms-dragarea-1',494 result: '1'495 },496 {497 from: 'cms-dragarea cms-dragarea-125',498 result: '125'499 }500 ].forEach(function(obj) {501 expect(board.getId($('<div class="' + obj.from + '"></div>'))).toEqual(obj.result);502 });503 });504 it('returns null if element is of non supported "type"', function() {505 [506 {507 from: 'cannot determine',508 result: null509 },510 {511 from: 'cms-not-supported cms-not-supported-1',512 result: null513 }514 ].forEach(function(obj) {515 expect(board.getId($('<div class="' + obj.from + '"></div>'))).toEqual(obj.result);516 });517 });518 it('returns false if element does not exist', function() {519 expect(board.getId()).toEqual(false);520 expect(board.getId(null)).toEqual(false);521 expect(board.getId($('.non-existent'))).toEqual(false);522 expect(board.getId([])).toEqual(false);523 });524 it('fails if classname string is incorrect', function() {525 expect(board.getId.bind(board, $('<div class="cms-plugin"></div>'))).toThrow();526 expect(board.getId($('<div class="cms-plugin fail cms-plugin-10"></div>'))).toEqual('fail');527 });528 });529 describe('.getIds()', function() {530 var board;531 beforeEach(function(done) {532 fixture.load('plugins.html');533 CMS.settings = {534 mode: 'edit'535 };536 CMS.config = {537 settings: {538 mode: 'edit',539 structure: 'structure'540 },541 mode: 'edit'542 };543 $(function() {544 CMS.StructureBoard._initializeGlobalHandlers();545 board = new CMS.StructureBoard();546 done();547 });548 });549 afterEach(function() {550 fixture.cleanup();551 });552 it('returns the array of ids of passed collection', function() {553 spyOn(board, 'getId').and.callThrough();554 [555 {556 from: ['cms-plugin cms-plugin-1'],557 result: ['1']558 },559 {560 from: ['cms-plugin cms-plugin-125', 'cms-plugin cms-plugin-1'],561 result: ['125', '1']562 },563 {564 from: ['cms-plugin cms-plugin-125', 'cms-plugin cms-plugin-1', 'cms-draggable cms-draggable-12'],565 result: ['125', '1', '12']566 },567 {568 from: ['non-existent', 'cms-plugin cms-plugin-1'],569 result: [null, '1']570 }571 ].forEach(function(obj) {572 var collection = $();573 obj.from.forEach(function(className) {574 collection = collection.add($('<div class="' + className + '"></div>'));575 });576 expect(board.getIds(collection)).toEqual(obj.result);577 });578 expect(board.getId).toHaveBeenCalled();579 });580 });581 describe('._setupModeSwitcher()', function() {582 var board;583 beforeEach(function(done) {584 fixture.load('plugins.html');585 CMS.settings = {586 mode: 'edit'587 };588 CMS.config = {589 settings: {590 mode: 'edit',591 structure: 'structure'592 },593 mode: 'edit'594 };595 $(function() {596 spyOn(keyboard, 'bind');597 CMS.StructureBoard._initializeGlobalHandlers();598 board = new CMS.StructureBoard();599 spyOn(board, 'show').and.callFake(function() {600 CMS.settings.mode = 'structure';601 });602 spyOn(board, 'hide').and.callFake(function() {603 CMS.settings.mode = 'edit';604 });605 done();606 });607 });608 afterEach(function() {609 board.ui.doc.off('keydown.cms.structureboard.switcher');610 fixture.cleanup();611 });612 it('sets up click handler to show board', function() {613 var showTrigger = board.ui.toolbarModeLinks;614 expect(showTrigger).toHandle(board.click);615 CMS.settings.mode = 'structure';616 showTrigger.trigger(board.click);617 expect(board.show).not.toHaveBeenCalled();618 CMS.settings.mode = 'edit';619 showTrigger.trigger(board.click);620 expect(board.show).toHaveBeenCalledTimes(1);621 });622 it('sets up click handler to hide board', function() {623 var hideTrigger = board.ui.toolbarModeLinks;624 expect(hideTrigger).toHandle(board.click);625 CMS.settings.mode = 'edit';626 hideTrigger.trigger(board.click);627 expect(board.hide).not.toHaveBeenCalled();628 CMS.settings.mode = 'structure';629 hideTrigger.trigger(board.click);630 expect(board.hide).toHaveBeenCalledTimes(1);631 });632 it('sets up shortcuts to toggle board', function() {633 spyOn(board, '_toggleStructureBoard');634 var preventDefaultSpySpace = jasmine.createSpy();635 var preventDefaultSpyShiftSpace = jasmine.createSpy();636 expect(keyboard.bind).toHaveBeenCalledTimes(2);637 expect(keyboard.bind).toHaveBeenCalledWith('space', jasmine.any(Function));638 expect(keyboard.bind).toHaveBeenCalledWith('shift+space', jasmine.any(Function));639 var calls = keyboard.bind.calls.all();640 calls[0].args[1]({ preventDefault: preventDefaultSpySpace });641 expect(board._toggleStructureBoard).toHaveBeenCalledTimes(1);642 expect(board._toggleStructureBoard).toHaveBeenCalledWith();643 expect(preventDefaultSpySpace).toHaveBeenCalledTimes(1);644 expect(preventDefaultSpyShiftSpace).not.toHaveBeenCalled();645 calls[1].args[1]({ preventDefault: preventDefaultSpyShiftSpace });646 expect(board._toggleStructureBoard).toHaveBeenCalledTimes(2);647 expect(board._toggleStructureBoard).toHaveBeenCalledWith({648 useHoveredPlugin: true649 });650 expect(preventDefaultSpySpace).toHaveBeenCalledTimes(1);651 expect(preventDefaultSpyShiftSpace).toHaveBeenCalledTimes(1);652 });653 it('does not setup key binds if toggler is not availabe', function() {654 keyboard.bind.calls.reset();655 board.ui.toolbarModeSwitcher.remove();656 CMS.StructureBoard._initializeGlobalHandlers();657 board = new CMS.StructureBoard();658 spyOn(board, 'show').and.callFake(function() {659 CMS.settings.mode = 'structure';660 });661 spyOn(board, 'hide').and.callFake(function() {662 CMS.settings.mode = 'edit';663 });664 expect(keyboard.bind).not.toHaveBeenCalled();665 });666 it('does not setup key binds if toggler is not visible (there are no placeholders)', function() {667 keyboard.bind.calls.reset();668 board.ui.placeholders.remove();669 board.ui.dragareas.remove();670 board.ui.toolbarModeSwitcher.find('.cms-btn').addClass('cms-btn-disabled');671 CMS.StructureBoard._initializeGlobalHandlers();672 board = new CMS.StructureBoard();673 spyOn(board, 'show').and.callFake(function() {674 CMS.settings.mode = 'structure';675 });676 spyOn(board, 'hide').and.callFake(function() {677 CMS.settings.mode = 'edit';678 });679 expect(keyboard.bind).not.toHaveBeenCalled();680 });681 });682 describe('._toggleStructureBoard()', function() {683 var board;684 beforeEach(function(done) {685 fixture.load('plugins.html');686 CMS.settings = {687 mode: 'edit'688 };689 CMS.config = {690 settings: {691 mode: 'edit',692 structure: 'structure'693 },694 mode: 'edit'695 };696 $(function() {697 spyOn(keyboard, 'bind');698 CMS.StructureBoard._initializeGlobalHandlers();699 board = new CMS.StructureBoard();700 spyOn(board, 'show').and.callFake(function() {701 CMS.settings.mode = 'structure';702 });703 spyOn(board, 'hide').and.callFake(function() {704 CMS.settings.mode = 'edit';705 });706 spyOn(board, '_showAndHighlightPlugin').and.returnValue({707 then() {}708 });709 done();710 });711 });712 it('shows structureboard', function() {713 board._toggleStructureBoard();714 expect(board.show).toHaveBeenCalledTimes(1);715 expect(board.hide).not.toHaveBeenCalled();716 });717 it('hides strucrueboard', function() {718 CMS.settings.mode = 'structure';719 board._toggleStructureBoard();720 expect(board.show).not.toHaveBeenCalled();721 expect(board.hide).toHaveBeenCalledTimes(1);722 });723 it('shows structureboard and highlights plugin', function() {724 CMS.settings.mode = 'edit';725 board._toggleStructureBoard({ useHoveredPlugin: true });726 expect(board._showAndHighlightPlugin).toHaveBeenCalledTimes(1);727 });728 it('does not show structureboard and highlights plugin if it is open already', function() {729 CMS.settings.mode = 'structure';730 board._toggleStructureBoard({ useHoveredPlugin: true });731 expect(board._showAndHighlightPlugin).not.toHaveBeenCalled();732 });733 });734 describe('._drag()', function() {735 var board;736 var options;737 beforeEach(function(done) {738 fixture.load('plugins.html');739 CMS.settings = {740 mode: 'structure'741 };742 CMS.config = {743 settings: {744 mode: 'structure',745 structure: 'structure'746 },747 mode: 'structure'748 };749 $(function() {750 CMS.StructureBoard._initializeGlobalHandlers();751 board = new CMS.StructureBoard();752 board._drag();753 options = board.ui.sortables.nestedSortable('option');754 board.show().then(() => {755 done();756 });757 });758 });759 afterEach(function() {760 board.ui.doc.off('keyup.cms.interrupt');761 fixture.cleanup();762 });763 it('initializes nested sortable', function() {764 options = board.ui.sortables.nestedSortable('option');765 expect(options).toEqual(766 jasmine.objectContaining({767 items: '> .cms-draggable:not(.cms-draggable-disabled .cms-draggable)',768 placeholder: 'cms-droppable',769 connectWith: '.cms-draggables:not(.cms-hidden)',770 appendTo: '.cms-structure-content',771 listType: 'div.cms-draggables',772 doNotClear: true,773 toleranceElement: '> div',774 disableNestingClass: 'cms-draggable-disabled',775 errorClass: 'cms-draggable-disallowed',776 start: jasmine.any(Function),777 helper: jasmine.any(Function),778 beforeStop: jasmine.any(Function),779 update: jasmine.any(Function),780 isAllowed: jasmine.any(Function)781 })782 );783 });784 it('adds event handler for cms-structure-update to actualize empty placeholders', function() {785 if (!CMS.$._data(board.ui.sortables[0]).events['cms-structure-update'][0].handler.name) {786 pending();787 }788 expect(board.ui.sortables).toHandle('cms-structure-update');789 // cheating here a bit790 expect(CMS.$._data(board.ui.sortables[0]).events['cms-structure-update'][0].handler.name).toEqual(791 'actualizePlaceholders'792 );793 });794 it('defines how draggable helper is created', function() {795 options = board.ui.sortables.nestedSortable('option');796 var helper = options.helper;797 var item = $(798 '<div class="some class string">' +799 '<div class="cms-dragitem">Only this will be cloned</div>' +800 '<div class="cms-draggables">' +801 '<div class="cms-dragitem">This will not</div>' +802 '</div>' +803 '</div>'804 );805 var result = helper(null, item);806 expect(result).toHaveClass('some');807 expect(result).toHaveClass('class');808 expect(result).toHaveClass('string');809 expect(result).toHaveText('Only this will be cloned');810 expect(result).not.toHaveText('This will not');811 });812 describe('start', function() {813 it('sets data-touch-action attribute', function() {814 expect(board.ui.content).toHaveAttr('data-touch-action', 'pan-y');815 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });816 expect(board.ui.content).toHaveAttr('data-touch-action', 'none');817 });818 it('sets dragging state', function() {819 expect(board.dragging).toEqual(false);820 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });821 expect(board.dragging).toEqual(true);822 });823 it('actualizes empty placeholders', function() {824 var firstPlaceholder = board.ui.dragareas.eq(0);825 var firstPlaceholderCopyAll = firstPlaceholder.find(826 '.cms-dragbar .cms-submenu-item:has(a[data-rel="copy"]):first'827 );828 var secondPlaceholder = board.ui.dragareas.eq(1);829 var secondPlaceholderCopyAll = secondPlaceholder.find(830 '.cms-dragbar .cms-submenu-item:has(a[data-rel="copy"]):first'831 );832 expect(firstPlaceholder).toHaveClass('cms-dragarea-empty');833 expect(firstPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');834 expect(secondPlaceholder).not.toHaveClass('cms-dragarea-empty');835 expect(secondPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');836 secondPlaceholder837 .find('> .cms-draggables')838 .contents()839 .appendTo(firstPlaceholder.find('> .cms-draggables'));840 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });841 expect(firstPlaceholder).not.toHaveClass('cms-dragarea-empty');842 expect(firstPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');843 expect(secondPlaceholder).toHaveClass('cms-dragarea-empty');844 expect(secondPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');845 // now check that the plugin currently being dragged does not count846 // towards "plugins count"847 firstPlaceholder848 .find('> .cms-draggables')849 .contents()850 .appendTo(secondPlaceholder.find('> .cms-draggables'));851 firstPlaceholder852 .find('> .cms-draggables')853 .append($('<div class="cms-draggable cms-draggable-is-dragging"></div>'));854 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });855 expect(firstPlaceholder).toHaveClass('cms-dragarea-empty');856 expect(firstPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');857 expect(secondPlaceholder).not.toHaveClass('cms-dragarea-empty');858 expect(secondPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');859 });860 it('hides settings menu', function() {861 spyOn(CMS.Plugin, '_hideSettingsMenu');862 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });863 expect(CMS.Plugin._hideSettingsMenu).toHaveBeenCalledTimes(1);864 });865 it('shows all the empty sortables', function() {866 expect($('.cms-draggables.cms-hidden').length).toEqual(1);867 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });868 expect($('.cms-draggables.cms-hidden').length).toEqual(0);869 });870 it('adds appropriate classes on item without children and helper', function() {871 var item = $('<div class="cms-draggable"><div class="cms-dragitem">Some plugin</div></div>');872 var helper = options.helper(null, item);873 options.start(874 {},875 {876 item: item,877 helper: helper878 }879 );880 expect(item).toHaveClass('cms-is-dragging');881 expect(helper).toHaveClass('cms-draggable-is-dragging');882 });883 it('adds appropriate classes on item with children', function() {884 var item = $(885 '<div class="cms-draggable">' +886 '<div class="cms-dragitem">Some plugin</div>' +887 '<div class="cms-draggables">' +888 '<div></div>' +889 '</div>' +890 '</div>'891 );892 var helper = options.helper(null, item);893 options.start(894 {},895 {896 item: item,897 helper: helper898 }899 );900 expect(helper).toHaveClass('cms-draggable-stack');901 });902 it('sets up a handler for interrupting dragging with keyboard', function() {903 expect(board.ui.doc).not.toHandle('keyup.cms.interrupt');904 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });905 expect(board.ui.doc).toHandle('keyup.cms.interrupt');906 var spy = jasmine.createSpy();907 board.ui.sortables.on('mouseup', spy);908 spyOn($.ui.sortable.prototype, '_mouseStop');909 var wrongEvent = new $.Event('keyup.cms.interrupt', { keyCode: 1287926834 });910 var correctEvent = new $.Event('keyup.cms.interrupt', { keyCode: CMS.KEYS.ESC });911 board.state = 'mock';912 board.ui.doc.trigger(wrongEvent);913 expect(board.state).toEqual('mock');914 expect($.ui.sortable.prototype._mouseStop).not.toHaveBeenCalled();915 expect(spy).not.toHaveBeenCalled();916 board.state = 'mock';917 board.ui.doc.trigger(wrongEvent, [true]);918 expect(board.state).toEqual(false);919 expect($.ui.sortable.prototype._mouseStop).toHaveBeenCalledTimes(1);920 expect(spy).toHaveBeenCalledTimes(1 + board.ui.sortables.length);921 board.ui.doc.off('keyup.cms.interrupt');922 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });923 board.state = 'mock';924 board.ui.doc.trigger(correctEvent);925 expect(board.state).toEqual(false);926 expect($.ui.sortable.prototype._mouseStop).toHaveBeenCalledTimes(2);927 expect(spy).toHaveBeenCalledTimes((1 + board.ui.sortables.length) * 2);928 });929 });930 describe('beforeStop', function() {931 it('sets dragging state to false', function() {932 board.dragging = true;933 options.beforeStop(null, { item: $('<div></div>') });934 expect(board.dragging).toEqual(false);935 });936 it('removes classes', function() {937 var item = $('<div class="cms-is-dragging cms-draggable-stack"></div>');938 options.beforeStop(null, { item: item });939 expect(item).not.toHaveClass('cms-is-dragging');940 expect(item).not.toHaveClass('cms-draggable-stack');941 });942 it('unbinds interrupt event', function() {943 var spy = jasmine.createSpy();944 board.ui.doc.on('keyup.cms.interrupt', spy);945 options.beforeStop(null, { item: $('<div></div>') });946 board.ui.doc.trigger('keyup.cms.interrupt');947 expect(spy).not.toHaveBeenCalled();948 expect(board.ui.doc).not.toHandle('keyup.cms.interrupt');949 });950 it('resets data-touch-action attribute', function() {951 board.ui.content.removeAttr('data-touch-action');952 options.beforeStop(null, { item: $('<div></div>') });953 expect(board.ui.content).toHaveAttr('data-touch-action', 'pan-y');954 });955 });956 describe('update', function() {957 it('returns false if it is not possible to update', function() {958 board.state = false;959 expect(options.update()).toEqual(false);960 });961 it('actualizes collapsible status', function() {962 var textPlugin = $('.cms-draggable-1');963 var randomPlugin = $('.cms-draggable-2');964 var helper = options.helper(null, textPlugin);965 // we need to start first to set a private variable original container966 options.start(null, { item: textPlugin, helper: helper });967 board.state = true;968 expect(randomPlugin.find('> .cms-dragitem')).not.toHaveClass('cms-dragitem-collapsable');969 expect(randomPlugin.find('> .cms-dragitem')).not.toHaveClass('cms-dragitem-expanded');970 textPlugin.appendTo(randomPlugin.find('.cms-draggables'));971 options.update(null, { item: textPlugin, helper: helper });972 expect(randomPlugin.find('> .cms-dragitem')).toHaveClass('cms-dragitem-collapsable');973 expect(randomPlugin.find('> .cms-dragitem')).toHaveClass('cms-dragitem-expanded');974 // and back975 options.start(null, { item: textPlugin, helper: helper });976 board.state = true;977 textPlugin.appendTo($('.cms-dragarea-1').find('> .cms-draggables'));978 options.update(null, { item: textPlugin, helper: helper });979 expect(randomPlugin.find('> .cms-dragitem')).not.toHaveClass('cms-dragitem-collapsable');980 expect(randomPlugin.find('> .cms-dragitem')).toHaveClass('cms-dragitem-expanded');981 });982 it('returns false if we moved plugin inside same container and the event is fired on the container', () => {983 var textPlugin = $('.cms-draggable-1');984 var helper = options.helper(null, textPlugin);985 var placeholderDraggables = $('.cms-dragarea-1').find('> .cms-draggables');986 // and one more time987 options.start(null, { item: textPlugin, helper: helper });988 board.state = true;989 textPlugin.prependTo(placeholderDraggables);990 expect(options.update.bind(textPlugin)(null, { item: textPlugin, helper: helper })).toEqual(false);991 });992 it('triggers event on the plugin when necessary', function() {993 var textPlugin = $('.cms-draggable-1');994 var randomPlugin = $('.cms-draggable-2');995 var helper = options.helper(null, textPlugin);996 var placeholderDraggables = $('.cms-dragarea-1').find('> .cms-draggables');997 var spy = jasmine.createSpy();998 textPlugin.on('cms-plugins-update', spy);999 // we need to start first to set a private variable original container1000 options.start(null, { item: textPlugin, helper: helper });1001 board.state = true;1002 textPlugin.appendTo(randomPlugin.find('.cms-draggables'));1003 options.update(null, { item: textPlugin, helper: helper });1004 expect(spy).toHaveBeenCalledTimes(1);1005 // and back1006 options.start(null, { item: textPlugin, helper: helper });1007 board.state = true;1008 textPlugin.appendTo($('.cms-dragarea-1').find('> .cms-draggables'));1009 options.update(null, { item: textPlugin, helper: helper });1010 expect(spy).toHaveBeenCalledTimes(2);1011 // and one more time1012 options.start(null, { item: textPlugin, helper: helper });1013 board.state = true;1014 textPlugin.prependTo(placeholderDraggables);1015 options.update.bind(placeholderDraggables)(null, { item: textPlugin, helper: helper });1016 expect(spy).toHaveBeenCalledTimes(3);1017 });1018 it('triggers event on the plugin in clipboard', function() {1019 $(fixture.el).prepend(1020 '<div class="cms-clipboard">' +1021 '<div class="cms-clipboard-containers cms-draggables"></div>' +1022 '</div>'1023 );1024 var textPlugin = $('.cms-draggable-1');1025 var randomPlugin = $('.cms-draggable-2');1026 var helper = options.helper(null, textPlugin);1027 textPlugin.prependTo('.cms-clipboard-containers');1028 var pluginSpy = jasmine.createSpy();1029 var clipboardSpy = jasmine.createSpy();1030 textPlugin.on('cms-plugins-update', pluginSpy);1031 textPlugin.on('cms-paste-plugin-update', clipboardSpy);1032 // we need to start first to set a private variable original container1033 options.start(null, { item: textPlugin, helper: helper });1034 board.state = true;1035 textPlugin.appendTo(randomPlugin.find('.cms-draggables'));1036 options.update(null, { item: textPlugin, helper: helper });1037 expect(pluginSpy).not.toHaveBeenCalled();1038 expect(clipboardSpy).toHaveBeenCalledTimes(1);1039 });1040 it('actualizes empty placeholders', function() {1041 var firstPlaceholder = board.ui.dragareas.eq(0);1042 var firstPlaceholderCopyAll = firstPlaceholder.find(1043 '.cms-dragbar .cms-submenu-item:has(a[data-rel="copy"]):first'1044 );1045 var secondPlaceholder = board.ui.dragareas.eq(1);1046 var secondPlaceholderCopyAll = secondPlaceholder.find(1047 '.cms-dragbar .cms-submenu-item:has(a[data-rel="copy"]):first'1048 );1049 expect(firstPlaceholder).toHaveClass('cms-dragarea-empty');1050 expect(firstPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');1051 expect(secondPlaceholder).not.toHaveClass('cms-dragarea-empty');1052 expect(secondPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');1053 options.start({}, { item: $('<div></div>'), helper: $('<div></div>') });1054 secondPlaceholder1055 .find('> .cms-draggables')1056 .contents()1057 .appendTo(firstPlaceholder.find('> .cms-draggables'));1058 board.state = true;1059 options.update({}, { item: $('<div class="cms-plugin-1"></div>'), helper: $('<div></div>') });1060 expect(firstPlaceholder).not.toHaveClass('cms-dragarea-empty');1061 expect(firstPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');1062 expect(secondPlaceholder).toHaveClass('cms-dragarea-empty');1063 expect(secondPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');1064 // now check that the plugin currently being dragged does not count1065 // towards "plugins count"1066 firstPlaceholder1067 .find('> .cms-draggables')1068 .contents()1069 .appendTo(secondPlaceholder.find('> .cms-draggables'));1070 firstPlaceholder1071 .find('> .cms-draggables')1072 .append($('<div class="cms-draggable cms-draggable-is-dragging"></div>'));1073 options.update({}, { item: $('<div class="cms-plugin-1"></div>'), helper: $('<div></div>') });1074 expect(firstPlaceholder).toHaveClass('cms-dragarea-empty');1075 expect(firstPlaceholderCopyAll).toHaveClass('cms-submenu-item-disabled');1076 expect(secondPlaceholder).not.toHaveClass('cms-dragarea-empty');1077 expect(secondPlaceholderCopyAll).not.toHaveClass('cms-submenu-item-disabled');1078 });1079 it('hides empty sortables', function() {1080 var textPlugin = $('.cms-draggable-1');1081 var randomPlugin = $('.cms-draggable-2');1082 var helper = options.helper(null, textPlugin);1083 options.start(null, { item: textPlugin, helper: helper });1084 board.state = true;1085 expect($('.cms-draggables.cms-hidden').length).toEqual(0);1086 textPlugin.appendTo(randomPlugin.find('.cms-draggables'));1087 options.update(null, { item: textPlugin, helper: helper });1088 expect($('.cms-draggables.cms-hidden').length).toEqual(0);1089 options.start(null, { item: textPlugin, helper: helper });1090 board.state = true;1091 expect($('.cms-draggables.cms-hidden').length).toEqual(0);1092 textPlugin.appendTo($('.cms-dragarea-1').find('> .cms-draggables'));1093 options.update(null, { item: textPlugin, helper: helper });1094 expect($('.cms-draggables.cms-hidden').length).toEqual(1);1095 });1096 });1097 describe('isAllowed', function() {1098 it('returns false if CMS.API is locked', function() {1099 CMS.API.locked = true;1100 board.state = 'mock';1101 expect(options.isAllowed()).toEqual(false);1102 expect(board.state).toEqual('mock');1103 });1104 it('returns false if there is no item', function() {1105 CMS.API.locked = false;1106 board.state = 'mock';1107 expect(options.isAllowed()).toEqual(false);1108 expect(board.state).toEqual('mock');1109 });1110 it('returns false if item has no settings', function() {1111 board.state = 'mock';1112 expect(options.isAllowed(null, null, $('.cms-draggable-1'))).toEqual(false);1113 expect(board.state).toEqual('mock');1114 });1115 it('returns false if parent cannot have children', function() {1116 board.state = 'mock';1117 var pluginStructure = $('.cms-draggable-1');1118 var pluginEdit = $('.cms-plugin-1');1119 var placeholder = $('.cms-draggables').eq(0);1120 placeholder.parent().addClass('cms-draggable-disabled');1121 $('.cms-placeholder-1').remove();1122 pluginEdit.data('cms', { plugin_parent_restriction: [] });1123 expect(options.isAllowed(placeholder, null, pluginStructure)).toEqual(false);1124 expect(board.state).toEqual('mock');1125 });1126 it('returns false if parent is a clipboard', function() {1127 board.state = 'mock';1128 var pluginStructure = $('.cms-draggable-1');1129 var pluginEdit = $('.cms-plugin-1');1130 var placeholder = $('.cms-draggables').eq(0);1131 placeholder.parent().addClass('cms-clipboard-containers');1132 $('.cms-placeholder-1').remove();1133 pluginEdit.data('cms', { plugin_parent_restriction: [] });1134 expect(options.isAllowed(placeholder, null, pluginStructure)).toEqual(false);1135 expect(board.state).toEqual('mock');1136 });1137 describe('bounds of a place we put current plugin in', function() {1138 it('uses placeholder bounds', function() {1139 board.state = 'mock';1140 var pluginStructure = $('.cms-draggable-1');1141 var placeholder = $('.cms-dragarea-1 > .cms-draggables');1142 var placeholderEdit = $('.cms-placeholder-1');1143 pluginStructure.data('cms', { plugin_parent_restriction: [] });1144 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1145 expect(options.isAllowed(placeholder, null, pluginStructure)).toEqual(false);1146 expect(board.state).toEqual(false);1147 });1148 it('uses placeholder bounds', function() {1149 board.state = 'mock';1150 var pluginStructure = $('.cms-draggable-1');1151 var placeholder = $('.cms-dragarea-1 > .cms-draggables');1152 var placeholderEdit = $('.cms-placeholder-1');1153 pluginStructure.data('cms', { plugin_parent_restriction: [], plugin_type: 'OnlyThisPlugin' });1154 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1155 expect(options.isAllowed(placeholder, null, pluginStructure)).toEqual(true);1156 expect(board.state).toEqual(true);1157 });1158 it('uses plugin bounds if pasted into the plugin', function() {1159 board.state = 'mock';1160 var pluginStructure = $('.cms-draggable-1');1161 var parentPluginStructure = $('.cms-draggable-2');1162 var placeholder = $('.cms-draggable-2 > .cms-draggables');1163 var placeholderEdit = $('.cms-placeholder-1');1164 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1165 pluginStructure.data('cms', { plugin_parent_restriction: [], plugin_type: 'OtherPlugin' });1166 parentPluginStructure.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1167 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1168 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(false);1169 expect(board.state).toEqual(false);1170 });1171 it('uses plugin bounds if pasted into the plugin', function() {1172 board.state = 'mock';1173 var pluginStructure = $('.cms-draggable-1');1174 var parentPluginStructure = $('.cms-draggable-2');1175 var placeholder = $('.cms-draggable-2 > .cms-draggables');1176 var placeholderEdit = $('.cms-placeholder-1');1177 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1178 pluginStructure.data('cms', { plugin_parent_restriction: [], plugin_type: 'OtherPlugin' });1179 parentPluginStructure.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1180 placeholderEdit.data('cms', { plugin_restriction: ['OtherPlugin'] });1181 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(false);1182 expect(board.state).toEqual(false);1183 });1184 it('uses plugin bounds if pasted into the plugin', function() {1185 board.state = 'mock';1186 var pluginStructure = $('.cms-draggable-1');1187 var parentPluginStructure = $('.cms-draggable-2');1188 var placeholder = $('.cms-draggable-2 > .cms-draggables');1189 var placeholderEdit = $('.cms-placeholder-1');1190 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1191 pluginStructure.data('cms', { plugin_parent_restriction: [], plugin_type: 'OtherPlugin' });1192 parentPluginStructure.data('cms', { plugin_restriction: [] });1193 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1194 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(true);1195 expect(board.state).toEqual(true);1196 });1197 it('uses placeholderParent bounds', function() {1198 board.state = 'mock';1199 var pluginStructure = $('.cms-draggable-1');1200 var parentPluginStructure = $('.cms-draggable-2');1201 var placeholder = $('.cms-draggable-2 > .cms-draggables');1202 var placeholderEdit = $('.cms-placeholder-1');1203 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1204 pluginStructure.data('cms', { plugin_parent_restriction: [], plugin_type: 'OtherPlugin' });1205 parentPluginStructure.data('cms', { plugin_restriction: [] });1206 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1207 // it's important that placeholder is used, and not .cms-draggable-11208 expect(options.isAllowed($('.cms-draggable-1'), placeholder, $('.cms-draggable-1'))).toEqual(true);1209 expect(board.state).toEqual(true);1210 });1211 });1212 describe('parent bonds of the plugin', function() {1213 it('respects parent bounds of the plugin', function() {1214 board.state = 'mock';1215 var pluginStructure = $('.cms-draggable-1');1216 var parentPluginStructure = $('.cms-draggable-2');1217 var placeholder = $('.cms-draggable-2 > .cms-draggables');1218 var placeholderEdit = $('.cms-placeholder-1');1219 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1220 pluginStructure.data('cms', {1221 plugin_parent_restriction: ['TestPlugin'],1222 plugin_type: 'OtherPlugin'1223 });1224 parentPluginStructure.data('cms', { plugin_restriction: [], plugin_type: 'TestPlugin' });1225 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1226 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(true);1227 expect(board.state).toEqual(true);1228 });1229 it('respects parent bounds of the plugin', function() {1230 board.state = 'mock';1231 var pluginStructure = $('.cms-draggable-1');1232 var parentPluginStructure = $('.cms-draggable-2');1233 var placeholder = $('.cms-draggable-2 > .cms-draggables');1234 var placeholderEdit = $('.cms-placeholder-1');1235 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1236 pluginStructure.data('cms', {1237 plugin_parent_restriction: ['TestPlugin'],1238 plugin_type: 'OtherPlugin'1239 });1240 parentPluginStructure.data('cms', { plugin_restriction: [], plugin_type: 'OtherType' });1241 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1242 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(false);1243 expect(board.state).toEqual(false);1244 });1245 it('works around "0" parent restriction for PlaceholderPlugin', function() {1246 board.state = 'mock';1247 var pluginStructure = $('.cms-draggable-1');1248 var parentPluginStructure = $('.cms-draggable-2');1249 var placeholder = $('.cms-draggable-2 > .cms-draggables');1250 var placeholderEdit = $('.cms-placeholder-1');1251 pluginStructure.appendTo(parentPluginStructure.find('> .cms-draggables'));1252 pluginStructure.data('cms', { plugin_parent_restriction: ['0'], plugin_type: 'OtherPlugin' });1253 parentPluginStructure.data('cms', { plugin_restriction: [], plugin_type: 'OtherType' });1254 placeholderEdit.data('cms', { plugin_restriction: ['OnlyThisPlugin'] });1255 expect(options.isAllowed(placeholder, null, $('.cms-draggable-1'))).toEqual(true);1256 expect(board.state).toEqual(true);1257 });1258 });1259 });1260 });1261 describe('invalidateState', () => {1262 let board;1263 beforeEach(done => {1264 fixture.load('plugins.html');1265 board = new CMS.StructureBoard();1266 StructureBoard.__Rewire__('Plugin', FakePlugin);1267 spyOn(StructureBoard, 'actualizePluginCollapseStatus');1268 spyOn(StructureBoard, 'actualizePlaceholders');1269 spyOn(StructureBoard, 'actualizePluginsCollapsibleStatus');1270 spyOn(Plugin, '_updateClipboard');1271 spyOn(board, '_drag');1272 setTimeout(() => {1273 done();1274 }, 20);1275 });1276 afterEach(() => {1277 fixture.cleanup();1278 StructureBoard.__ResetDependency__('Plugin');1279 });1280 describe('itself', () => {1281 beforeEach(() => {1282 spyOn(CMS.API.Helpers, 'reloadBrowser');1283 CMS.API.Toolbar = {1284 _refreshMarkup: jasmine.createSpy()1285 };1286 spyOn(board, 'handleAddPlugin');1287 spyOn(board, 'handleEditPlugin');1288 spyOn(board, 'handleDeletePlugin');1289 spyOn(board, 'handleClearPlaceholder');1290 spyOn(board, 'handleCopyPlugin');1291 spyOn(board, 'handleMovePlugin');1292 spyOn(board, 'handleCutPlugin');1293 spyOn(board, '_loadToolbar').and.returnValue({1294 done() {1295 return {1296 fail() {}1297 };1298 }1299 });1300 spyOn(board, '_requestMode').and.returnValue({1301 done() {1302 return {1303 fail() {}1304 };1305 }1306 });1307 spyOn(board, 'refreshContent');1308 });1309 it('delegates to correct methods', () => {1310 board.invalidateState('ADD', { randomData: 1 });1311 expect(board.handleAddPlugin).toHaveBeenCalledWith({ randomData: 1 });1312 board.invalidateState('MOVE', { randomData: 1 });1313 expect(board.handleMovePlugin).toHaveBeenCalledWith({ randomData: 1 });1314 board.invalidateState('COPY', { randomData: 1 });1315 expect(board.handleCopyPlugin).toHaveBeenCalledWith({ randomData: 1 });1316 board.invalidateState('PASTE', { randomData: 1 });1317 expect(board.handleMovePlugin).toHaveBeenCalledWith({ randomData: 1 });1318 board.invalidateState('CUT', { randomData: 1 });1319 expect(board.handleCutPlugin).toHaveBeenCalledWith({ randomData: 1 });1320 board.invalidateState('EDIT', { randomData: 1 });1321 expect(board.handleEditPlugin).toHaveBeenCalledWith({ randomData: 1 });1322 board.invalidateState('DELETE', { randomData: 1 });1323 expect(board.handleDeletePlugin).toHaveBeenCalledWith({ randomData: 1 });1324 board.invalidateState('CLEAR_PLACEHOLDER', { randomData: 1 });1325 expect(board.handleClearPlaceholder).toHaveBeenCalledWith({ randomData: 1 });1326 expect(board.handleAddPlugin).toHaveBeenCalledTimes(1);1327 expect(board.handleCopyPlugin).toHaveBeenCalledTimes(1);1328 expect(board.handleMovePlugin).toHaveBeenCalledTimes(2);1329 expect(board.handleCutPlugin).toHaveBeenCalledTimes(1);1330 expect(board.handleEditPlugin).toHaveBeenCalledTimes(1);1331 expect(board.handleDeletePlugin).toHaveBeenCalledTimes(1);1332 expect(board.handleClearPlaceholder).toHaveBeenCalledTimes(1);1333 });1334 it('reloads browser if there was no action', () => {1335 board.invalidateState();1336 expect(CMS.API.Helpers.reloadBrowser).toHaveBeenCalledWith();1337 expect(board._loadToolbar).not.toHaveBeenCalled();1338 });1339 it('reloads toolbar if there is an action', () => {1340 board.invalidateState('ADD', { randomData: 1 });1341 board.invalidateState('MOVE', { randomData: 1 });1342 board.invalidateState('COPY', { randomData: 1 });1343 board.invalidateState('PASTE', { randomData: 1 });1344 board.invalidateState('CUT', { randomData: 1 });1345 board.invalidateState('EDIT', { randomData: 1 });1346 board.invalidateState('DELETE', { randomData: 1 });1347 board.invalidateState('CLEAR_PLACEHOLDER', { randomData: 1 });1348 expect(board._loadToolbar).toHaveBeenCalledTimes(8);1349 board.invalidateState('x');1350 expect(board._loadToolbar).toHaveBeenCalledTimes(9);1351 });1352 it('refreshes markup if loading markup succeeds', () => {1353 board._loadToolbar.and.returnValue({1354 done(fn) {1355 fn();1356 return {1357 fail() {}1358 };1359 }1360 });1361 board.invalidateState('x');1362 expect(CMS.API.Toolbar._refreshMarkup).toHaveBeenCalled();1363 });1364 it('reloads if fails', () => {1365 board._loadToolbar.and.returnValue({1366 done() {1367 return {1368 fail(fn) {1369 fn();1370 }1371 };1372 }1373 });1374 board.invalidateState('x');1375 expect(CMS.API.Helpers.reloadBrowser).toHaveBeenCalled();1376 });1377 it('resets the requested content', () => {1378 const args = ['random', 'stuff'];1379 expect(CMS.settings.mode).toEqual('structure');1380 board._loadedContent = false;1381 board._requestMode.and.callFake(mode => {1382 expect(mode).toEqual('content');1383 return {1384 done(fn) {1385 fn(...args);1386 return { fail() {} };1387 }1388 };1389 });1390 board._requestcontent = '1';1391 board.invalidateState('x');1392 expect(board._requestcontent).toEqual(null);1393 expect(board.refreshContent).not.toHaveBeenCalled();1394 });1395 it('refreshes content mode if needed', () => {1396 const args = ['random', 'stuff'];1397 expect(CMS.settings.mode).toEqual('structure');1398 board._loadedContent = true;1399 board._requestMode.and.callFake(mode => {1400 expect(mode).toEqual('content');1401 return {1402 done(fn) {1403 fn(...args);1404 return { fail() {} };1405 }1406 };1407 });1408 board.invalidateState('x');1409 expect(board.refreshContent).toHaveBeenCalledWith('random');1410 });1411 it('reloads if it cannot refresh content', () => {1412 const args = ['random', 'stuff'];1413 expect(CMS.settings.mode).toEqual('structure');1414 board._loadedContent = true;1415 board._requestMode.and.callFake(mode => {1416 expect(mode).toEqual('content');1417 return {1418 done() {1419 return {1420 fail(fn) {1421 fn(...args);1422 }1423 };1424 }1425 };1426 });1427 board.invalidateState('x');1428 expect(CMS.API.Helpers.reloadBrowser).toHaveBeenCalledWith();1429 });1430 it('refreshes content if in content mode', () => {1431 const args = ['random', 'stuff'];1432 CMS.settings.mode = 'edit';1433 board._loadedContent = true;1434 board._requestMode.and.callFake(mode => {1435 expect(mode).toEqual('content');1436 expect(board._requestcontent).toEqual(null);1437 return {1438 done(fn) {1439 fn(...args);1440 return {1441 fail() {}1442 };1443 }1444 };1445 });1446 board.invalidateState('x');1447 expect(board._requestMode).toHaveBeenCalledWith('content');1448 expect(board.refreshContent).toHaveBeenCalledWith('random');1449 });1450 it('reloads if cant refresh content when in content mode', () => {1451 const args = ['random', 'stuff'];1452 CMS.settings.mode = 'edit';1453 board._loadedContent = false;1454 board._requestMode.and.callFake(mode => {1455 expect(mode).toEqual('content');1456 expect(board._requestcontent).toEqual(null);1457 return {1458 done() {1459 return {1460 fail(fn) {1461 fn(...args);1462 }1463 };1464 }1465 };1466 });1467 board.invalidateState('x');1468 expect(board._requestMode).toHaveBeenCalledWith('content');1469 expect(CMS.API.Helpers.reloadBrowser).toHaveBeenCalledWith();1470 });1471 });1472 describe('handleMovePlugin', () => {1473 it('replaces markup with given one', () => {1474 const data = {1475 plugin_parent: false,1476 plugin_id: 1,1477 html: '<div class="new-draggable"><div class="cms-draggables"></div></div>',1478 plugins: [{ plugin_id: 1, otherStuff: true }]1479 };1480 board.handleMovePlugin(data);1481 expect($('.cms-draggable-1')).not.toExist();1482 expect($('.new-draggable')).toExist();1483 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1484 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.plugins);1485 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1486 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(1);1487 expect(board._drag).toHaveBeenCalled();1488 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1489 });1490 it('replaces markup with given one when parent is also provided', () => {1491 const data = {1492 plugin_parent: 2,1493 plugin_id: 1,1494 html: `1495 <div class="new-draggable ">1496 <div class="cms-draggables"><div class="cms-draggable-1"></div></div>1497 </div>1498 `,1499 plugins: [{ plugin_id: 1, otherStuff: true }]1500 };1501 board.handleMovePlugin(data);1502 expect($('.cms-draggable-1')).toExist();1503 expect($('.cms-draggable-2')).not.toExist();1504 expect($('.new-draggable')).toExist();1505 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1506 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.plugins);1507 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1508 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(1);1509 expect(board._drag).toHaveBeenCalled();1510 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1511 });1512 it('replaces markup with given one when it is copying from language', () => {1513 const data = {1514 target_placeholder_id: 2,1515 html: '<div class="new-draggable"><div class="cms-draggables"></div></div>',1516 plugins: [{ plugin_id: 1, otherStuff: true }]1517 };1518 board.handleMovePlugin(data);1519 expect($('.cms-draggable-1')).toExist();1520 expect($('.cms-draggable-2')).toExist();1521 expect($('.new-draggable')).toExist();1522 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1523 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.plugins);1524 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1525 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(1);1526 expect(board._drag).toHaveBeenCalled();1527 expect(board.ui.sortables.filter('.cms-dragarea-2 .new-draggable .cms-draggables')).toExist();1528 });1529 it('handles top level move update when in same placeholder', () => {1530 const data = {1531 placeholder_id: 1,1532 plugin_id: 2,1533 plugin_order: ['2', '1'],1534 html: `1535 <div class="cms-draggable cms-draggable-2 new-cms-draggable-2">1536 </div>1537 `,1538 plugins: [{ plugin_id: 2, otherStuff: true }, { plugin_id: 1, otherStuff: true }]1539 };1540 board.handleMovePlugin(data);1541 expect($('.cms-draggable-1')).toExist();1542 expect($('.cms-draggable-2')).toExist();1543 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1544 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.plugins);1545 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(2);1546 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(1);1547 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(2);1548 expect(board._drag).toHaveBeenCalled();1549 expect($('.new-cms-draggable-2')).toExist();1550 expect($('.cms-draggable-2').index()).toEqual(0); // account for "empty" message1551 expect($('.cms-draggable-1').index()).toEqual(2);1552 });1553 it('handles top level move update when in same placeholder', () => {1554 const data = {1555 placeholder_id: 1,1556 plugin_id: 1,1557 plugin_order: ['2', '1'],1558 html: `1559 <div class="cms-draggable cms-draggable-1 new-cms-draggable-1">1560 </div>1561 `,1562 plugins: [{ plugin_id: 2, otherStuff: true }, { plugin_id: 1, otherStuff: true }]1563 };1564 board.handleMovePlugin(data);1565 expect($('.cms-draggable-1')).toExist();1566 expect($('.cms-draggable-2')).toExist();1567 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1568 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.plugins);1569 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(2);1570 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(1);1571 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(2);1572 expect(board._drag).toHaveBeenCalled();1573 expect($('.new-cms-draggable-1')).toExist();1574 expect($('.cms-draggable-2').index()).toEqual(1);1575 expect($('.cms-draggable-1').index()).toEqual(2);1576 });1577 });1578 describe('handleAddPlugin', () => {1579 it('replaces parent if provided', () => {1580 const data = {1581 plugin_parent: 2,1582 plugin_id: 3,1583 structure: {1584 html: `1585 <div class="cms-draggable-2 new">1586 <div class="cms-draggables">1587 <div class="cms-draggable-3 new-draggable">1588 <div class="cms-draggables"></div>1589 </div>1590 </div>1591 </div>1592 `,1593 plugins: [{ plugin_id: 2, otherStuff: true }, { plugin_id: 3, other_stuff: false }]1594 }1595 };1596 board.handleAddPlugin(data);1597 expect($('.cms-draggable-2')).toHaveClass('new');1598 expect($('.new-draggable')).toExist();1599 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1600 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.structure.plugins);1601 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(2);1602 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(2);1603 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(3);1604 expect(board._drag).toHaveBeenCalled();1605 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1606 });1607 it('appends to placeholder if no parent', () => {1608 const data = {1609 plugin_parent: null,1610 placeholder_id: 2,1611 plugin_id: 3,1612 structure: {1613 html: `1614 <div class="cms-draggable-3 new-draggable">1615 <div class="cms-draggables"></div>1616 </div>1617 `,1618 plugins: [{ plugin_id: 3, other_stuff: false }]1619 }1620 };1621 board.handleAddPlugin(data);1622 expect($('.cms-draggable-2')).not.toHaveClass('new');1623 expect($('.cms-dragarea-2 > .cms-draggables > .new-draggable')).toBeInDOM();1624 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1625 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.structure.plugins);1626 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1627 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(3);1628 expect(board._drag).toHaveBeenCalled();1629 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1630 });1631 });1632 describe('handleEditPlugin', () => {1633 it('replaces edited plugin with new markup', () => {1634 const data = {1635 plugin_parent: null,1636 plugin_id: 2,1637 structure: {1638 html: `1639 <div class="cms-draggable-3 new-draggable">1640 <div class="cms-draggables"></div>1641 </div>1642 `,1643 plugins: [{ plugin_id: 3, other_stuff: false }]1644 }1645 };1646 board.handleEditPlugin(data);1647 expect($('.cms-draggable-2')).not.toExist();1648 expect($('.new-draggable')).toBeInDOM();1649 expect(StructureBoard.actualizePlaceholders).not.toHaveBeenCalled();1650 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.structure.plugins);1651 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1652 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(3);1653 expect(board._drag).toHaveBeenCalled();1654 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1655 });1656 it('replaces parent of edited plugin if it was passed', () => {1657 const data = {1658 plugin_parent: 2,1659 plugin_id: 3,1660 structure: {1661 html: `1662 <div class="cms-draggable-3 new-draggable">1663 <div class="cms-draggables"></div>1664 </div>1665 `,1666 plugins: [{ plugin_id: 3, other_stuff: false }]1667 }1668 };1669 board.handleEditPlugin(data);1670 expect($('.cms-draggable-2')).not.toExist();1671 expect($('.new-draggable')).toBeInDOM();1672 expect(StructureBoard.actualizePlaceholders).not.toHaveBeenCalled();1673 expect(FakePlugin._updateRegistry).toHaveBeenCalledWith(data.structure.plugins);1674 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledTimes(1);1675 expect(StructureBoard.actualizePluginCollapseStatus).toHaveBeenCalledWith(3);1676 expect(board._drag).toHaveBeenCalled();1677 expect(board.ui.sortables.filter('.new-draggable .cms-draggables')).toExist();1678 });1679 });1680 describe('handleDeletePlugin', () => {1681 it('removes plugin', () => {1682 CMS._plugins = [['cms-plugin-1', { plugin_id: 1 }], ['cms-plugin-2']];1683 CMS._instances = [{ options: { plugin_id: 1 } }, { options: { plugin_id: 2 } }];1684 board.handleDeletePlugin({ plugin_id: 1 });1685 expect($('.cms-draggable-1')).not.toBeInDOM();1686 expect(StructureBoard.actualizePluginsCollapsibleStatus).toHaveBeenCalledWith(1687 $('.cms-dragarea-1 > .cms-draggables')1688 );1689 expect(CMS._plugins).toEqual([['cms-plugin-2']]);1690 expect(CMS._instances).toEqual([{ options: { plugin_id: 2 } }]);1691 });1692 it('removes plugin and its children', () => {1693 CMS._plugins = [['cms-plugin-3', { plugin_id: 3 }], ['cms-plugin-4']];1694 CMS._instances = [{ options: { plugin_id: 3 } }, { options: { plugin_id: 4 } }];1695 $('.cms-draggable-2').find('.cms-draggables').append(`1696 <div class="cms-draggable cms-draggable-3">1697 <div class="cms-draggables">1698 <div class="cms-draggable cms-draggable-4">1699 </div>1700 </div>1701 </div>1702 `);1703 expect($('.cms-draggable-3')).toBeInDOM();1704 expect($('.cms-draggable-4')).toBeInDOM();1705 board.handleDeletePlugin({ plugin_id: 3 });1706 expect($('.cms-draggable-3')).not.toBeInDOM();1707 expect($('.cms-draggable-4')).not.toBeInDOM();1708 expect(StructureBoard.actualizePluginsCollapsibleStatus).toHaveBeenCalledWith(1709 $('.cms-draggable-2 > .cms-draggables')1710 );1711 expect(CMS._plugins).toEqual([]);1712 expect(CMS._instances).toEqual([]);1713 });1714 });1715 describe('handleClearPlaceholder', () => {1716 it('clears placeholder', () => {1717 CMS._plugins = [1718 ['cms-plugin-3'],1719 ['cms-plugin-1', { plugin_id: 1, placeholder_id: 1 }],1720 ['cms-plugin-2', { plugin_id: '2', placeholder_id: 1 }]1721 ];1722 CMS._instances = [1723 { options: { plugin_id: 3 } },1724 { options: { plugin_id: 1, placeholder_id: 1 } },1725 { options: { plugin_id: '2', placeholder_id: '1' } }1726 ];1727 expect($('.cms-draggable-1')).toBeInDOM();1728 expect($('.cms-draggable-2')).toBeInDOM();1729 board.handleClearPlaceholder({ placeholder_id: 1 });1730 expect($('.cms-draggable-1')).not.toBeInDOM();1731 expect($('.cms-draggable-2')).not.toBeInDOM();1732 expect(StructureBoard.actualizePluginsCollapsibleStatus).not.toHaveBeenCalled();1733 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();1734 expect(CMS._plugins).toEqual([['cms-plugin-3']]);1735 expect(CMS._instances).toEqual([{ options: { plugin_id: 3 } }]);1736 });1737 });1738 describe('handleCopyPlugin', () => {1739 const clipboardConstructor = jasmine.createSpy();1740 const close = jasmine.createSpy();1741 class FakeClipboard {1742 constructor(...args) {1743 clipboardConstructor(...args);1744 }1745 }1746 FakeClipboard.prototype = Object.assign(FakeClipboard.prototype, {1747 _isClipboardModalOpen: jasmine.createSpy(),1748 modal: {1749 close: jasmine.createSpy()1750 },1751 populate: jasmine.createSpy(),1752 _enableTriggers: jasmine.createSpy()1753 });1754 beforeEach(() => {1755 CMS.API.Clipboard = {1756 _isClipboardModalOpen: jasmine.createSpy(),1757 modal: {1758 close1759 },1760 populate: jasmine.createSpy(),1761 _enableTriggers: jasmine.createSpy()1762 };1763 StructureBoard.__Rewire__('Clipboard', FakeClipboard);1764 StructureBoard.__Rewire__('Plugin', FakePlugin);1765 fixture.load('clipboard.html');1766 });1767 afterEach(() => {1768 StructureBoard.__ResetDependency__('Clipboard');1769 StructureBoard.__ResetDependency__('Plugin');1770 });1771 it('updates the clipboard', () => {1772 const data = {1773 plugins: [{ plugin_id: 10, stuff: true }],1774 html: '<div class="new-clipboard-draggable cms-draggable-from-clipboard"></div>'1775 };1776 CMS._plugins = [];1777 CMS._instances = [];1778 board.handleCopyPlugin(data);1779 expect(CMS._plugins).toEqual([['cms-plugin-10', data.plugins[0]]]);1780 expect(CMS._instances).toEqual([jasmine.any(FakePlugin)]);1781 expect(FakePlugin._updateClipboard).toHaveBeenCalled();1782 expect(clipboardConstructor).toHaveBeenCalled();1783 expect(FakeClipboard.prototype.populate).toHaveBeenCalled();1784 expect(FakeClipboard.prototype._enableTriggers).toHaveBeenCalled();1785 expect(board.ui.sortables.find('.new-clipboard-draggable')).toExist();1786 expect(board._drag).toHaveBeenCalled();1787 expect(pluginConstructor).toHaveBeenCalledWith('cms-plugin-10', data.plugins[0]);1788 expect(CMS.API.Clipboard.modal.close).not.toHaveBeenCalled();1789 });1790 it('closes clipboard modal if needed', () => {1791 CMS.API.Clipboard._isClipboardModalOpen.and.returnValue(true);1792 const data = {1793 plugins: [{ plugin_id: 10, stuff: true }],1794 html: '<div class="new-clipboard-draggable cms-draggable-from-clipboard"></div>'1795 };1796 board.handleCopyPlugin(data);1797 expect(close).toHaveBeenCalled();1798 });1799 });1800 describe('handleCutPlugin', () => {1801 it('calls delete and copy', () => {1802 spyOn(board, 'handleDeletePlugin');1803 spyOn(board, 'handleCopyPlugin');1804 board.handleCutPlugin({ randomData: true });1805 expect(board.handleDeletePlugin).toHaveBeenCalledWith({ randomData: true });1806 expect(board.handleCopyPlugin).toHaveBeenCalledWith({ randomData: true });1807 });1808 });1809 });1810 describe('_loadToolbar', () => {1811 it('loads toolbar url', () => {1812 const board = new StructureBoard();1813 spyOn($, 'ajax');1814 CMS.config.request = {1815 toolbar: 'TOOLBAR_URL',1816 pk: 100,1817 model: 'cms.page'1818 };1819 board._loadToolbar();1820 expect($.ajax).toHaveBeenCalledWith({1821 url: jasmine.stringMatching(1822 /TOOLBAR_URL\?obj_id=100&amp;obj_type=cms.page&amp;cms_path=%2Fcontext.html.*/1823 )1824 });1825 });1826 });1827 describe('_requestMode', () => {1828 let board;1829 let request;1830 const preloadImages = jasmine.createSpy();1831 beforeEach(() => {1832 board = new StructureBoard();1833 StructureBoard.__Rewire__('preloadImagesFromMarkup', preloadImages);1834 });1835 afterEach(() => {1836 StructureBoard.__ResetDependency__('preloadImagesFromMarkup');1837 preloadImages.calls.reset();1838 });1839 it('requests content', () => {1840 request = {1841 then(fn) {1842 fn('markup');1843 return request;1844 }1845 };1846 spyOn($, 'ajax').and.callFake(req => {1847 expect(req.method).toEqual('GET');1848 expect(req.url).toMatch(/\?edit/);1849 return request;1850 });1851 expect(board._requestcontent).not.toBeDefined();1852 board._requestMode('content');1853 expect(preloadImages).toHaveBeenCalledWith('markup');1854 expect(board._requestcontent).toBe(request);1855 });1856 it('requests structure', () => {1857 request = {1858 then(fn) {1859 fn('markup');1860 return request;1861 }1862 };1863 spyOn($, 'ajax').and.callFake(req => {1864 expect(req.method).toEqual('GET');1865 expect(req.url).toMatch(/\?structure/);1866 return request;1867 });1868 expect(board._requeststructure).not.toBeDefined();1869 board._requestMode('structure');1870 expect(preloadImages).toHaveBeenCalledWith('markup');1871 expect(board._requeststructure).toBe(request);1872 });1873 it('reuses same promise if it was not reset', () => {1874 request = {1875 then(fn) {1876 fn('markup');1877 return request;1878 }1879 };1880 spyOn($, 'ajax').and.callFake(req => {1881 expect(req.method).toEqual('GET');1882 expect(req.url).toMatch(/\?edit/);1883 return request;1884 });1885 expect(board._requestcontent).not.toBeDefined();1886 board._requestMode('content');1887 expect(preloadImages).toHaveBeenCalledWith('markup');1888 expect(board._requestcontent).toBe(request);1889 board._requestMode('content');1890 expect(preloadImages).toHaveBeenCalledTimes(1);1891 expect(board._requestcontent).toBe(request);1892 });1893 });1894 describe('_loadContent', () => {1895 let board;1896 let response = '';1897 let requestSucceeded;1898 beforeEach(() => {1899 requestSucceeded = jasmine.createSpy();1900 CMS.API.Toolbar = {1901 _refreshMarkup: jasmine.createSpy()1902 };1903 board = new StructureBoard();1904 CMS.config = {1905 settings: {1906 mode: 'structure'1907 }1908 };1909 spyOn(board, '_requestMode').and.returnValue({1910 done(fn) {1911 requestSucceeded();1912 fn(response);1913 return {1914 fail() {1915 return {1916 then(callback) {1917 callback();1918 }1919 };1920 }1921 };1922 }1923 });1924 StructureBoard.__Rewire__('Plugin', FakePlugin);1925 Plugin.__Rewire__('Plugin', FakePlugin);1926 });1927 afterEach(() => {1928 StructureBoard.__ResetDependency__('Plugin');1929 Plugin.__ResetDependency__('Plugin', FakePlugin);1930 });1931 it('resolves immediately when content mode is already loaded', done => {1932 CMS.config.settings.mode = 'edit';1933 board._loadContent().then(() => {1934 expect(requestSucceeded).not.toHaveBeenCalled();1935 done();1936 });1937 CMS.config.settings.mode = 'structure';1938 });1939 it('resolves immediately when content mode is already loaded', done => {1940 board._loadedContent = true;1941 board._loadContent().then(() => {1942 expect(requestSucceeded).not.toHaveBeenCalled();1943 done();1944 });1945 CMS.config.settings.mode = 'structure';1946 });1947 it('requests content', done => {1948 response = `1949 <html attr0="a" attr1="b">1950 <head>1951 <title>i am a new title</title>1952 </head>1953 <body attr2="x" attr3="y">1954 <p class="new-content">New body content yay</p>1955 </body>1956 </html>1957 `;1958 CMS._instances = [1959 new FakePlugin('cms-plugin-1', { plugin_id: 1, type: 'plugin' }),1960 new FakePlugin('cms-placeholder-1', { placeholder_id: 1, type: 'placeholder' }),1961 new FakePlugin('cms-plugin-existing-generic-1', { plugin_id: '1', type: 'generic' })1962 ];1963 CMS._plugins = [1964 ['cms-plugin-1', { plugin_id: 1, type: 'plugin' }],1965 ['cms-plugin-1', { plugin_id: 1, type: 'plugin' }],1966 ['cms-placeholder-1', { placeholder_id: 1, type: 'placeholder' }],1967 ['cms-plugin-existing-generic-1', { plugin_id: 1, type: 'generic' }],1968 ['cms-plugin-new-generic-2', { plugin_id: 2, type: 'generic' }]1969 ];1970 expect(board._loadedContent).not.toBeDefined();1971 pluginConstructor.calls.reset();1972 board._loadContent().then(() => {1973 expect(showLoader).toHaveBeenCalled();1974 expect(hideLoader).toHaveBeenCalled();1975 expect(CMS.API.Toolbar._refreshMarkup).toHaveBeenCalled();1976 expect($('html').attr('attr0')).toEqual('a');1977 expect($('html').attr('attr1')).toEqual('b');1978 expect($('body').attr('attr2')).toEqual('x');1979 expect($('body').attr('attr3')).toEqual('y');1980 expect($('.new-content')).toBeInDOM();1981 expect(FakePlugin.prototype._ensureData).toHaveBeenCalledTimes(3);1982 expect(FakePlugin.prototype._setGeneric).toHaveBeenCalledTimes(1);1983 expect(FakePlugin.prototype._setPluginContentEvents).toHaveBeenCalledTimes(1);1984 expect(pluginConstructor).toHaveBeenCalledTimes(1);1985 $('.new-content').remove();1986 expect(board._loadedContent).toBe(true);1987 done();1988 });1989 });1990 });1991 describe('_loadStructure', () => {1992 let board;1993 let response = '';1994 let requestSucceeded;1995 beforeEach(() => {1996 requestSucceeded = jasmine.createSpy();1997 CMS.API.Toolbar = {1998 _refreshMarkup: jasmine.createSpy()1999 };2000 board = new StructureBoard();2001 CMS.config = {2002 settings: {2003 mode: 'edit'2004 }2005 };2006 spyOn(StructureBoard, '_initializeGlobalHandlers');2007 spyOn(StructureBoard, 'actualizePlaceholders');2008 spyOn(StructureBoard, '_initializeDragItemsStates');2009 spyOn(board, '_drag');2010 spyOn(board, '_requestMode').and.returnValue({2011 done(fn) {2012 requestSucceeded();2013 fn(response);2014 return {2015 fail() {2016 return {2017 then(callback) {2018 callback();2019 }2020 };2021 }2022 };2023 }2024 });2025 StructureBoard.__Rewire__('Plugin', FakePlugin);2026 });2027 afterEach(() => {2028 StructureBoard.__ResetDependency__('Plugin');2029 });2030 it('resolves immediately when structure mode is already loaded', done => {2031 CMS.config.settings.mode = 'structure';2032 board._loadStructure().then(() => {2033 expect(requestSucceeded).not.toHaveBeenCalled();2034 done();2035 });2036 CMS.config.settings.mode = 'edit';2037 });2038 it('resolves immediately when structure mode is already loaded', done => {2039 board._loadedStructure = true;2040 board._loadStructure().then(() => {2041 expect(requestSucceeded).not.toHaveBeenCalled();2042 done();2043 });2044 CMS.config.settings.mode = 'edit';2045 });2046 it('requests structure', done => {2047 response = `2048 <html attr0="a" attr1="b">2049 <head>2050 <title>i am a new title</title>2051 </head>2052 <body attr2="x" attr3="y">2053 <p class="new-content">New body content yay</p>2054 </body>2055 </html>2056 `;2057 CMS._instances = [2058 new FakePlugin('cms-plugin-1', { plugin_id: 1, type: 'plugin' }),2059 new FakePlugin('cms-placeholder-1', { placeholder_id: 1, type: 'placeholder' }),2060 new FakePlugin('cms-plugin-existing-generic-1', { plugin_id: '1', type: 'generic' })2061 ];2062 expect(board._loadedStructure).not.toBeDefined();2063 pluginConstructor.calls.reset();2064 board._loadStructure().then(() => {2065 expect(showLoader).toHaveBeenCalled();2066 expect(hideLoader).toHaveBeenCalled();2067 expect(CMS.API.Toolbar._refreshMarkup).toHaveBeenCalled();2068 expect(FakePlugin.prototype._setPlaceholder).toHaveBeenCalledTimes(1);2069 expect(FakePlugin.prototype._setPluginStructureEvents).toHaveBeenCalledTimes(1);2070 expect(FakePlugin.prototype._setGeneric).not.toHaveBeenCalled();2071 expect(pluginConstructor).not.toHaveBeenCalled();2072 expect(board._drag).toHaveBeenCalled();2073 expect(StructureBoard._initializeDragItemsStates).toHaveBeenCalled();2074 expect(StructureBoard._initializeGlobalHandlers).toHaveBeenCalled();2075 expect(StructureBoard.actualizePlaceholders).toHaveBeenCalled();2076 expect(board._loadedStructure).toBe(true);2077 done();2078 });2079 });2080 });2081 describe('_getPluginDataFromMarkup()', () => {2082 [2083 {2084 args: ['', [1, 2, 3]],2085 expected: []2086 },2087 {2088 args: ['whatever', []],2089 expected: []2090 },2091 {2092 args: ['CMS._plugins.push(["cms-plugin-4",{"plugin_id":"4"}]);', [1, 2, 3]],2093 expected: []2094 },2095 {2096 args: ['CMS._plugins.push(["cms-plugin-4",{"plugin_id":"4"}]);', [1, 2, 4]],2097 expected: [['cms-plugin-4', { plugin_id: '4' }]]2098 },2099 {2100 args: [2101 `CMS._plugins.push(["cms-plugin-4",{"plugin_id":"4"}]);2102 CMS._plugins.push(["cms-plugin-10", { "plugin_id": "meh"}]);`, [1, 2, 10]],2103 expected: [['cms-plugin-10', { plugin_id: 'meh' }]]2104 },2105 {2106 args: ['CMS._plugins.push(["cms-plugin-4",{plugin_id:"4"}])', [4]],2107 expected: []2108 },2109 {2110 args: ['CMS._plugins.push(["cms-plugin-4",not a json :(]);', [4]],2111 expected: []2112 },2113 {2114 args: [`CMS._plugins.push(["cms-plugin-4", {2115 "something": 12116 }])`, [4]],2117 expected: [['cms-plugin-4', { something: 1 }]]2118 }2119 ].forEach((test, i) => {2120 it(`extracts plugin data from markup ${i}`, () => {2121 expect(StructureBoard._getPluginDataFromMarkup(...test.args)).toEqual(test.expected);2122 });2123 });2124 });2125 describe('_extractMessages()', () => {2126 let board;2127 beforeEach(() => {2128 board = new StructureBoard();2129 });2130 it('extracts messages', () => {2131 expect(2132 board._extractMessages(2133 $(`2134 <div>2135 <div data-cms-messages-container>2136 <div data-cms-message data-cms-message-tags="error">2137 Error2138 </div>2139 <div data-cms-message data-cms-message-tags="invalid">2140 Normal2141 </div>2142 <div data-cms-message>2143 </div>2144 </div>2145 </div>2146 `)2147 )2148 ).toEqual([{ message: 'Error', error: true }, { message: 'Normal', error: false }]);2149 expect(2150 board._extractMessages(2151 $(`2152 <div>2153 <ul class="messagelist"></ul>2154 <div data-cms-messages-container>2155 <div data-cms-message data-cms-message-tags="error">2156 Error12157 </div>2158 <div data-cms-message data-cms-message-tags="invalid">2159 Normal12160 </div>2161 </div>2162 </div>2163 `)2164 )2165 ).toEqual([{ message: 'Error1', error: true }, { message: 'Normal1', error: false }]);2166 expect(2167 board._extractMessages(2168 $(`2169 <div>2170 <ul class="messagelist">2171 <li class="whatever">normal message</li>2172 <li class="error">error message</li>2173 </ul>2174 </div>2175 `)2176 )2177 ).toEqual([{ message: 'normal message', error: false }, { message: 'error message', error: true }]);2178 expect(2179 board._extractMessages(2180 $(`2181 <div>2182 </div>2183 `)2184 )2185 ).toEqual([]);2186 });2187 });2188 describe('_refreshContent()', () => {2189 let board;2190 const diffDOMConstructor = jasmine.createSpy();2191 const newDoc = `2192 <!DOCTYPE html>2193 <html>2194 <head>2195 </head>2196 <body>2197 <div class="new-markup">new markup</div>2198 </body>2199 </html>2200 `;2201 class DiffDOM {2202 constructor() {2203 diffDOMConstructor();2204 }2205 }2206 DiffDOM.prototype.diff = jasmine.createSpy();2207 DiffDOM.prototype.apply = jasmine.createSpy();2208 class FakeDOMParser {}2209 FakeDOMParser.prototype.parseFromString = jasmine.createSpy().and.returnValue({2210 head: 'fakeNewHead',2211 body: 'fakeNewBody'2212 });2213 beforeEach(() => {2214 StructureBoard.__Rewire__('DiffDOM', DiffDOM);2215 StructureBoard.__Rewire__('DOMParser', FakeDOMParser);2216 board = new StructureBoard();2217 spyOn(StructureBoard, '_replaceBodyWithHTML');2218 CMS.API.Messages = {2219 open: jasmine.createSpy()2220 };2221 CMS.API.Toolbar = {2222 _refreshMarkup: jasmine.createSpy()2223 };2224 });2225 afterEach(() => {2226 StructureBoard.__ResetDependency__('DiffDOM');2227 StructureBoard.__ResetDependency__('DOMParser');2228 });2229 it('resets loaded content flag', () => {2230 CMS._instances = [];2231 board._requestcontent = {};2232 board._loadedContent = false;2233 board.refreshContent(newDoc);2234 expect(board._requestcontent).toBe(null);2235 expect(board._loadedContent).toBe(true);2236 });2237 it('shows messages', done => {2238 CMS._instances = [];2239 spyOn(board, '_extractMessages').and.returnValue([{ message: 'hello' }]);2240 board.refreshContent(newDoc);2241 setTimeout(() => {2242 expect(CMS.API.Messages.open).toHaveBeenCalledWith({ message: 'hello' });2243 done();2244 }, 20);2245 });2246 it('resets plugin instances', () => {2247 CMS._instances = [2248 new FakePlugin('cms-plugin-1', { plugin_id: 1, type: 'plugin' }),2249 new FakePlugin('cms-placeholder-1', { placeholder_id: 1, type: 'placeholder' })2250 ];2251 board.refreshContent(newDoc);2252 expect(FakePlugin.prototype._setupUI).toHaveBeenCalledTimes(2);2253 expect(FakePlugin.prototype._setupUI).toHaveBeenCalledWith('cms-plugin-1');2254 expect(FakePlugin.prototype._setupUI).toHaveBeenCalledWith('cms-placeholder-1');2255 expect(FakePlugin.prototype._ensureData).toHaveBeenCalledTimes(2);2256 expect(FakePlugin.prototype._setPlaceholder).toHaveBeenCalledTimes(1);2257 expect(FakePlugin.prototype._setPluginContentEvents).toHaveBeenCalledTimes(1);2258 });2259 });2260 describe('_preloadOppositeMode', () => {2261 ['content', 'structure'].forEach(mode => {2262 it(`preloads the opposite mode (${mode})`, () => {2263 const div = document.createElement('div');2264 const _getWindow = jasmine.createSpy().and.returnValue(div);2265 StructureBoard.__Rewire__('Helpers', {2266 _getWindow2267 });2268 const board = new StructureBoard();2269 spyOn(board, '_requestMode');2270 jasmine.clock().install();2271 if (mode === 'content') {2272 board._loadedStructure = false;2273 } else {2274 board._loadedStructure = true;2275 }2276 board._preloadOppositeMode();2277 expect(board._requestMode).not.toHaveBeenCalled();2278 $(div).trigger('load');2279 expect(board._requestMode).not.toHaveBeenCalled();2280 jasmine.clock().tick(2001);2281 expect(board._requestMode).toHaveBeenCalledTimes(1);2282 expect(board._requestMode).toHaveBeenCalledWith(mode === 'content' ? 'structure' : 'content');2283 jasmine.clock().uninstall();2284 StructureBoard.__ResetDependency__('Helpers');2285 });2286 });2287 it('does not preload the opposite mode (legacy renderer)', () => {2288 const div = document.createElement('div');2289 const _getWindow = jasmine.createSpy().and.returnValue(div);2290 StructureBoard.__Rewire__('Helpers', {2291 _getWindow2292 });2293 const board = new StructureBoard();2294 spyOn(board, '_requestMode');2295 jasmine.clock().install();2296 CMS.config.settings.legacy_mode = true;2297 board._loadedContent = true;2298 board._loadedStructure = true;2299 board._preloadOppositeMode();2300 expect(board._requestMode).not.toHaveBeenCalled();2301 $(div).trigger('load');2302 expect(board._requestMode).not.toHaveBeenCalled();2303 jasmine.clock().tick(2001);2304 expect(board._requestMode).not.toHaveBeenCalled();2305 jasmine.clock().uninstall();2306 StructureBoard.__ResetDependency__('Helpers');2307 });2308 });2309 describe('actualizePluginCollapseStatus', () => {2310 it('works', () => {2311 $('#fixture_container').append(`2312 <div class="cms-draggable-1">2313 <div class="cms-collapsable-container cms-hidden"></div>2314 <div class="cms-dragitem"></div>2315 <div class="cms-draggables"></div>2316 </div>2317 `);2318 CMS.settings = {2319 states: ['1\n']2320 };2321 StructureBoard.actualizePluginCollapseStatus(1);2322 expect('.cms-draggable-1 .cms-collapsable-container').not.toHaveClass('cms-hidden');2323 expect('.cms-draggable-1 .cms-dragitem').toHaveClass('cms-dragitem-expanded');2324 $('#fixture_container').empty();2325 });2326 });...

Full Screen

Full Screen

PlatformJson.spec.js

Source:PlatformJson.spec.js Github

copy

Full Screen

1/**2 Licensed to the Apache Software Foundation (ASF) under one3 or more contributor license agreements. See the NOTICE file4 distributed with this work for additional information5 regarding copyright ownership. The ASF licenses this file6 to you under the Apache License, Version 2.0 (the7 "License"); you may not use this file except in compliance8 with the License. You may obtain a copy of the License at9 http://www.apache.org/licenses/LICENSE-2.010 Unless required by applicable law or agreed to in writing,11 software distributed under the License is distributed on an12 "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY13 KIND, either express or implied. See the License for the14 specific language governing permissions and limitations15 under the License.16*/17const rewire = require('rewire');18const PlatformJson = rewire('../src/PlatformJson');19const ModuleMetadata = PlatformJson.__get__('ModuleMetadata');20const FAKE_MODULE = {21 name: 'fakeModule',22 src: 'www/fakeModule.js',23 clobbers: [{ target: 'window.fakeClobber' }],24 merges: [{ target: 'window.fakeMerge' }],25 runs: true26};27describe('PlatformJson class', function () {28 it('Test 001 : should be constructable', function () {29 expect(new PlatformJson()).toEqual(jasmine.any(PlatformJson));30 });31 describe('instance', function () {32 let platformJson;33 let fakePlugin;34 beforeEach(function () {35 platformJson = new PlatformJson('/fake/path', 'android');36 fakePlugin = jasmine.createSpyObj('fakePlugin', ['getJsModules']);37 fakePlugin.id = 'fakeId';38 fakePlugin.version = '1.0.0';39 fakePlugin.getJsModules.and.returnValue([FAKE_MODULE]);40 });41 describe('addPluginMetadata method', function () {42 it('Test 002 : should not throw if root "modules" property is missing', function () {43 expect(function () {44 platformJson.addPluginMetadata(fakePlugin);45 }).not.toThrow();46 });47 it('Test 003 : should add each module to "root.modules" array', function () {48 platformJson.addPluginMetadata(fakePlugin);49 expect(platformJson.root.modules.length).toBe(1);50 expect(platformJson.root.modules[0]).toEqual(jasmine.any(ModuleMetadata));51 });52 it('Test 004 : shouldn\'t add module if there is already module with the same file added', function () {53 platformJson.root.modules = [{54 name: 'fakePlugin2',55 file: 'plugins/fakeId/www/fakeModule.js'56 }];57 platformJson.addPluginMetadata(fakePlugin);58 expect(platformJson.root.modules.length).toBe(1);59 expect(platformJson.root.modules[0].name).toBe('fakePlugin2');60 });61 it('Test 005 : should add entry to plugin_metadata with corresponding version', function () {62 platformJson.addPluginMetadata(fakePlugin);63 expect(platformJson.root.plugin_metadata[fakePlugin.id]).toBe(fakePlugin.version);64 });65 });66 describe('removePluginMetadata method', function () {67 it('Test 006 : should not throw if root "modules" property is missing', function () {68 expect(function () {69 platformJson.removePluginMetadata(fakePlugin);70 }).not.toThrow();71 });72 it('Test 007 : should remove plugin modules from "root.modules" array based on file path', function () {73 const pluginPaths = [74 'plugins/fakeId/www/fakeModule.js',75 'plugins/otherPlugin/www/module1.js',76 'plugins/otherPlugin/www/module1.js'77 ];78 platformJson.root.modules = pluginPaths.map(function (p) { return { file: p }; });79 platformJson.removePluginMetadata(fakePlugin);80 const resultantPaths = platformJson.root.modules81 .map(function (p) { return p.file; })82 .filter(function (f) { return /fakeModule\.js$/.test(f); });83 expect(resultantPaths.length).toBe(0);84 });85 it('Test 008 : should remove entry from plugin_metadata with corresponding version', function () {86 platformJson.root.plugin_metadata = {};87 platformJson.root.plugin_metadata[fakePlugin.id] = fakePlugin.version;88 platformJson.removePluginMetadata(fakePlugin);89 expect(platformJson.root.plugin_metadata[fakePlugin.id]).not.toBeDefined();90 });91 });92 function evaluateCordovaDefineStatement (str) {93 expect(typeof str).toBe('string');94 const fnString = str.replace(/^\s*cordova\.define\('cordova\/plugin_list',\s*([\s\S]+)\);\s*$/, '($1)');95 const mod = { exports: {} };96 global.eval(fnString)(null, mod.exports, mod); // eslint-disable-line no-eval97 return mod;98 }99 function expectedMetadata () {100 // Create plain objects from ModuleMetadata instances101 const modules = platformJson.root.modules.map(o => Object.assign({}, o));102 modules.metadata = platformJson.root.plugin_metadata;103 return modules;104 }105 describe('generateMetadata method', function () {106 it('Test 009 : should generate text metadata containing list of installed modules', function () {107 const meta = platformJson.addPluginMetadata(fakePlugin).generateMetadata();108 const mod = evaluateCordovaDefineStatement(meta);109 expect(mod.exports).toEqual(expectedMetadata());110 });111 });112 describe('generateAndSaveMetadata method', function () {113 it('should save generated metadata', function () {114 // Needs to use graceful-fs, since that is used by fs-extra115 const spy = spyOn(require('graceful-fs'), 'writeFileSync');116 const dest = require('path').join(__dirname, 'test-destination');117 platformJson.addPluginMetadata(fakePlugin).generateAndSaveMetadata(dest);118 expect(spy).toHaveBeenCalledTimes(1);119 const [file, data] = spy.calls.argsFor(0);120 expect(file).toBe(dest);121 const mod = evaluateCordovaDefineStatement(data);122 expect(mod.exports).toEqual(expectedMetadata());123 });124 });125 });126});127describe('ModuleMetadata class', function () {128 it('Test 010 : should be constructable', function () {129 let meta;130 expect(function () {131 meta = new ModuleMetadata('fakePlugin', { src: 'www/fakeModule.js' });132 }).not.toThrow();133 expect(meta instanceof ModuleMetadata).toBeTruthy();134 });135 it('Test 011 : should throw if either pluginId or jsModule argument isn\'t specified', function () {136 expect(ModuleMetadata).toThrow();137 expect(() => new ModuleMetadata('fakePlugin', {})).toThrow();138 });139 it('Test 012 : should guess module id either from name property of from module src', function () {140 expect(new ModuleMetadata('fakePlugin', { name: 'fakeModule' }).id).toMatch(/fakeModule$/);141 expect(new ModuleMetadata('fakePlugin', { src: 'www/fakeModule.js' }).id).toMatch(/fakeModule$/);142 });143 it('Test 013 : should read "clobbers" property from module', function () {144 expect(new ModuleMetadata('fakePlugin', { name: 'fakeModule' }).clobbers).not.toBeDefined();145 const metadata = new ModuleMetadata('fakePlugin', FAKE_MODULE);146 expect(metadata.clobbers).toEqual(jasmine.any(Array));147 expect(metadata.clobbers[0]).toBe(FAKE_MODULE.clobbers[0].target);148 });149 it('Test 014 : should read "merges" property from module', function () {150 expect(new ModuleMetadata('fakePlugin', { name: 'fakeModule' }).merges).not.toBeDefined();151 const metadata = new ModuleMetadata('fakePlugin', FAKE_MODULE);152 expect(metadata.merges).toEqual(jasmine.any(Array));153 expect(metadata.merges[0]).toBe(FAKE_MODULE.merges[0].target);154 });155 it('Test 015 : should read "runs" property from module', function () {156 expect(new ModuleMetadata('fakePlugin', { name: 'fakeModule' }).runs).not.toBeDefined();157 expect(new ModuleMetadata('fakePlugin', FAKE_MODULE).runs).toBe(true);158 });...

Full Screen

Full Screen

graphql-codegen.config.test.js

Source:graphql-codegen.config.test.js Github

copy

Full Screen

1import * as fs from 'fs-extra'2import * as path from 'path'3import { buildSchema } from 'graphql'4import { loadDocuments } from '@graphql-tools/load'5import { generateWithConfig, mapCodegenPlugins } from './graphql-codegen.config'6jest.mock('fs-extra', () => ({7 ensureDir: jest.fn(),8 writeFile: jest.fn(),9}))10jest.mock('@graphql-tools/load', () => ({11 loadDocuments: jest.fn(),12}))13it('takes in options and returns a function that runs codegen for the schema', async () => {14 loadDocuments.mockReturnValueOnce(Promise.resolve([]))15 const mockReporter = {16 warn: jest.fn(),17 }18 const generateFromSchema = await generateWithConfig({19 directory: './example-directory',20 documentPaths: ['./src/**/*.{ts,tsx}'],21 fileName: 'example-types.ts',22 reporter: mockReporter,23 codegenPlugins: [],24 codegenConfig: {},25 })26 const mockSchema = buildSchema(`27 type Query {28 example: String29 }30 `)31 expect(mockSchema).toMatchInlineSnapshot(`32 GraphQLSchema {33 "__validationErrors": undefined,34 "_directives": Array [35 "@include",36 "@skip",37 "@deprecated",38 "@specifiedBy",39 ],40 "_implementationsMap": Object {},41 "_mutationType": undefined,42 "_queryType": "Query",43 "_subTypeMap": Object {},44 "_subscriptionType": undefined,45 "_typeMap": Object {46 "Boolean": "Boolean",47 "Query": "Query",48 "String": "String",49 "__Directive": "__Directive",50 "__DirectiveLocation": "__DirectiveLocation",51 "__EnumValue": "__EnumValue",52 "__Field": "__Field",53 "__InputValue": "__InputValue",54 "__Schema": "__Schema",55 "__Type": "__Type",56 "__TypeKind": "__TypeKind",57 },58 "astNode": undefined,59 "description": undefined,60 "extensionASTNodes": Array [],61 "extensions": undefined,62 }63 `)64 await generateFromSchema(mockSchema)65 expect(fs.ensureDir).toMatchInlineSnapshot(`66 [MockFunction] {67 "calls": Array [68 Array [69 "example-directory",70 ],71 ],72 "results": Array [73 Object {74 "type": "return",75 "value": undefined,76 },77 ],78 }79 `)80 expect(fs.writeFile.mock.calls[0]).toBeDefined()81 expect(fs.writeFile.mock.calls[0][0]).toBe(82 path.join('example-directory', 'example-types.ts')83 )84 expect(fs.writeFile.mock.calls[0][1]).toMatchInlineSnapshot(`85 "export type Maybe<T> = T | null;86 export type Exact<T extends { [key: string]: unknown }> = { [K in keyof T]: T[K] };87 export type MakeOptional<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]?: Maybe<T[SubKey]> };88 export type MakeMaybe<T, K extends keyof T> = Omit<T, K> & { [SubKey in K]: Maybe<T[SubKey]> };89 /** All built-in and custom scalars, mapped to their actual values */90 export type Scalars = {91 ID: string;92 String: string;93 Boolean: boolean;94 Int: number;95 Float: number;96 };97 export type Query = {98 example?: Maybe<Scalars['String']>;99 };100 "101 `)102 expect(mockReporter.warn).not.toHaveBeenCalled()103})104it('calls `reporter.warn` when `loadDocuments` rejects', async () => {105 loadDocuments.mockReturnValueOnce(Promise.reject(new Error('test error')))106 const mockReporter = {107 warn: jest.fn(),108 }109 const generateFromSchema = await generateWithConfig({110 directory: './example-directory',111 documentPaths: ['./src/**/*.{ts,tsx}'],112 fileName: 'example-types.ts',113 reporter: mockReporter,114 codegenPlugins: [],115 codegenConfig: {},116 })117 const mockSchema = buildSchema(`118 type Query {119 example: String120 }121 `)122 await generateFromSchema(mockSchema)123 expect(mockReporter.warn).toMatchInlineSnapshot(`124 [MockFunction] {125 "calls": Array [126 Array [127 "[gatsby-plugin-graphql-codegen] test error",128 ],129 ],130 "results": Array [131 Object {132 "type": "return",133 "value": undefined,134 },135 ],136 }137 `)138})139describe('mapCodegenPlugins', () => {140 const fakePlugin = () => {}141 it('add new plugin', () => {142 const { pluginMap, plugins } = mapCodegenPlugins({143 codegenPlugins: [144 {145 resolve: fakePlugin,146 options: {147 hey: false,148 },149 },150 ],151 defaultPlugins: {152 pluginMap: {},153 plugins: [],154 },155 })156 const identifier = 'codegen-plugin-0'157 expect(plugins).toHaveLength(1)158 expect(plugins).toContainEqual({ [identifier]: { hey: false } })159 expect(pluginMap).toHaveProperty(identifier)160 expect(pluginMap[identifier].plugin).toBe(fakePlugin)161 })162 it('update default plugins', () => {163 const { pluginMap, plugins } = mapCodegenPlugins({164 codegenPlugins: [165 {166 resolve: 'typescript',167 options: {168 hey: false,169 },170 },171 ],172 defaultPlugins: {173 pluginMap: {174 typescript: {175 plugin: fakePlugin,176 },177 },178 plugins: [{ typescript: { hey: true } }],179 },180 })181 const identifier = 'typescript'182 expect(plugins).toHaveLength(1)183 expect(plugins).toContainEqual({ [identifier]: { hey: false } })184 expect(pluginMap).toHaveProperty(identifier)185 expect(pluginMap[identifier].plugin).toBe(fakePlugin)186 })187 it('add new plugin and update default plugin', () => {188 const { pluginMap, plugins } = mapCodegenPlugins({189 codegenPlugins: [190 {191 resolve: 'typescript',192 options: {193 hey: false,194 },195 },196 {197 resolve: fakePlugin,198 options: {199 how: 1,200 },201 },202 ],203 defaultPlugins: {204 pluginMap: {205 typescript: {206 plugin: fakePlugin,207 },208 },209 plugins: [{ typescript: { hey: true } }],210 },211 })212 expect(plugins).toHaveLength(2)213 expect(plugins).toContainEqual({ typescript: { hey: false } })214 expect(plugins).toContainEqual({ 'codegen-plugin-1': { how: 1 } })215 expect(pluginMap).toHaveProperty('typescript')216 expect(pluginMap).toHaveProperty('codegen-plugin-1')217 })...

Full Screen

Full Screen

PluginManager.js

Source:PluginManager.js Github

copy

Full Screen

1import PluginManager from 'src/lib/PluginManager.js';2var fakeEditor = {};3var fakePlugin;4var fakePluginTwo;5var pluginManager;6QUnit.module('lib/PluginManager', {7 beforeEach: function () {8 fakePlugin = function () {};9 fakePluginTwo = function () {};10 pluginManager = new PluginManager(fakeEditor);11 PluginManager.plugins.fakePlugin = fakePlugin;12 PluginManager.plugins.fakePluginTwo = fakePluginTwo;13 }14});15QUnit.test('call()', function (assert) {16 var arg = {};17 var firstSpy = sinon.spy();18 var secondSpy = sinon.spy();19 fakePlugin.prototype.signalTest = firstSpy;20 fakePluginTwo.prototype.signalTest = secondSpy;21 pluginManager.register('fakePlugin');22 pluginManager.register('fakePluginTwo');23 pluginManager.call('test', arg);24 assert.ok(firstSpy.calledOnce);25 assert.ok(firstSpy.calledOn(fakeEditor));26 assert.ok(firstSpy.calledWithExactly(arg));27 assert.ok(secondSpy.calledOnce);28 assert.ok(secondSpy.calledOn(fakeEditor));29 assert.ok(secondSpy.calledWithExactly(arg));30 assert.ok(firstSpy.calledBefore(secondSpy));31});32QUnit.test('callOnlyFirst()', function (assert) {33 var arg = {};34 var stub = sinon.stub();35 stub.returns(1);36 fakePlugin.prototype.signalTest = stub;37 fakePluginTwo.prototype.signalTest = sinon.spy();38 pluginManager.register('fakePlugin');39 pluginManager.register('fakePluginTwo');40 assert.ok(pluginManager.callOnlyFirst('test', arg));41 assert.ok(fakePlugin.prototype.signalTest.calledOnce);42 assert.ok(fakePlugin.prototype.signalTest.calledOn(fakeEditor));43 assert.ok(fakePlugin.prototype.signalTest.calledWithExactly(arg));44 assert.ok(!fakePluginTwo.prototype.signalTest.called);45});46QUnit.test('hasHandler()', function (assert) {47 fakePlugin.prototype.signalTest = sinon.spy();48 fakePluginTwo.prototype.signalTest = sinon.spy();49 fakePluginTwo.prototype.signalTestTwo = sinon.spy();50 pluginManager.register('fakePlugin');51 pluginManager.register('fakePluginTwo');52 assert.ok(pluginManager.hasHandler('test'));53 assert.ok(pluginManager.hasHandler('testTwo'));54});55QUnit.test('hasHandler() - No handler', function (assert) {56 fakePlugin.prototype.signalTest = sinon.spy();57 pluginManager.register('fakePlugin');58 assert.ok(!pluginManager.hasHandler('teSt'));59 assert.ok(!pluginManager.hasHandler('testTwo'));60});61QUnit.test('exists()', function (assert) {62 assert.ok(pluginManager.exists('fakePlugin'));63 assert.ok(!pluginManager.exists('noPlugin'));64});65QUnit.test('isRegistered()', function (assert) {66 pluginManager.register('fakePlugin');67 assert.ok(pluginManager.isRegistered('fakePlugin'));68 assert.ok(!pluginManager.isRegistered('fakePluginTwo'));69});70QUnit.test('register() - No plugin', function (assert) {71 assert.strictEqual(pluginManager.register('noPlugin'), false);72});73QUnit.test('register() - Call init', function (assert) {74 fakePlugin.prototype.init = sinon.spy();75 fakePluginTwo.prototype.init = sinon.spy();76 assert.strictEqual(pluginManager.register('fakePlugin'), true);77 assert.ok(fakePlugin.prototype.init.calledOnce);78 assert.ok(fakePlugin.prototype.init.calledOn(fakeEditor));79 assert.ok(!fakePluginTwo.prototype.init.called);80});81QUnit.test('register() - Called twice', function (assert) {82 fakePlugin.prototype.init = sinon.spy();83 assert.strictEqual(pluginManager.register('fakePlugin'), true);84 assert.strictEqual(pluginManager.register('fakePlugin'), false);85 assert.ok(fakePlugin.prototype.init.calledOnce);86 assert.ok(fakePlugin.prototype.init.calledOn(fakeEditor));87});88QUnit.test('deregister()', function (assert) {89 fakePlugin.prototype.destroy = sinon.spy();90 fakePluginTwo.prototype.destroy = sinon.spy();91 pluginManager.register('fakePlugin');92 pluginManager.register('fakePluginTwo');93 pluginManager.deregister('fakePlugin');94 assert.ok(fakePlugin.prototype.destroy.calledOnce);95 assert.ok(fakePlugin.prototype.destroy.calledOn(fakeEditor));96 assert.ok(!fakePluginTwo.prototype.destroy.calledOnce);97});98QUnit.test('deregister() - Called twice', function (assert) {99 fakePlugin.prototype.destroy = sinon.spy();100 fakePluginTwo.prototype.destroy = sinon.spy();101 pluginManager.register('fakePlugin');102 pluginManager.register('fakePluginTwo');103 pluginManager.deregister('fakePlugin');104 pluginManager.deregister('fakePlugin');105 assert.ok(fakePlugin.prototype.destroy.calledOnce);106 assert.ok(fakePlugin.prototype.destroy.calledOn(fakeEditor));107 assert.ok(!fakePluginTwo.prototype.destroy.calledOnce);108});109QUnit.test('destroy()', function (assert) {110 fakePlugin.prototype.destroy = sinon.spy();111 fakePluginTwo.prototype.destroy = sinon.spy();112 pluginManager.register('fakePlugin');113 pluginManager.register('fakePluginTwo');114 pluginManager.destroy();115 assert.ok(fakePlugin.prototype.destroy.calledOnce);116 assert.ok(fakePlugin.prototype.destroy.calledOn(fakeEditor));117 assert.ok(fakePluginTwo.prototype.destroy.calledOnce);118 assert.ok(fakePluginTwo.prototype.destroy.calledOn(fakeEditor));...

Full Screen

Full Screen

plugin-test.js

Source:plugin-test.js Github

copy

Full Screen

...10 proxy.target.success = true;11 resolver.resolve();12 }13};14function fakePlugin() {15 return {16 facets: {17 test: {18 ready: function(resolver, proxy) {19 proxy.target.success = true;20 resolver.resolve();21 }22 }23 }24 };25}26buster.testCase('plugin', {27 'sync-init': {28 'should initialize': function() {29 function pluginFactory() {30 return plugin;31 }32 return wire({33 plugins: [pluginFactory],34 fixture: { literal: {} }35 }).then(36 function(context) {37 assert(context.fixture.success);38 },39 fail40 );41 }42 },43 'async-init': {44 'should initialize': function() {45 function pluginFactory() {46 return delay(plugin, 0);47 }48 return wire({49 plugins: [pluginFactory],50 fixture: { literal: {} }51 }).then(52 function(context) {53 assert(context.fixture.success);54 },55 fail56 );57 }58 },59 'namespace': {60 'should be in global namespace when not specified': function() {61 return wire({62 plugins: [fakePlugin],63 fixture: {64 literal: {},65 test: {}66 }67 }).then(68 function(context) {69 assert(context.fixture.success);70 },71 fail72 );73 },74 'should not be in global namespace when namespace provided': function() {75 return wire({76 plugins: { testNamespace: fakePlugin },77 fixture: {78 literal: {},79 test: {}80 }81 }).then(82 fail,83 function(e) {84 assert.defined(e);85 }86 );87 },88 'should be in provided namespace': function() {89 return wire({90 plugins: { testNamespace: fakePlugin },91 fixture: {92 literal: {},93 'testNamespace:test': {}94 }95 }).then(96 function(context) {97 assert(context.fixture.success);98 },99 fail100 );101 },102 'should fail wiring if non-unique': function() {103 return wire({104 plugins: [105 { wire$plugin: fakePlugin, $ns: 'namespace' },106 { wire$plugin: function() { return fakePlugin(); }, $ns: 'namespace' }107 ]108 }).then(109 fail,110 function(e) {111 assert.defined(e);112 }113 );114 }115 }116});117})(118 require('buster'),119 require('when/delay'),120 require('../../wire')...

Full Screen

Full Screen

MetadataTest.js

Source:MetadataTest.js Github

copy

Full Screen

1asynctest(2 'Browser Test: .MetadataTest',3 [4 'ephox.agar.api.Assertions',5 'ephox.agar.api.Chain',6 'ephox.agar.api.Pipeline',7 'ephox.agar.api.UiFinder',8 'ephox.mcagar.api.TinyDom',9 'ephox.mcagar.api.TinyLoader',10 'ephox.mcagar.api.TinyUi',11 'ephox.sugar.api.properties.Html',12 'tinymce.plugins.help.Plugin',13 'tinymce.plugins.help.test.FakePlugin',14 'tinymce.plugins.help.test.NoMetaFakePlugin',15 'tinymce.themes.modern.Theme'16 ],17 function (Assertions, Chain, Pipeline, UiFinder, TinyDom, TinyLoader, TinyUi, Html, HelpPlugin, FakePlugin, NoMetaFakePlugin, ModernTheme) {18 var success = arguments[arguments.length - 2];19 var failure = arguments[arguments.length - 1];20 ModernTheme();21 HelpPlugin();22 FakePlugin();23 NoMetaFakePlugin();24 var sAssertPluginList = function (html) {25 return Chain.asStep(TinyDom.fromDom(document.body), [26 UiFinder.cWaitFor('Could not find notification', 'div.mce-floatpanel ul'),27 Chain.mapper(Html.get),28 Assertions.cAssertHtml('Plugin list html does not match', html)29 ]);30 };31 TinyLoader.setup(function (editor, onSuccess, onFailure) {32 var tinyUi = TinyUi(editor);33 Pipeline.async({}, [34 tinyUi.sClickOnToolbar('click on help button', 'button'),35 sAssertPluginList(36 '<li><a href="https://www.tinymce.com/docs/plugins/help" target="_blank" rel="noopener">Help</a></li>' +37 '<li><a href="http://www.fake.com" target="_blank" rel="noopener">Fake</a></li>' +38 '<li>nometafake</li>'39 )40 ], onSuccess, onFailure);41 }, {42 plugins: 'help fake nometafake',43 toolbar: 'help',44 skin_url: '/project/src/skins/lightgray/dist/lightgray'45 }, success, failure);46 }...

Full Screen

Full Screen

dns.js

Source:dns.js Github

copy

Full Screen

1var Hapi = require('hapi');2var Lab = require('lab');3var Nipple = require('nipple');4var Sinon = require('sinon');5var lab = exports.lab = Lab.script();6var describe = lab.describe;7var it = lab.it;8var beforeEach = lab.beforeEach;9var afterEach = lab.afterEach;10var expect = Lab.expect;11describe('github/dns', function() {12 var Dns = require('../../lib/github/dns');13 var spy, fakePlugin;14 beforeEach(function(done) {15 spy = Sinon.spy(function(slug, content, callback) {16 if (slug === 'error') {17 callback(new Error('dns error'));18 }19 callback(null, 'foo');20 });21 fakePlugin = {22 methods: {23 dns: spy24 }25 };26 done();27 });28 afterEach(function(done) {29 spy = null;30 fakePlugin = null;31 done();32 });33 it('calls the dns method', function(done) {34 var dns = Dns(fakePlugin, 'foo', 'bar');35 expect(spy.calledOnce).to.be.true;36 done();37 });38 it('handles errors', function(done) {39 Dns(fakePlugin, 'error', 'bar');40 expect(spy.calledOnce).to.be.true;41 done();42 });...

Full Screen

Full Screen

fake-plugin.js

Source:fake-plugin.js Github

copy

Full Screen

1class fakePlugin {2 testFunc () {3 return true4 }5}6fakePlugin.type = 'plugin'7fakePlugin.version = '0.0.0'8class legacyPlugin {9 testFunc () {10 return true11 }12}13legacyPlugin.plugin_name = 'legacyPluginName'14legacyPlugin.type = 'plugin'15legacyPlugin.version = '0.0.0'16class renamedPlugin {17 testFunc () {18 return true19 }20}21renamedPlugin.pluginName = 'test-plugin'22renamedPlugin.type = 'plugin'23renamedPlugin.version = '0.0.0'24class dependencyPlugin {25 constructor (deps) {26 this.deps = deps27 }28}29dependencyPlugin.dependencies = [30 'fakePlugin',31 'legacyPluginName',32 'test-plugin'33]34dependencyPlugin.type = 'plugin'35dependencyPlugin.version = '0.0.0'36class namePrecedencePlugin {}37namePrecedencePlugin.pluginName = 'correctPluginName'38namePrecedencePlugin.plugin_name = 'incorrectPluginName'39namePrecedencePlugin.type = 'plugin'40namePrecedencePlugin.version = '0.0.0'41module.exports = {42 fakePlugin,43 legacyPlugin,44 renamedPlugin,45 dependencyPlugin,46 namePrecedencePlugin...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1const wd = require('wd');2const chai = require('chai');3const chaiAsPromised = require('chai-as-promised');4const chaiWebdriver = require('chai-webdriverio').default;5const fakePlugin = require('appium-fake-plugin');6chai.use(chaiAsPromised);7chai.use(chaiWebdriver(browser));8const should = chai.should();9describe('fake plugin test', function () {10 let driver;11 before(async function () {12 await driver.init({

Full Screen

Using AI Code Generation

copy

Full Screen

1var wd = require('wd');2var assert = require('assert');3var desired = {4};5var browser = wd.remote();6browser.init(desired, function() {7 browser.elementByTagName('body', function(err, body) {8 assert.ok(!err);9 body.text(function(err, text) {10 assert.ok(text.length > 0);11 browser.quit();12 });13 });14 });15});

Full Screen

Using AI Code Generation

copy

Full Screen

1const fakePlugin = require('appium-base-driver').fakePlugin;2const fakePlugin2 = require('appium-base-driver').fakePlugin2;3fakePlugin('test');4fakePlugin2('test');5exports.fakePlugin = function (param) {6 console.log(`Fake Plugin called with param: ${param}`);7};8exports.fakePlugin2 = function (param) {9 console.log(`Fake Plugin called with param: ${param}`);10};11exports.fakePlugin = async function (param) {12 return await this.fakePlugin(param);13};14exports.fakePlugin2 = async function (param) {15 return await this.fakePlugin2(param);16};17exports.fakePlugin = require('./plugin').fakePlugin;18exports.fakePlugin2 = require('./plugin').fakePlugin2;19exports.fakePlugin = function (param) {20 console.log(`Fake Plugin called with param: ${param}`);21};22exports.fakePlugin2 = function (param) {23 console.log(`Fake Plugin called with param: ${param}`);24};25exports.fakePlugin = async function (param) {26 return await this.fakePlugin(param);27};28exports.fakePlugin2 = async function (param) {29 return await this.fakePlugin2(param);30};31exports.fakePlugin = require('./plugin').fakePlugin;32exports.fakePlugin2 = require('./plugin').fakePlugin2;33exports.fakePlugin = function (param) {34 console.log(`Fake Plugin called with param: ${param}`);35};36exports.fakePlugin2 = function (param) {37 console.log(`Fake Plugin called with param: ${param}`);38};39exports.fakePlugin = async function (param) {40 return await this.fakePlugin(param);41};42exports.fakePlugin2 = async function (param) {43 return await this.fakePlugin2(param);44};

Full Screen

Using AI Code Generation

copy

Full Screen

1var BaseDriver = require('appium-base-driver');2var fakePlugin = BaseDriver.fakePlugin;3fakePlugin('fakePlugin', function() {4 console.log('fake plugin called');5});6var AndroidDriver = require('appium-android-driver');7AndroidDriver.fakePlugin('fakePlugin', function() {8 console.log('fake plugin called');9});10var IOSDriver = require('appium-ios-driver');11IOSDriver.fakePlugin('fakePlugin', function() {12 console.log('fake plugin called');13});14var WindowsDriver = require('appium-windows-driver');15WindowsDriver.fakePlugin('fakePlugin', function() {16 console.log('fake plugin called');17});18var MacDriver = require('appium-mac-driver');19MacDriver.fakePlugin('fakePlugin', function() {20 console.log('fake plugin called');21});22var YouiEngineDriver = require('appium-youiengine-driver');23YouiEngineDriver.fakePlugin('fakePlugin', function() {24 console.log('fake plugin called');25});26var SelendroidDriver = require('appium-selendroid-driver');27SelendroidDriver.fakePlugin('fakePlugin', function() {28 console.log('fake plugin called');29});30var EspressoDriver = require('appium-espresso-driver');31EspressoDriver.fakePlugin('fakePlugin', function() {32 console.log('fake plugin called');33});34var FakeDriver = require('appium-fake-driver');35FakeDriver.fakePlugin('fakePlugin', function() {36 console.log('fake plugin called');37});38var TizenDriver = require('appium-tizen-driver');39TizenDriver.fakePlugin('fakePlugin', function() {40 console.log('fake plugin called');41});42var FirefoxDriver = require('appium-firefox-driver');43FirefoxDriver.fakePlugin('fakePlugin', function() {44 console.log('fake plugin called');

Full Screen

Using AI Code Generation

copy

Full Screen

1describe('Fake Plugin', function () {2 it('should call fakePlugin', async function () {3 await driver.fakePlugin('fake');4 });5});6describe('Fake Plugin', function () {7 it('should call fakePlugin', async function () {8 await driver.fakePlugin('fake');9 });10});11describe('Fake Plugin', function () {12 it('should call fakePlugin', async function () {13 await driver.fakePlugin('fake');14 });15});16describe('Fake Plugin', function () {17 it('should call fakePlugin', async function () {18 await driver.fakePlugin('fake');19 });20});21describe('Fake Plugin', function () {22 it('should call fakePlugin', async function () {23 await driver.fakePlugin('fake');24 });25});26describe('Fake Plugin', function () {27 it('should call fakePlugin', async function () {28 await driver.fakePlugin('fake');29 });30});31describe('Fake Plugin', function () {32 it('should call fakePlugin', async function () {33 await driver.fakePlugin('fake');34 });35});36describe('Fake Plugin', function () {37 it('should call fakePlugin', async function () {38 await driver.fakePlugin('fake');39 });40});41describe('Fake Plugin', function () {42 it('should call fakePlugin', async function () {43 await driver.fakePlugin('fake');44 });45});46describe('Fake Plugin', function () {47 it('should call fakePlugin', async function () {48 await driver.fakePlugin('fake');49 });50});51describe('Fake Plugin', function () {52 it('should call fakePlugin', async function () {53 await driver.fakePlugin('fake');54 });55});56describe('Fake Plugin', function () {57 it('should call fake

Full Screen

Using AI Code Generation

copy

Full Screen

1module.exports = {2 fakePlugin: function() {3 return this.fakePlugin();4 }5}6describe('fakePlugin', function() {7 it('should return true', function() {8 driver.fakePlugin().should.eventually.be.true;9 });10});11describe('fakePlugin', function() {12 it('should return true', function() {13 driver.fakePlugin().should.eventually.be.true;14 });15});16describe('fakePlugin', function() {17 it('should return true', function() {18 driver.fakePlugin().should.eventually.be.true;19 });20});21describe('fakePlugin', function() {22 it('should return true', function() {23 driver.fakePlugin().should.eventually.be.true;24 });25});26describe('fakePlugin', function() {27 it('should return true', function() {28 driver.fakePlugin().should.eventually.be.true;29 });30});31describe('fakePlugin', function() {32 it('should return true', function() {33 driver.fakePlugin().should.eventually.be.true;34 });35});36describe('fakePlugin', function() {37 it('should return true', function() {38 driver.fakePlugin().should.eventually.be.true;39 });40});41describe('fakePlugin', function() {42 it('should return true', function() {43 driver.fakePlugin().should.eventually.be.true;44 });45});46describe('fakePlugin', function() {47 it('should return true', function() {48 driver.fakePlugin().should.eventually.be.true;49 });50});51describe('fakePlugin', function() {52 it('should return true', function() {53 driver.fakePlugin().should.eventually.be.true;54 });55});56describe('fakePlugin', function() {57 it('should return true', function() {58 driver.fakePlugin().should.eventually.be.true;59 });60});61describe('fakePlugin', function() {62 it('should return true', function() {63 driver.fakePlugin().should.event

Full Screen

Using AI Code Generation

copy

Full Screen

1var fakePluginName = 'fakePlugin';2var fakePluginFunction = function() {3 console.log('fakePluginFunction');4};5var fakePluginMethod = function() {6 console.log('fakePluginMethod');7};8var fakePluginName = 'fakePlugin';9var fakePluginFunction = function() {10 console.log('fakePluginFunction');11};12var fakePluginMethod = function() {13 console.log('fakePluginMethod');14};15var fakePluginName = 'fakePlugin';16var fakePluginFunction = function() {17 console.log('fakePluginFunction');18};19var fakePluginMethod = function() {20 console.log('fakePluginMethod');21};22var fakePluginName = 'fakePlugin';23var fakePluginFunction = function() {24 console.log('fakePluginFunction');25};26var fakePluginMethod = function() {27 console.log('fakePluginMethod');28};

Full Screen

Using AI Code Generation

copy

Full Screen

1await this.driver.fakePlugin('com.test.app', 'fakePlugin');2await this.driver.fakePlugin('com.test.app', 'fakePlugin');3await this.driver.fakePlugin('com.test.app', 'fakePlugin');4await this.driver.fakePlugin('com.test.app', 'fakePlugin');5await this.driver.fakePlugin('com.test.app', 'fakePlugin');6await this.driver.fakePlugin('com.test.app', 'fakePlugin');7await this.driver.fakePlugin('com.test.app', 'fakePlugin');8await this.driver.fakePlugin('

Full Screen

Automation Testing Tutorials

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.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Appium Base Driver automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful