Best JavaScript code snippet using testcafe
nw-winstate.js
Source:nw-winstate.js  
...112      win.resizeTo(winState.width, winState.height);113      win.moveTo(winState.x, winState.y);114    }115  }116  function saveWindowState() {117    dumpWindowState();118    localStorage.windowState = JSON.stringify(winState);119  }120  window.saveWindowState = saveWindowState;121  initWindowState();122  win.on('maximize', function () {123    isMaximizationEvent = true;124    currWinMode = 'maximized';125    saveWindowState();126  });127  win.on('unmaximize', function () {128    currWinMode = 'normal';129    restoreWindowState();130    saveWindowState();131  });132  win.on('minimize', function () {133    currWinMode = 'minimized';134    saveWindowState();135  });136  win.on('restore', function () {137    currWinMode = 'normal';138    saveWindowState();139  });140  win.window.addEventListener('resize', function () {141    // resize event is fired many times on one resize action,142    // this hack with setTiemout forces it to fire only once143    clearTimeout(resizeTimeout);144    resizeTimeout = setTimeout(function () {145      // on MacOS you can resize maximized window, so it's no longer maximized146      if (isMaximizationEvent) {147        // first resize after maximization event should be ignored148        isMaximizationEvent = false;149      } else {150        if (currWinMode === 'maximized') {151          currWinMode = 'normal';152        }153      }154      // there is no deltaHeight yet, calculate it and adjust window size155      if (deltaHeight !== 'disabled' && deltaHeight === false) {156        deltaHeight = win.height - winState.height;157        // set correct size158        if (deltaHeight !== 0) {159          win.resizeTo(winState.width, win.height - deltaHeight);160        }161      }162      saveWindowState();163    }, 500);164  }, false);165  win.on('close', function () {166    try {167      saveWindowState();168    } catch(err) {169      console.log("winstateError: " + err);170    }171    this.close(true);172  });...WindowState.js
Source:WindowState.js  
...76    function saveState(win) {77        logg.info(state)78        if (win) updateState(win)79        setWindowState(state)80        saveWindowState()81    }82    function stateHandler() {83        updateState()84    }85    function closedHandler() {86        unmanage()87        saveState()88    }89    function manage(win) {90        if (state.isMinimized) {91            win.minimize()92        }93        if (state.isMaximized) {94            win.maximize()95        }96        if (state.isFullScreen) {97            win.setFullScreen(true)98        }99        win.on('resize', stateHandler)100        win.on('move', stateHandler)101        win.on('close', stateHandler)102        win.on('closed', closedHandler)103        winRef = win104    }105    function unmanage() {106        if (winRef) {107            winRef.removeListener('resize', stateHandler)108            winRef.removeListener('move', stateHandler)109            winRef.removeListener('close', stateHandler)110            winRef.removeListener('closed', closedHandler)111            winRef = null112        }113    }114    state = getWindowState()115    validateState()116    state = Object.assign({117        width: config.width || 800,118        height: config.height || 600119    }, state)120    return {121        get x() { return state.x },122        get y() { return state.y },123        get width() { return state.width },124        get height() { return state.height },125        get displayBounds() { return state.displayBounds },126        get isMaximized() { return state.isMaximized },127        get isMinimized() { return state.isMinimized },128        get isFullScreen() { return state.isFullScreen },129        saveState,130        unmanage,131        manage,132        resetStateToDefault133    }134}135/* =====================   Window Properties   ===================== */136const DEFAULT_WINDOW_CONFIG = {137    x: 0,138    y: 0,139    width: 1280,140    height: 720,141    isMaximized: false,142    isFullScreen: false143}144let windowStateConfigPath = path.join(ConfigManager.getLauncherDirectory(), 'window-config.json')145let windowConfig = null146const saveWindowState = function () {147    fs.writeFileSync(windowStateConfigPath, JSON.stringify(windowConfig, null, 4), 'UTF-8')148}149const loadWindowState = function () {150    let loaded = false151    if (!fs.existsSync(windowStateConfigPath)) {152        fs.mkdirSync(path.join(windowStateConfigPath, '..'), { recursive: true },);153        loaded = true154        windowConfig = DEFAULT_WINDOW_CONFIG155        saveWindowState()156    }157    if (!loaded) {158        try {159            windowConfig = JSON.parse(fs.readFileSync(windowStateConfigPath, 'UTF-8')) 160        } catch (err) {161            logg.error(err)162            logg.log('Configuration file contains malformed JSON or is corrupt.')163            logg.log('Generating a new configuration file.')164            fs.mkdirSync(path.join(windowStateConfigPath, '..'), { recursive: true });165            windowConfig = DEFAULT_WINDOW_CONFIG166            saveWindowState()167        }168    }169    logg.log('Load window config - success')170}171const getWindowState = function () {172    return windowConfig173}174const setWindowState = function (state) {175    windowConfig = state...mainWindow.js
Source:mainWindow.js  
...3// See LICENSE.txt for license information.4import fs from 'fs';5import path from 'path';6import {app, BrowserWindow} from 'electron';7function saveWindowState(file, window) {8  var windowState = window.getBounds();9  windowState.maximized = window.isMaximized();10  windowState.fullscreen = window.isFullScreen();11  try {12    fs.writeFileSync(file, JSON.stringify(windowState));13  } catch (e) {14    // [Linux] error happens only when the window state is changed before the config dir is created.15    console.log(e);16  }17}18function createMainWindow(config, options) {19  const defaultWindowWidth = 1000;20  const defaultWindowHeight = 700;21  const minimumWindowWidth = 400;22  const minimumWindowHeight = 240;23  // Create the browser window.24  const boundsInfoPath = path.join(app.getPath('userData'), 'bounds-info.json');25  var windowOptions;26  try {27    windowOptions = JSON.parse(fs.readFileSync(boundsInfoPath, 'utf-8'));28  } catch (e) {29    // Follow Electron's defaults, except for window dimensions which targets 1024x768 screen resolution.30    windowOptions = {width: defaultWindowWidth, height: defaultWindowHeight};31  }32  if (process.platform === 'linux') {33    windowOptions.icon = options.linuxAppIcon;34  }35  Object.assign(windowOptions, {36    title: app.getName(),37    fullscreenable: true,38    show: false,39    minWidth: minimumWindowWidth,40    minHeight: minimumWindowHeight,41  });42  const mainWindow = new BrowserWindow(windowOptions);43  mainWindow.deeplinkingUrl = options.deeplinkingUrl;44  const indexURL = global.isDev ? 'http://localhost:8080/browser/index.html' : `file://${app.getAppPath()}/browser/index.html`;45  mainWindow.loadURL(indexURL);46  // This section should be called after loadURL() #57047  if (options.hideOnStartup) {48    if (windowOptions.maximized) {49      mainWindow.maximize();50    }51    // on MacOS, the window is already hidden until 'ready-to-show'52    if (process.platform !== 'darwin') {53      mainWindow.minimize();54    }55  } else if (windowOptions.maximized) {56    mainWindow.maximize();57  }58  mainWindow.webContents.on('will-attach-webview', (event, webPreferences) => {59    webPreferences.nodeIntegration = false;60  });61  mainWindow.once('ready-to-show', () => {62    mainWindow.webContents.setZoomLevel(0);63    if (process.platform !== 'darwin') {64      mainWindow.show();65    } else if (options.hideOnStartup !== true) {66      mainWindow.show();67    }68  });69  // App should save bounds when a window is closed.70  // However, 'close' is not fired in some situations(shutdown, ctrl+c)71  // because main process is killed in such situations.72  // 'blur' event was effective in order to avoid this.73  // Ideally, app should detect that OS is shutting down.74  mainWindow.on('blur', () => {75    saveWindowState(boundsInfoPath, mainWindow);76    mainWindow.blurWebView();77  });78  mainWindow.on('close', (event) => {79    if (global.willAppQuit) { // when [Ctrl|Cmd]+Q80      saveWindowState(boundsInfoPath, mainWindow);81    } else { // Minimize or hide the window for close button.82      event.preventDefault();83      function hideWindow(window) {84        window.blur(); // To move focus to the next top-level window in Windows85        window.hide();86      }87      switch (process.platform) {88      case 'win32':89        hideWindow(mainWindow);90        break;91      case 'linux':92        if (config.minimizeToTray) {93          hideWindow(mainWindow);94        } else {...ConfigService.js
Source:ConfigService.js  
1const BITFLUX_STOCK_AMOUNT = 1200;2const BITFLUX_INITIAL_PROPORTION = 112 / BITFLUX_STOCK_AMOUNT; // 112 days == ~4 months3const CLOSED_SIDEBAR_WIDTH = 50;4const SIDETAB_TOP_HEIGHT = 50;5const TEAROUT_WINDOW_OFFSET = [CLOSED_SIDEBAR_WIDTH, SIDETAB_TOP_HEIGHT];6const TEAROUT_WINDOW_OFFSET_COMPACT = [0, 34];7const TEAROUT_CARD_WIDTH = 230;8const TEAROUT_CARD_DIMENSIONS = [TEAROUT_CARD_WIDTH, 110];9const COMPACT_WINDOW_DIMENSIONS = [TEAROUT_CARD_WIDTH, 500];10const DEFAULT_WINDOW_DIMENSIONS = [1280, 720];11const DEFAULT_WINDOW_MIN_DIMENSIONS = [918, 510];12const DEFAULT_STOCKS = ['AAPL', 'MSFT', 'TITN', 'TSLA'];13const allowContextMenu = process.env.NODE_ENV !== 'production';14/**15 * Stores common configuration for the application.16 */17class ConfigService {18    createName() {19        return `window${Math.floor(Math.random() * 1000) + Math.ceil(Math.random() * 999)}`;20    }21    getConfig(name, overrides) {22        const sharedConfig = {23            name: name || this.createName(),24            contextMenu: allowContextMenu,25            autoShow: false,26            frame: false,27            shadow: false,28            resizeRegion: {29                size: 7,30                topLeftCorner: 14,31                topRightCorner: 14,32                bottomRightCorner: 14,33                bottomLeftCorner: 1434            }35        };36        Object.keys(sharedConfig).forEach((key) => {37            if (overrides[key] === undefined) {38                overrides[key] = sharedConfig[key]; // eslint-disable-line no-param-reassign39            }40        });41        return overrides;42    }43    getWindowConfig(name) {44        return this.getConfig(name, {45            showTaskbarIcon: true,46            saveWindowState: true,47            url: 'index.html',48            resizable: true,49            maximizable: true,50            minWidth: DEFAULT_WINDOW_MIN_DIMENSIONS[0],51            minHeight: DEFAULT_WINDOW_MIN_DIMENSIONS[1],52            defaultWidth: DEFAULT_WINDOW_DIMENSIONS[0],53            defaultHeight: DEFAULT_WINDOW_DIMENSIONS[1]54        });55    }56    getCompactWindowConfig(name) {57        return this.getConfig(name, {58            showTaskbarIcon: true,59            saveWindowState: true,60            url: 'index.html',61            resizable: false,62            maximizable: false,63            minWidth: COMPACT_WINDOW_DIMENSIONS[0],64            minHeight: COMPACT_WINDOW_DIMENSIONS[1],65            defaultWidth: COMPACT_WINDOW_DIMENSIONS[0],66            defaultHeight: COMPACT_WINDOW_DIMENSIONS[1]67        });68    }69    getMaximizedWindowConfig(name) {70        return this.getConfig(name, {71            showTaskbarIcon: true,72            saveWindowState: true,73            url: 'index.html',74            resizable: true,75            maximizable: true,76            state: 'maximized',77            minWidth: DEFAULT_WINDOW_MIN_DIMENSIONS[0],78            minHeight: DEFAULT_WINDOW_MIN_DIMENSIONS[1],79            defaultWidth: DEFAULT_WINDOW_DIMENSIONS[0],80            defaultHeight: DEFAULT_WINDOW_DIMENSIONS[1]81        });82    }83    getTearoutConfig(name) {84        return this.getConfig(name, {85            maximizable: false,86            resizable: false,87            showTaskbarIcon: false,88            saveWindowState: false,89            maxWidth: TEAROUT_CARD_DIMENSIONS[0],90            maxHeight: TEAROUT_CARD_DIMENSIONS[1],91            url: 'tearout.html'92        });93    }94    getTearoutCardDimensions() {95        return TEAROUT_CARD_DIMENSIONS;96    }97    getCompactWindowDimensions() {98        return COMPACT_WINDOW_DIMENSIONS;99    }100    getDefaultWindowDimensions() {101        return DEFAULT_WINDOW_DIMENSIONS;102    }103    getDefaultWindowMinDimensions() {104        return DEFAULT_WINDOW_MIN_DIMENSIONS;105    }106    getTopCardOffset(compact) {107        return compact ? TEAROUT_WINDOW_OFFSET_COMPACT : TEAROUT_WINDOW_OFFSET;108    }109    getInitialBitfluxProportion() {110        return BITFLUX_INITIAL_PROPORTION;111    }112    getBitfluxStockAmount() {113        return BITFLUX_STOCK_AMOUNT;114    }115    getDefaultStocks() {116        return DEFAULT_STOCKS;117    }118}...window-behaviour.js
Source:window-behaviour.js  
...6var settings = require('./settings');7var win = gui.Window.get();8module.exports = {9    close : function(c){10        this.saveWindowState(win);11        win.close(c);12    },13    min : function(){14        win.minimize();15    },16    max : function(){17        win.maximize();18    },19    unmax : function(){20        win.unmaximize();21    },22    closeWithEscKey: function(win) {23        var option = {24            key : "Shift+Escape",25            active : function() {26                console.log("Global desktop keyboard shortcut: " + this.key + " active.");27            },28            failed : function(msg) {29                console.log(msg);30            }31        };32        var shortcut = new gui.Shortcut(option);33        gui.App.unregisterGlobalHotKey(shortcut);34        gui.App.registerGlobalHotKey(shortcut);35        shortcut.on('active', function() {36            win.hide();37        });38    },39    set : function(win){40        gui.App.removeAllListeners('reopen');41        gui.App.on('reopen', function() {42            win.show();43        });44        // Don't quit the app when the window is closed45        if (!platform.isLinux) {46            win.removeAllListeners('close');47            win.on('close', function() {48                    this.saveWindowState(win);49                    win.hide();50            }.bind(this));51        }52    },53    bindWindowStateEvents: function(win) {54        win.removeAllListeners('maximize');55        win.on('maximize', function() {56            win.sizeMode = 'maximized';57        });58        win.removeAllListeners('unmaximize');59        win.on('unmaximize', function() {60            win.sizeMode = 'normal';61        });62        win.removeAllListeners('minimize');...app.js
Source:app.js  
...57}58/**59 * Persist the window state for the next session60 */61function saveWindowState(cb) {62  var bounds = mainWindow.getBounds(),63      config = {};64  if (mainWindow.isMaximized() || mainWindow.isFullScreen()) {65    config = {66      isMaximized: mainWindow.isMaximized(),67      isFullScreen: mainWindow.isFullScreen()68    }69  }70  else {71    config = {72      x: bounds.x,73      y: bounds.y,74      width: bounds.width,75      height: bounds.height,...index.js
Source:index.js  
...35  })36  mainWindow.on('closed', () => {37    mainWindow = null38  })39  mainWindow.on('resize', () => saveWindowState(mainWindow))40  mainWindow.on('move', () => saveWindowState(mainWindow))41  mainWindow.on('close', () => saveWindowState(mainWindow))42}43app.on('ready', createWindow)44app.on('window-all-closed', () => {45  if (process.platform !== 'darwin') {46    app.quit()47  }48})49app.on('activate', () => {50  if (mainWindow === null) {51    createWindow()52  }53})54require('electron-context-menu')()55function saveWindowState (mainWindow) {...index-test.js
Source:index-test.js  
...8test9    .before(async t => {10        if (!config.useLocalBrowsers)11            return;12        await saveWindowState(t);13        await t.maximizeWindow();14    })15    .after(async t => {16        if (!config.useLocalBrowsers)17            return;18        await restoreWindowState(t);19    })20    ("Shouldn't scroll to target parent while performing click", async t => {21        const oldWindowScrollValue = await getWindowScrollTop();22        await t.click('#child');23        const newWindowScrollValue = await getWindowScrollTop();24        expect(newWindowScrollValue).eql(oldWindowScrollValue);...Using AI Code Generation
1import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';2test('My first test', async t => {3    await saveWindowState('chrome');4        .click('#populate')5        .click('#submit-button')6        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');7    await restoreWindowState('chrome');8});9import { setWindowSize } from 'testcafe-browser-tools';10test('My first test', async t => {11    await setWindowSize('chrome', 500, 500);12        .click('#populate')13        .click('#submit-button')14        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');15});16import { setWindowPosition } from 'testcafe-browser-tools';17test('My first test', async t => {18    await setWindowPosition('chrome', 500, 500);19        .click('#populate')20        .click('#submit-button')21        .expect(Selector('#article-header').innerText).eql('Thank you, John Smith!');22});Using AI Code Generation
1import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';2test('My test', async t => {3        .typeText('#developer-name', 'John Smith')4        .click('#windows')5        .click('#submit-button');6    const windowState = await saveWindowState();7    await restoreWindowState(windowState);8});9import { resizeWindow } from 'testcafe-browser-tools';10test('My test', async t => {11        .typeText('#developer-name', 'John Smith')12        .click('#windows')13        .click('#submit-button');14    await resizeWindow(1000, 1000);15});16import { maximizeWindow } from 'testcafe-browser-tools';17test('My test', async t => {18        .typeText('#developer-name', 'John Smith')19        .click('#windows')20        .click('#submit-button');21    await maximizeWindow();22});23import { takeScreenshot } from 'testcafe-browser-tools';24test('My test', async t => {25        .typeText('#developer-name', 'John Smith')26        .click('#windows')27        .click('#submit-button');28    await takeScreenshot('screenshotPath');29});30import { setFilesToUpload } from 'testcafe-browser-tools';31test('My test', asyncUsing AI Code Generation
1import { saveWindowState } from 'testcafe-browser-tools';2test('My test', async t => {3    await saveWindowState('test', { path: 'window.json' });4});5import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';6    .before( async t => {7        await saveWindowState('test', { path: 'window.json' });8    })9    .after( async t => {10        await restoreWindowState('test', { path: 'window.json' });11    });12test('My test', async t => {13});14import { restoreWindowState } from 'testcafe-browser-tools';Using AI Code Generation
1import { saveWindowState } from 'testcafe-browser-tools';2test('My Test', async t => {3    await saveWindowState('my-window-1');4});5import { maximizeWindow } from 'testcafe-browser-tools';6test('My Test', async t => {7    await maximizeWindow();8});9import { resizeWindow } from 'testcafe-browser-tools';10test('My Test', async t => {11    await resizeWindow(100, 200);12});13import { takeScreenshot } from 'testcafe-browser-tools';14test('My Test', async t => {15    await t.takeScreenshot('my-screenshot-path');16});17import { setFilesToUpload } from 'testcafe-browser-tools';18test('My Test', async t => {19    await t.setFilesToUpload('#upload-input', [20    ]);21});22import { getViewportSize } from 'testcafe-browser-tools';23test('My Test', async t => {24    const viewportSize = await getViewportSize('my-window-1');25});26import { getWindows } from 'testcafe-browser-tools';27test('My Test', async t => {28    const windows = await getWindows();29});Using AI Code Generation
1import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';2    .before(async ctx => {3        ctx.state = await saveWindowState();4    })5    .after(async ctx => {6        await restoreWindowState(ctx.state);7    });8test('My Test', async t => {9});10import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';11async function saveWindowAndRestore (t) {12    const windowState = await saveWindowState();13    await restoreWindowState(windowState);14}15test('My Test', saveWindowAndRestore);16import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';17test('My Test', async t => {18    const windowState = await saveWindowState();19        .click('#populate')20        .click('#submit-button');21    await restoreWindowState(windowState);22});23await saveWindowState (options)24import { saveWindowState } from 'testcafe-browser-tools';25test('My Test', async t => {26    const windowState = await saveWindowState();27    await restoreWindowState(windowState);28});29await restoreWindowState (state, options)30import { restoreWindowState } from 'testcafe-browser-tools';31test('My Test', async t => {32    const windowState = await saveWindowState();33    await restoreWindowState(windowState);34});Using AI Code Generation
1import { saveWindowState, restoreWindowState } from 'testcafe-browser-tools';2test('My Test', async t => {3    await saveWindowState('MyTest1');4        .click('#myButton')5        .wait(1000);6    await restoreWindowState('MyTest1');7});Using AI Code Generation
1import { saveWindowState } from 'testcafe-browser-tools';2test('test', async t => {3    await saveWindowState('chrome', 'test');4});5import { restoreWindowState } from 'testcafe-browser-tools';6test('test', async t => {7    await restoreWindowState('chrome', 'test');8});Using AI Code Generation
1import { saveWindowState } from 'testcafe-browser-tools';2test('test', async t => {3    await saveWindowState('chrome', 'test1');4        .resizeWindow(1000, 1000)5        .click('#button');6    await saveWindowState('chrome', 'test2');7});8import { restoreWindowState } from 'testcafe-browser-tools';9test('test', async t => {10    await restoreWindowState('chrome', 'test1');11        .click('#button');12    await restoreWindowState('chrome', 'test2');13});14import { saveWindowDimensions } from 'testcafe-browser-tools';15test('test', async t => {16    await saveWindowDimensions('chrome', 'test1');17        .resizeWindow(1000, 1000)18        .click('#button');19    await saveWindowDimensions('chrome', 'test2');20});21import { restoreWindowDimensions } from 'testcafe-browser-tools';22test('test', async t => {23    await restoreWindowDimensions('chrome', 'test1');24        .click('#button');25    await restoreWindowDimensions('chrome', 'test2');26});27import { saveWindowPosition } from 'testcafe-browser-tools';28test('test', async t => {29    await saveWindowPosition('chrome', 'test1');30        .resizeWindow(1000, 1000)31        .click('#button');32    await saveWindowPosition('chrome', 'test2');33});34import { restoreWindowPosition } from 'testcafe-browser-tools';35test('test', async t => {36    await restoreWindowPosition('chromeLearn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
