Best JavaScript code snippet using playwright-internal
facetDynamic.spec.js
Source:facetDynamic.spec.js  
1describe("facet dynamic directive", function() {2    var $compile, $rootScope, $controller, $scope, provider;3    var selectOption = function() {};4    var deselectOption = function() {};5    var updateCallback = jasmine.createSpy('updateCallback');6    var facetOptions;7    beforeEach(module("ux-aspects.facets", "ux-aspects.previewPanes", "ux-aspects.safeTimeout", "ux-aspects.checkbox"));8    beforeEach(inject(function(_$controller_, _$compile_, _$rootScope_, _previewPaneProvider_) {9        $compile = _$compile_;10        $rootScope = _$rootScope_;11        $controller = _$controller_;12        provider = _previewPaneProvider_;13    }));14    beforeEach(function() {15        facetOptions = {16            name: 'Test Name',17            options: [{18                name: 'Item One',19                count: 0,20                select: selectOption,21                deselect: deselectOption22            }, {23                name: 'Item Two',24                count: 10,25                select: selectOption,26                deselect: deselectOption27            }, {28                name: 'Item Three',29                count: 20,30                select: selectOption,31                deselect: deselectOption32            }]33        };34    });35    describe("controller", function() {36        it('should have correct default display configuration', function() {37            //create new scope and decorate it38            $scope = $rootScope.$new();39            $scope.name = facetOptions.name;40            $scope.facetOptions = facetOptions;41            $scope.displayConfiguration = {};42            $scope.placeholder = 'Sample Placeholder';43            $scope.updateCallback = updateCallback;44            //instantiate controller with scope45            var controller = $controller("FacetDynamicCtrl as fc", {46                $scope: $scope47            });48            //expect default values49            expect(controller.maxDisplayableItems).toBe(facetOptions.options.length);50            expect(controller.minCharsForTypeahead).toBe(3);51            expect(controller.showZero).toBe(undefined);52        });53        it('should have correct display configuration after set', function() {54            //create new scope and decorate it55            $scope = $rootScope.$new();56            $scope.name = facetOptions.name;57            $scope.facetOptions = facetOptions;58            $scope.displayConfiguration = {59                minCharacters: 10,60                minIndividualItems: 11,61                maxIndividualItems: 12,62                maxDisplayableItems: 13,63                showZero: true64            };65            $scope.placeholder = 'Sample Placeholder';66            $scope.updateCallback = updateCallback;67            //instantiate controller with scope68            var controller = $controller("FacetDynamicCtrl as fc", {69                $scope: $scope70            });71            //expect set values72            expect(controller.maxDisplayableItems).toBe(13);73            expect(controller.minCharsForTypeahead).toBe(10);74            expect(controller.showZero).toBe(true);75            expect(controller.visibleFacetOptions.length).toBe(facetOptions.options.length);76        });77        it('should have typeahead control', function() {78            //create new scope and decorate it79            $scope = $rootScope.$new();80            $scope.name = facetOptions.name;81            $scope.facetOptions = facetOptions;82            $scope.displayConfiguration = {83                maxIndividualItems: 284            };85            $scope.placeholder = 'Sample Placeholder';86            $scope.updateCallback = updateCallback;87            //instantiate controller with scope88            var controller = $controller("FacetDynamicCtrl as fc", {89                $scope: $scope90            });91            //expect default values92            expect(controller.useTypeaheadControl).toBe(true);93            expect(controller.showFacetOptions).toBe(false);94        });95        it('should not have typeahead control', function() {96            //create new scope and decorate it97            $scope = $rootScope.$new();98            $scope.name = facetOptions.name;99            $scope.facetOptions = facetOptions;100            $scope.displayConfiguration = {101                maxIndividualItems: 4102            };103            $scope.placeholder = 'Sample Placeholder';104            $scope.updateCallback = updateCallback;105            //instantiate controller with scope106            var controller = $controller("FacetDynamicCtrl as fc", {107                $scope: $scope108            });109            //expect default values110            expect(controller.useTypeaheadControl).toBe(false);111            expect(controller.showFacetOptions).toBe(true);112        });113        it('should have typeahead control and facet options', function() {114            //create new scope and decorate it115            $scope = $rootScope.$new();116            $scope.name = facetOptions.name;117            $scope.facetOptions = facetOptions;118            $scope.displayConfiguration = {119                minIndividualItems: 1,120                maxIndividualItems: 2121            };122            $scope.placeholder = 'Sample Placeholder';123            $scope.updateCallback = updateCallback;124            //instantiate controller with scope125            var controller = $controller("FacetDynamicCtrl as fc", {126                $scope: $scope127            });128            //expect default values129            expect(controller.useTypeaheadControl).toBe(true);130            expect(controller.visibleFacetOptions.length).toBe(1);131            expect(controller.showFacetOptions).toBe(true);132        });133        it('should not show typeahead if showing all items as facet options', function() {134            //create new scope and decorate it135            $scope = $rootScope.$new();136            $scope.name = facetOptions.name;137            $scope.facetOptions = facetOptions;138            $scope.displayConfiguration = {139                minIndividualItems: 3,140                maxIndividualItems: 2141            };142            $scope.placeholder = 'Sample Placeholder';143            $scope.updateCallback = updateCallback;144            //instantiate controller with scope145            var controller = $controller("FacetDynamicCtrl as fc", {146                $scope: $scope147            });148            //expect default values149            expect(controller.useTypeaheadControl).toBe(false);150            expect(controller.showFacetOptions).toBe(true);151        });152    });153    describe("element", function() {154        var htmlTemplate =155            "<facet-container select-title=\"Filters\" clear-text=\"Clear All\" no-items-text=\"None selected\">\n" +156            "  <facet-dynamic name=\"name\" facet-options=\"facetOptions\" display-configuration=\"displayConfiguration\" placeholder=\"placeholder\" update-callback=\"updateCallback\">\n" +157            "  </facet-dynamic>\n" +158            "</facet-container>";159        it("should display element correctly", function() {160            //create new scope and decorate it161            $scope = $rootScope.$new();162            $scope.name = facetOptions.name;163            $scope.facetOptions = facetOptions;164            $scope.displayConfiguration = {};165            $scope.placeholder = 'Sample Placeholder';166            $scope.updateCallback = updateCallback;167            var element = $compile(htmlTemplate)($scope);168            $scope.$digest();169            //ensure title text is correct170            var titleElements = element[0].getElementsByClassName('facet-name');171            expect(titleElements.length).toBe(1);172            var title = titleElements[0].innerText;173            expect(title).toBe($scope.name);174            var typeaheadElement = element[0].getElementsByTagName('textarea');175            expect(typeaheadElement.length).toBe(1);176            var placeholder = typeaheadElement[0].getAttribute('placeholder');177            expect(placeholder).toBe($scope.placeholder + '...');178        });179        it("should show no facet options", function() {180            //create new scope and decorate it181            $scope = $rootScope.$new();182            $scope.name = facetOptions.name;183            $scope.facetOptions = facetOptions;184            $scope.displayConfiguration = {};185            $scope.placeholder = 'Sample Placeholder';186            $scope.updateCallback = updateCallback;187            var element = $compile(htmlTemplate)($scope);188            $scope.$digest();189            var facetElements = element[0].getElementsByClassName('facet-option');190            expect(facetElements.length).toBe(0);191        });192        it("should show facet options with counts greater than zero", function() {193            //create new scope and decorate it194            $scope = $rootScope.$new();195            $scope.name = facetOptions.name;196            $scope.facetOptions = facetOptions;197            $scope.displayConfiguration = {198                minIndividualItems: 3199            };200            $scope.placeholder = 'Sample Placeholder';201            $scope.updateCallback = updateCallback;202            var element = $compile(htmlTemplate)($scope);203            $scope.$digest();204            var facetElements = element[0].getElementsByClassName('facet-option');205            expect(facetElements.length).toBe(2);206        });207        it("should show facet options with counts greater than or equal to zero", function() {208            //create new scope and decorate it209            $scope = $rootScope.$new();210            $scope.name = facetOptions.name;211            $scope.facetOptions = facetOptions;212            $scope.displayConfiguration = {213                minIndividualItems: 3,214                showZero: true215            };216            $scope.placeholder = 'Sample Placeholder';217            $scope.updateCallback = updateCallback;218            var element = $compile(htmlTemplate)($scope);219            $scope.$digest();220            var facetElements = element[0].getElementsByClassName('facet-option');221            expect(facetElements.length).toBe(3);222        });223        it("should call updateCallback when typeahead text changes", function() {224            //create new scope and decorate it225            $scope = $rootScope.$new();226            $scope.name = facetOptions.name;227            $scope.facetOptions = facetOptions;228            $scope.displayConfiguration = {229                maxIndividualItems: 1230            };231            $scope.placeholder = 'Sample Placeholder';232            $scope.updateCallback = updateCallback;233            var element = $compile(htmlTemplate)($scope);234            $scope.$digest();235            var typeaheadElement = element[0].getElementsByTagName('textarea');236            expect(typeaheadElement.length).toBe(1);237            //set value less than min character length238            typeaheadElement[0].value = 'abc';239            angular.element(typeaheadElement[0]).triggerHandler('input');240            expect($scope.updateCallback).toHaveBeenCalled();241        });242        it("should call select facet option when clicked", function() {243            //create new scope and decorate it244            $scope = $rootScope.$new();245            $scope.name = facetOptions.name;246            $scope.facetOptions = facetOptions;247            $scope.displayConfiguration = {248                minIndividualItems: 1249            };250            $scope.placeholder = 'Sample Placeholder';251            $scope.updateCallback = updateCallback;252            var element = $compile(htmlTemplate)($scope);253            $scope.$digest();254            //find a facet option255            var facetOptionsElements = element[0].getElementsByClassName('facet-option');256            expect(facetOptionsElements.length).toBe(1);257            var facetLink = facetOptionsElements[0].getElementsByTagName('a');258            expect(facetLink.length).toBe(1);259            //should be unchecked260            var tickIcon = facetLink[0].getElementsByClassName('el-checkbox');261            expect(tickIcon.length).toBe(1);262            expect(angular.element(tickIcon[0]).hasClass('checked')).toBe(false);263            //click link264            angular.element(facetLink[0]).click();265            $scope.$digest();266            expect(angular.element(tickIcon[0]).hasClass('checked')).toBe(true);267        });268    });...api.test.js
Source:api.test.js  
...13    describe('no selected story', () => {14      it('should set stories and select the first story', () => {15        const clientStore = new MockClientStore();16        actions.setStories({ clientStore }, stories);17        const newState = clientStore.updateCallback({});18        expect(newState).toEqual({19          stories,20          selectedKind: 'abc',21          selectedStory: 'a',22        });23      });24    });25    describe('has a selected story', () => {26      it('should set stories and select the existing story', () => {27        const clientStore = new MockClientStore();28        actions.setStories({ clientStore }, stories);29        const state = {30          selectedKind: 'abc',31          selectedStory: 'c',32        };33        const newState = clientStore.updateCallback(state);34        expect(newState).toEqual({35          stories,36          selectedKind: 'abc',37          selectedStory: 'c',38        });39      });40    });41    describe('has a selected story, but it is story is not in new stories', () => {42      it('should set stories and select the first story of the selected kind', () => {43        const clientStore = new MockClientStore();44        actions.setStories({ clientStore }, stories);45        const state = {46          selectedKind: 'bbc',47          selectedStory: 'k',48        };49        const newState = clientStore.updateCallback(state);50        expect(newState).toEqual({51          stories,52          selectedKind: 'bbc',53          selectedStory: 'x',54        });55      });56    });57    describe('has a selected story, but it is kind is not in new stories', () => {58      it('should set stories and select the first story', () => {59        const clientStore = new MockClientStore();60        actions.setStories({ clientStore }, stories);61        const state = {62          selectedKind: 'kky',63          selectedStory: 'c',64        };65        const newState = clientStore.updateCallback(state);66        expect(newState).toEqual({67          stories,68          selectedKind: 'abc',69          selectedStory: 'a',70        });71      });72    });73  });74  describe('selectStory', () => {75    describe('with both kind and story', () => {76      it('should select the correct story', () => {77        const clientStore = new MockClientStore();78        actions.selectStory({ clientStore }, 'bbc', 'y');79        const state = {80          stories,81          selectedKind: 'abc',82          selectedStory: 'c',83        };84        const stateUpdates = clientStore.updateCallback(state);85        expect(stateUpdates).toEqual({86          selectedKind: 'bbc',87          selectedStory: 'y',88        });89      });90    });91    describe('with just the kind', () => {92      it('should select the first of the kind', () => {93        const clientStore = new MockClientStore();94        actions.selectStory({ clientStore }, 'bbc');95        const state = {96          stories,97          selectedKind: 'abc',98          selectedStory: 'c',99        };100        const stateUpdates = clientStore.updateCallback(state);101        expect(stateUpdates).toEqual({102          selectedKind: 'bbc',103          selectedStory: 'x',104        });105      });106    });107  });108  describe('jumpToStory', () => {109    describe('has enough stories', () => {110      it('should select the next story', () => {111        const clientStore = new MockClientStore();112        actions.jumpToStory({ clientStore }, 1); // eslint-disable-line113        const state = {114          stories,115          selectedKind: 'abc',116          selectedStory: 'c',117        };118        const stateUpdates = clientStore.updateCallback(state);119        expect(stateUpdates).toEqual({120          selectedKind: 'bbc',121          selectedStory: 'x',122        });123      });124      it('should select the prev story', () => {125        const clientStore = new MockClientStore();126        actions.jumpToStory({ clientStore }, -1); // eslint-disable-line127        const state = {128          stories,129          selectedKind: 'abc',130          selectedStory: 'c',131        };132        const stateUpdates = clientStore.updateCallback(state);133        expect(stateUpdates).toEqual({134          selectedKind: 'abc',135          selectedStory: 'b',136        });137      });138    });139    describe('has not enough stories', () => {140      it('should select the current story', () => {141        const clientStore = new MockClientStore();142        actions.jumpToStory({ clientStore }, 1); // eslint-disable-line143        const state = {144          stories,145          selectedKind: 'bbc',146          selectedStory: 'z',147        };148        const stateUpdates = clientStore.updateCallback(state);149        expect(stateUpdates).toEqual({150          selectedKind: 'bbc',151          selectedStory: 'z',152        });153      });154    });155  });156  describe('setOptions', () => {157    it('should update options', () => {158      const clientStore = new MockClientStore();159      actions.setOptions({ clientStore }, { abc: 10 });160      const state = {161        uiOptions: { bbc: 50, abc: 40 },162      };163      const stateUpdates = clientStore.updateCallback(state);164      expect(stateUpdates).toEqual({165        uiOptions: { bbc: 50, abc: 10 },166      });167    });168    const provider = {169      getPanels: () => ({170        'storybook/actions/actions-panel': {171          title: 'Action logger',172        },173        'storybooks/storybook-addon-knobs': {174          title: 'Knobs',175        },176      }),177    };178    it('should update selectedAddonPanel', () => {179      const clientStore = new MockClientStore();180      actions.setOptions(181        { clientStore, provider },182        { selectedAddonPanel: 'storybooks/storybook-addon-knobs' }183      );184      const state = {185        uiOptions: {},186        selectedAddonPanel: 'storybook/actions/actions-panel',187      };188      const stateUpdates = clientStore.updateCallback(state);189      expect(stateUpdates.selectedAddonPanel).toEqual('storybooks/storybook-addon-knobs');190    });191    it('should keep current downPanel and output panel IDs', () => {192      const clientStore = new MockClientStore();193      actions.setOptions({ clientStore, provider }, { selectedAddonPanel: null });194      global.console = {195        log: jest.fn(),196        group: jest.fn(),197        groupEnd: jest.fn(),198      };199      const logger = console;200      const state = {201        uiOptions: {},202        selectedAddonPanel: 'storybook/actions/actions-panel',203      };204      const stateUpdates = clientStore.updateCallback(state);205      expect(stateUpdates.selectedAddonPanel).toEqual('storybook/actions/actions-panel');206      expect(logger.log.mock.calls).toEqual([207        ['storybook/actions/actions-panel (Action logger)'],208        ['storybooks/storybook-addon-knobs (Knobs)'],209      ]);210    });211    it('should only update options for the key already defined', () => {212      const clientStore = new MockClientStore();213      actions.setOptions({ clientStore }, { abc: 10, notGoingToState: 20 });214      const state = {215        uiOptions: { bbc: 50, abc: 40 },216      };217      const stateUpdates = clientStore.updateCallback(state);218      expect(stateUpdates).toEqual({219        uiOptions: { bbc: 50, abc: 10 },220      });221    });222  });223  describe('setQueryParams', () => {224    it('shodul update query params', () => {225      const clientStore = new MockClientStore();226      actions.setQueryParams({ clientStore }, { abc: 'aaa', cnn: 'ccc' });227      const state = {228        customQueryParams: { bbc: 'bbb', abc: 'sshd' },229      };230      const stateUpdates = clientStore.updateCallback(state);231      expect(stateUpdates).toEqual({232        customQueryParams: { bbc: 'bbb', abc: 'aaa', cnn: 'ccc' },233      });234    });235    it('should delete the param if it is null', () => {236      const clientStore = new MockClientStore();237      actions.setQueryParams({ clientStore }, { abc: null, bbc: 'ccc' });238      const state = {239        customQueryParams: { bbc: 'bbb', abc: 'sshd' },240      };241      const stateUpdates = clientStore.updateCallback(state);242      expect(stateUpdates).toEqual({243        customQueryParams: { bbc: 'ccc' },244      });245    });246  });...hotUpdate.js
Source:hotUpdate.js  
1var Constants = require('../config/Constants')2var TAG = 'hotUpdata.js'3cc.Class({4    initHotUpdate(manifestUrl,verifycallback,updateCallBack){5        var self = this6        self.m_manifestUrl = manifestUrl7        self.m_updateCallBack = updateCallBack8        self._storagePath = ((jsb.fileUtils ? jsb.fileUtils.getWritablePath() : '/') + 'remote-assets');9        self._am = new jsb.AssetsManager('', self._storagePath, self.versionCompareHandle.bind(self));10        self._am.setVerifyCallback(function (filePath, asset) {11            if(verifycallback){12                verifycallback(filePath,asset)13            }14            return true;15        });16        if (cc.sys.os === cc.sys.OS_ANDROID) {17            self._am.setMaxConcurrentTask(2);18        }19    },20    updateCallBack(code,data) {21        var self = this22        console.log(TAG,'updataCallBack',code)23        switch (code) {24            case Constants.UPDATE_CODE.OK:25                self.closeUpdateCallBack()26                break;27            case Constants.UPDATE_CODE.HOT_UPDATE_ERR:28                self.closeUpdateCallBack()29                break;30            case Constants.UPDATE_CODE.LOCAL_MANIFEST_LOAD_ERR:31                self.closeUpdateCallBack()32                break;33            case Constants.UPDATE_CODE.UPDATE_FINISHED:34                self.closeUpdateCallBack()35                self.gameRestart()36                break;37        }38        if(self.m_updateCallBack){39            self.m_updateCallBack(code,data)40        }41    },42    versionCompareHandle(versionA, versionB){43        var vA = versionA.split('.');44        var vB = versionB.split('.');45        for (var i = 0; i < vA.length; ++i) {46            var a = parseInt(vA[i]);47            var b = parseInt(vB[i] || 0);48            if (a === b) {49                continue;50            }51            else {52                return a - b;53            }54        }55        if (vB.length > vA.length) {56            return -1;57        }58        else {59            return 0;60        }61    },62    checkUpdata() {63        var self = this64        if (self._am.getState() === jsb.AssetsManager.State.UNINITED) {65            var url = self.m_manifestUrl.nativeUrl;66            if (cc.loader.md5Pipe) {67                url = cc.loader.md5Pipe.transformURL(url);68            }69            self._am.loadLocalManifest(url);70        }71        if (!self._am.getLocalManifest() || !self._am.getLocalManifest().isLoaded()) {72            if(self.updateCallBack){73                self.updateCallBack(Constants.UPDATE_CODE.LOCAL_MANIFEST_LOAD_ERR)74            }75            return76        }77        self._am.setEventCallback(self.checkCb.bind(self));78        self._am.checkUpdate();79    },80    checkCb(event) {81        var self = this82        switch (event.getEventCode()) {83            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST://"No local manifest file found, hot update skipped."84                if(self.updateCallBack){85                    self.updateCallBack(Constants.UPDATE_CODE.CHECK_UPDATE_ERR)86                }87                break;88            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:89            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST://"Fail to download manifest file, hot update skipped."90                if(self.updateCallBack){91                    self.updateCallBack(Constants.UPDATE_CODE.CHECK_UPDATE_ERR)92                }93                break;94            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE://"Already up to date with the latest remote version."95                if(self.updateCallBack){96                    self.updateCallBack(Constants.UPDATE_CODE.OK)97                }98                break;99            case jsb.EventAssetsManager.NEW_VERSION_FOUND://'New version found, start try to update.'100                if(self.updateCallBack){101                    self.updateCallBack(Constants.UPDATE_CODE.NEW_VERSION_FOUND)102                }103                break;104            default:105                return;106        }107        self._am.setEventCallback(null);108    },109    hotUpdate() {110        var self = this111        if (self._am) {112            self._am.setEventCallback(self.updateCb.bind(self));113            if (self._am.getState() === jsb.AssetsManager.State.UNINITED) {114                var url = self.m_manifestUrl.nativeUrl;115                if (cc.loader.md5Pipe) {116                    url = cc.loader.md5Pipe.transformURL(url);117                }118                self._am.loadLocalManifest(url);119            }120            self._am.update();121        }122    },123    updateCb(event) {124        var self = this125        switch (event.getEventCode()) {126            case jsb.EventAssetsManager.ERROR_NO_LOCAL_MANIFEST://'No local manifest file found, hot update skipped.'127                if(self.updateCallBack){128                    self.updateCallBack(Constants.UPDATE_CODE.LOCAL_MANIFEST_LOAD_ERR)129                }130                break;131            case jsb.EventAssetsManager.UPDATE_PROGRESSION:132                if(self.updateCallBack){133                    self.updateCallBack(Constants.UPDATE_CODE.UPDATEING_ASSETS,event)134                }135                break;136            case jsb.EventAssetsManager.ERROR_DOWNLOAD_MANIFEST:137            case jsb.EventAssetsManager.ERROR_PARSE_MANIFEST://'Fail to download manifest file, hot update skipped.'138                if(self.updateCallBack){139                    self.updateCallBack(Constants.UPDATE_CODE.HOT_UPDATE_ERR)140                }141                break;142            case jsb.EventAssetsManager.ALREADY_UP_TO_DATE://'Already up to date with the latest remote version.'143                if(self.updateCallBack){144                    self.updateCallBack(Constants.UPDATE_CODE.OK)145                }146                break;147            case jsb.EventAssetsManager.UPDATE_FINISHED://Update finished. + event.getMessage()148                if(self.updateCallBack){149                    self.updateCallBack(Constants.UPDATE_CODE.UPDATE_FINISHED)150                }151                break;152            case jsb.EventAssetsManager.UPDATE_FAILED://'Update failed. ' + event.getMessage()153                if(self.updateCallBack){154                    self.updateCallBack(Constants.UPDATE_CODE.UPDATE_FAILED)155                }156                break;157            case jsb.EventAssetsManager.ERROR_UPDATING://'Asset update error: ' + event.getAssetId() + ', ' + event.getMessage()158                if(self.updateCallBack){159                    self.updateCallBack(Constants.UPDATE_CODE.ASSET_UPDATE_ERR)160                }161                break;162            case jsb.EventAssetsManager.ERROR_DECOMPRESS:163                if(self.updateCallBack){164                    self.updateCallBack(Constants.UPDATE_CODE.DECOMPRESS_ERR)165                }166                break;167            default:168                break;169        }170    },171    closeUpdateCallBack(){172        var self = this173        self._am.setEventCallback(null);174    },175    gameRestart:function(){176        var self = this177        var searchPaths = jsb.fileUtils.getSearchPaths();178        var newPaths = self._am.getLocalManifest().getSearchPaths();179        Array.prototype.unshift.apply(searchPaths, newPaths);180        G.ioUtil.set(Constants.LOCALLSTORAGEKEY.HOTUPDATESEARCHPATHS,searchPaths)181        jsb.fileUtils.setSearchPaths(searchPaths);182        cc.audioEngine.stopAll();183        cc.game.restart();184    },185    getLocalVersion:function(){186        var self = this187        var manifest = self._am.getLocalManifest();188        return manifest.getVersion();189    },190    onDestroy() {191        var self = this192        self.closeUpdateCallBack()193    }...deploy.render.js
Source:deploy.render.js  
1;2var renderWaitProcess = function (element) {3    React.render(4        <WaitProgressComponent />,5        element6    );7};8var renderRegisterForm = function (element, data) {9    React.render(10        <RegisterFormComponent data={data}/>,11        element12    );13};14var renderSideNavBar = function (element, menuData, path) {15    //console.log(location.pathname);16    var hasActive = function (data) {17        for (var i in data) {18            if (data[i].url == path) {19                data[i].active = true;20                return true;21            }22            if (data[i].children != undefined) {23                if (hasActive(data[i].children)) {24                    return true;25                }26            }27        }28        return false;29    }30    hasActive(menuData);31    React.render(32        <SideBarNavComponent data={menuData}/>,33        element34    );35};36var renderRoleForm = function (element, callback) {37    React.render(<RoleAddFormComponent reloadCallback={callback}/>, element);38};39var renderRoleModal = function (element, data, updateCallback) {40    $(element).html("");41    var c = React.render(<RoleEditModalComponent data={data} updateCallback={updateCallback}/>, element);42    c.handleToggle();43};44var renderHostTypeCatalog = function (element, type, data, updateCallback) {45    $(element).html("");46    var c = React.render(<RoleEditModalComponent data={data} updateCallback={updateCallback}/>, element);47    c.handleToggle();48};49var renderHostTypeCatalogModal = function (element, type, data, updateCallback) {50    $(element).html("");51    var c = React.render(<HostTypeCatalogEditComponent id={data.id} type={type} data={data} updateCallback={updateCallback}/>, element);52    c.handleToggle();53};54var renderSiteModal = function (element, type, data, updateCallback) {55    $(element).html("");56    var c = React.render(<SiteEditComponent id={data.id} type={type} data={data} updateCallback={updateCallback}/>, element);57    c.handleToggle();58};59var renderRolePermissionModal = function (element, data, updateCallback) {60    $(element).html("");61    var c = React.render(<RolePermissionModal data={data} updateCallback={updateCallback}/>, element);62    c.handleToggle();63};64var renderUserRoleAddModal = function (element, data, updateCallback) {65    $(element).html("");66    var c = React.render(<UserRoleAddModal data={data} updateCallback={updateCallback}/>, element);67    c.handleToggle();68};69var renderSiteConfig = function (element, data) {70    React.render(<SiteConfigComponent data={data} />, element);71};72var renderSiteDeployConfig = function (element, data) {73    React.render(<SiteDeployConfigComponent data={data} />, element);74};75var renderSiteHostType = function (element, type, data, updateCallback) {76    $(element).html("");77    var c = React.render(<SiteHostTypeEditModal data={data} type={type} updateCallback={updateCallback} />, element);78    c.handleToggle();79};80var renderSiteHosts = function (element, type, data, updateCallback) {81    $(element).html("");82    var c = React.render(<SiteHostEditModal data={data} type={type} updateCallback={updateCallback} />, element);83    c.handleToggle();84};85var renderNewBuildForm = function (element, data, updateCallback) {86    $(element).html("");87    var c = React.render(<NewBuildForm data={data} updateCallback={updateCallback} />, element);88};89var renderSystemConfigureForm = function (element) {90    React.render(<BasicConfigureForm />, element);91};92var renderJobInfo = function (element, jobId, type) {93    $(element).html("");94    var c = React.render(<JobInfoTabContent jobId={jobId} jobType={type}/>, element);95    return c.timeoutEvent;96};97var renderDeployJob = function (element, siteId, type, toDeploy) {98    $(element).html("");99    var c = React.render(<DeployJobForm siteId={siteId} deployType={type} toDeploy={toDeploy}/>, element);100};101var renderWatchButton = function (element, siteId, isWatching) {102    $(element).html("");103    React.render(<WatchComponent siteId={siteId} isWatching={isWatching}/>, element);104};105var renderSiteHostsMany = function (element, data, updateCallback) {106    $(element).html("");107    var c = React.render(<AddSiteHostsMany data={data} updateCallback={updateCallback} />, element); };108//var marked = require('marked');109var renderDashboard = function (element, data) {110    var html = marked(data);111    $(element).html(html);112};...checklisthandler.js
Source:checklisthandler.js  
...16			this.products = JSON.parse(cachedUserProducts);17			this.products = this.sort();18			19			if(updateCallback)20				updateCallback(this.commands.CACHELOADED);21			22			if(online)23			{24				this.onlineLoad(function(success) {25					if(success) {26						self.products = self.sort();27						28						if(updateCallback)29							updateCallback(self.commands.ONLINELOADEDAFTERCACHE);30					}31					else32					{33						if(updateCallback)34							updateCallback(self.commands.ONLINEFAILEDAFTERCACHE);35					}36				});37			}38		}39		else40		{41			if(online)42			{43				this.onlineLoad(function(success) {44					if(success) {45						self.products = self.sort();46						47						if(updateCallback)48							updateCallback(self.commands.ONLINEONLYLOADED);49					}50					else51					{52						if(updateCallback)53							updateCallback(self.commands.ONLINEONLYFAILED);54					}55				});56			}57			else58			{59				if(updateCallback)60					updateCallback(self.commands.ONLINEONLYFAILED);61			}62		}63	};64	65	this.onlineLoad = function(updateCallback) {66		$.ajax({67			type: "get",68			dataType: "json",69			url: host + "services/ajax/user/products?token=" + token,70			success: function(data) {71				var response = data;72				73				if(response.success == true)74				{75					self.products = response.records;76					if(updateCallback)77						updateCallback(true);78				}79				else80				{81					if(updateCallback)82						updateCallback(false);83				}84			},85			error: function()86			{87				if(updateCallback)88					updateCallback(false);89			}90		});91	};92	93	this.getProduct = function(id) {94		var item = _.find(this.products, function(i) {95			if(i._id == id)96				return true;97		});98		99		return item;100	};101	102	this.sort = function() {
...AnimationTrackPlayback.spec.js
Source:AnimationTrackPlayback.spec.js  
1import AnimationTrack from "./AnimationTrack";2import AnimationTrackPlayback from "./AnimationTrackPlayback";3import TransitionFunctions from "../TransitionFunctions";4function makeSingleKeyTrack() {5    const t = new AnimationTrack(["a"]);6    t.addKey(0, [7]);7    return t;8}9function makeTwoKeyTransitionTrack() {10    const t = new AnimationTrack(["a"]);11    t.addKey(0, [5]);12    t.addKey(1, [3]);13    t.addTransition(0, TransitionFunctions.Linear);14    return t;15}16test("calling advance(0) twice results in no change", () => {17    const t = makeTwoKeyTransitionTrack();18    const updateCallback = jest.fn();19    const playback = new AnimationTrackPlayback(t, updateCallback, null);20    expect(playback.position).toBe(0);21    playback.advance(0);22    expect(updateCallback).toHaveBeenCalledTimes(1);23    expect(updateCallback).toHaveBeenLastCalledWith(5);24    expect(playback.position).toBe(0);25    playback.advance(0);26    expect(updateCallback).toHaveBeenCalledTimes(2);27    expect(updateCallback).toHaveBeenLastCalledWith(5);28    expect(playback.position).toBe(0);29});30test("calling advance(0) results in no change", () => {31    const t = makeTwoKeyTransitionTrack();32    const updateCallback = jest.fn();33    const playback = new AnimationTrackPlayback(t, updateCallback, null);34    expect(playback.position).toBe(0);35    playback.advance(0);36    expect(playback.position).toBe(0);37    expect(updateCallback).toHaveBeenCalledTimes(1);38    expect(updateCallback).toHaveBeenLastCalledWith(5);39});40test("advancing past last key results in last key being held", () => {41    const t = makeTwoKeyTransitionTrack();42    const updateCallback = jest.fn();43    const playback = new AnimationTrackPlayback(t, updateCallback, null);44    playback.advance(2);45    expect(updateCallback).toHaveBeenLastCalledWith(3);46});47test("playback starts at position 0 by default", () => {48    const t = makeSingleKeyTrack();49    const updateCallback = jest.fn();50    const playback = new AnimationTrackPlayback(t, updateCallback, null);51    expect(playback.position).toBe(0);52});53test("single static key playback works", () => {54    const t = makeSingleKeyTrack();55    const updateCallback = jest.fn();56    const playback = new AnimationTrackPlayback(t, updateCallback, null);57    playback.advance(1);58    expect(updateCallback).toHaveBeenCalledTimes(1);59    expect(updateCallback).toHaveBeenLastCalledWith(7);...assignCallback.js
Source:assignCallback.js  
1let callbacks = {2    MESSAGE_CREATECallback: null,3    MESSAGE_DELETECallback: null,4    MESSAGE_UPDATECallback: null,5    CHANNEL_CREATECallback: null,6    CHANNEL_DELETECallback: null,7    WEBHOOKS_UPDATECallback: null,8    VOICE_SERVER_UPDATECallback: null,9    VOICE_STATE_UPDATECallback: null,10    USER_UPDATECallback: null,11    TYPING_STARTCallback: null,12    STAGE_INSTANCE_UPDATECallback: null,13    STAGE_INSTANCE_DELETECallback: null,14    STAGE_INSTANCE_CREATECallback: null,15    PRESENCE_UPDATECallback: null,16    MESSAGE_REACTION_ADDCallback: null,17    GUILD_ROLE_CREATECallback: null,18    GUILD_ROLE_DELETECallback: null,19    MESSAGE_REACTION_REMOVE_EMOJICallback: null,20    MESSAGE_REACTION_REMOVE_ALLCallback: null,21    MESSAGE_REACTION_REMOVECallback: null,22    MESSAGE_REACTION_ADDCallback: null,23    MESSAGE_DELETE_BULKCallback: null,24    INVITE_DELETECallback: null,25    INVITE_CREATECallback: null,26    INTERACTION_CREATECallback: null,27    INTEGRATION_DELETECallback: null,28    INTEGRATION_CREATECallback: null,29    INTEGRATION_UPDATECallback: null,30    GUILD_ROLE_UPDATECallback: null,31    GUILD_MEMBERS_CHUNKCallback: null,32    GUILD_MEMBER_UPDATECallback: null,33    GUILD_MEMBER_REMOVECallback: null,34    GUILD_MEMBER_ADDCallback: null,35    GUILD_INTEGRATIONS_UPDATECallback: null,36    GUILD_STICKERS_UPDATECallback: null,37    GUILD_EMOJIS_UPDATECallback: null,38    GUILD_BAN_REMOVECallback: null,39    GUILD_BAN_ADDCallback: null,40    GUILD_DELETECallback: null,41    GUILD_UPDATECallback: null,42    GUILD_CREATECallback: null,43    THREAD_MEMBERS_UPDATECallback: null,44    THREAD_MEMBER_UPDATECallback: null,45    THREAD_LIST_SYNCCallback: null,46    THREAD_DELETECallback: null,47    THREAD_UPDATECallback: null,48    THREAD_CREATECallback: null,49    CHANNEL_PINS_UPDATECallback: null,50    CHANNEL_UPDATECallback: null,51    INVALID_SESSIONCallback: null,52    RECONNECTCallback: null,53    RESUMEDCallback: null,54    READYCallback: null,55    HELLOCallback: null,56}57module.exports = { 58    callbacks...window-scroll-model.js
Source:window-scroll-model.js  
...3    'jquery'4], function(Backbone, $) {5    var $body = $(document.body);6    var $window = $(window);7    function updateCallback() {8        this.set({9            innerHeight: $body.innerHeight(),10            scrollTop: $body.scrollTop(),11            scrollHeight: $body.prop('scrollHeight'),12            top: 0,13            bottom: $window.innerHeight()14        });15    }16    // Tracks window scroll parameters17    return Backbone.Model.extend({18        initialize: function() {19            this.updateCallback = updateCallback.bind(this);20            $window21                .on('scroll', this.updateCallback)22                .on('resize', this.updateCallback);23            this.updateCallback();24        },25        shutdown: function() {26            $window27                .off('scroll', this.updateCallback)28                .off('resize', this.updateCallback);29        }30    });...Using AI Code Generation
1const { chromium } = require('playwright');2const {updateCallback} = require('playwright/lib/server/browserType');3(async () => {4  const browser = await chromium.launch({headless: false});5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: `example.png` });8  await browser.close();9})();10const { updateCallback } = require('./browserType');11updateCallback(async (browserType, launchOptions) => {12  if (browserType.name() === 'chromium') {13    launchOptions.args = launchOptions.args || [];14    launchOptions.args.push('--window-size=1920,1080');15  }16});17const { chromium } = require('playwright');18(async () => {19  const browser = await chromium.launch({headless: false, args: ['--window-size=1920,1080']});20  const context = await browser.newContext();21  const page = await context.newPage();22  await page.screenshot({ path: `example.png` });23  await browser.close();24})();Using AI Code Generation
1const playwright = require('playwright');2const { updateCallback } = require('playwright/lib/server/browserContext');3const browser = await playwright.chromium.launch();4const context = await browser.newContext();5await updateCallback(context, 'page', (page) => {6  page.on('request', request => {7    console.log(request.url());8  });9});10const page = await context.newPage();11await browser.close();12module.exports = {13  use: {14    viewport: { width: 1280, height: 720 },15  },16};17module.exports = {18};19module.exports = {20  use: {21    viewport: { width: 1280, height: 720 },22  },23};24module.exports = {25};26module.exports = {27  use: {28    viewport: { width: 1280, height: 720 },29  },30};31module.exports = {32};33module.exports = {34  use: {35    viewport: { width: 1280, height: 720 },36  },37};38module.exports = {39};40module.exports = {41  use: {42    viewport: { width: 1280, height: 720 },43  },44};45module.exports = {46};47module.exports = {48  use: {49    viewport: { width: 1280, height: 720 },50  },51};Using AI Code Generation
1const playwright = require('playwright');2const context = await playwright.chromium.launch({3});4const page = await context.newPage();5await page.evaluate(() => {6    window.__updateCallback('test')7});8chrome.runtime.onMessage.addListener(9    function (request, sender, sendResponse) {10        console.log(request);11    }12);Using AI Code Generation
1const { chromium } = require('playwright');2const { updateCallback } = require('playwright/internal/inspector');3(async () => {4  const browser = await chromium.launch();5  const context = await browser.newContext();6  const page = await context.newPage();7  await page.screenshot({ path: 'google.png' });8  await browser.close();9})();Using AI Code Generation
1const { updateCallback } = require('playwright/lib/protocol/protocol');2updateCallback('Network', 'requestWillBeSent', (params) => {3    console.log(params.request.url);4});5const { test, expect } = require('@playwright/test');6test('test', async ({ page }) => {7    await page.click('text=Get started');8    await page.click('text=Docs');9    await page.click('text=API');Using AI Code Generation
1async function updateCallback() {2  const { updateCallback } = require('playwright/lib/server/supplements/recorder/recorderSupplement');3  const callback = await updateCallback();4  console.log(callback);5}6updateCallback();7error: Uncaught (in promise) TypeError: Cannot read property 'updateCallback' of undefined8at async ModuleJob.run (deno:runtime/js/40_testing.js:225:23)9at async TestDefinition.run (deno:runtime/js/40_testing.js:106:23)10at async Object.runTests (deno:runtime/js/40_testing.js:400:25)Using AI Code Generation
1const { updateCallback } = require('playwright/lib/server/supplements/recorder/recorderSupplement');2updateCallback((event, data) => {3  console.log(event, data);4});5const { chromium } = require('playwright');6(async () => {7  const browser = await chromium.launch({ headless: true });8  const context = await browser.newContext();9  const page = await context.newPage();Using AI Code Generation
1const { updateCallback } = require('playwright/lib/server/browserContext');2updateCallback((context, route, request) => {3  console.log('request intercepted', context, route, request);4});5const { test, expect } = require('@playwright/test');6test('test', async ({ page }) => {7  await page.route('**/*', (route) => {8    route.continue();9  });10  await expect(page).toHaveText('Example Domain');11});Using AI Code Generation
1async function updateContext() {2    const context = await browser.newContext({3        recordVideo: {4            size: { width: 1280, height: 720 }5        }6    });7    const page = await context.newPage();8    await context.close();9}10async function updateContext() {11    const context = await browser.newContext({12        recordVideo: {13            size: { width: 1280, height: 720 }14        }15    });16    const page = await context.newPage();17    await context.close();18}19async function updateContext() {20    const context = await browser.newContext({21        recordVideo: {22            size: { width: 1280, height: 720 }23        }24    });25    const page = await context.newPage();26    await context.close();27}28async function updateContext() {29    const context = await browser.newContext({30        recordVideo: {31            size: { width: 1280, height: 720 }32        }33    });34    const page = await context.newPage();35    await context.close();36}37async function updateContext() {38    const context = await browser.newContext({39        recordVideo: {40            size: { width: 1280, height: 720 }41        }42    });43    const page = await context.newPage();44    await context.close();45}46async function updateContext() {47    const context = await browser.newContext({48        recordVideo: {49            size: { width: 1280Using AI Code Generation
1const { test } = use('Test/Suite')('Example')2const { chromium } = require('playwright')3const { updateCallback } = require('playwright/lib/runner/Test')4const { saveTestResult } = require('playwright/lib/runner/TestResult')5const { TestStatus } = require('playwright/lib/runner/TestResult')6const { Test } = require('playwright/lib/runner/Test')7const { TestResult } = require('playwright/lib/runner/TestResult')8const { TestResultOutput } = require('playwright/lib/runner/TestResultOutput')9const { TestResultOutputStatus } = require('playwright/lib/runner/TestResultOutputStatus')10const { TestResultError } = require('playwright/lib/runner/TestResultError')11const { TestResultErrorStatus } = require('playwright/lib/runner/TestResultErrorStatus')12const { TestResultErrorAction } = require('playwright/lib/runner/TestResultErrorAction')13const { TestResultErrorLocation } = require('playwright/lib/runner/TestResultErrorLocation')14const { TestResultErrorLocationType } = require('playwright/lib/runner/TestResultErrorLocationType')15const { TestResultErrorLocationValue } = require('playwright/lib/runner/TestResultErrorLocationValue')16const { TestResultErrorLocationValueStatus } = require('playwright/lib/runner/TestResultErrorLocationValueStatus')17const { TestResultErrorLocationValueAction } = require('playwright/lib/runner/TestResultErrorLocationValueAction')18const { TestResultErrorLocationValueActionStatus } = require('playwright/lib/runner/TestResultErrorLocationValueActionStatus')19const { TestResultErrorLocationValueActionValue } = require('playwright/lib/runner/TestResultErrorLocationValueActionValue')20const { TestResultErrorLocationValueActionValueStatus } = require('playwright/lib/runner/TestResultErrorLocationValueActionValueStatus')21const { TestResultErrorLocationValueActionValueStatusValue } = require('playwright/lib/runner/TestResultErrorLocationValueActionValueStatusValue')22const { TestResultErrorLocationValueActionValueStatusValueStatus } = require('playwright/lib/runner/TestResultErrorLocationValueActionValueStatusValueStatus')23const { TestResultErrorLocationValueActionValueStatusValueStatusValue } = require('playwright/lib/runner/TestResultErrorLocationValueActionValueStatusValueStatusValue')LambdaTest’s Playwright tutorial will give you a broader idea about the Playwright automation framework, its unique features, and use cases with examples to exceed your understanding of Playwright testing. This tutorial will give A to Z guidance, from installing the Playwright framework to some best practices and advanced concepts.
Get 100 minutes of automation test minutes FREE!!
