Best JavaScript code snippet using cypress
Schedule.js
Source:Schedule.js  
1import 'dayjs/locale/ru'2import { makeAutoObservable } from 'mobx'3import dayjs from 'dayjs'4import cache from '../services/cache'5import sources from '../global/sources'6import weeks from '../global/weeks'7import types from '../global/pickerTypes'8import requestFilters from "../global/requestFilters";9import getListOf from "../utils/getListOf";10import entities from './Entities'11import pickers from './Pickers'12import app from './App'13class Schedule {14    tables = []15    call = []16    isPressed = false17    pressedConfig = {}18    modalVisible = false19    moodle = []20    sources = [...sources] //from import21    weeks = [...weeks] //from import22    set(item, data) {23        this[item] = data24    }25    async init() {26        app.isReady = false27        const baseEndpoints = {28            'ÐÑÑппÑ': 'https://api.ptpit.ru/groups' + requestFilters,29            'ÐÑеподаваÑели': 'https://api.ptpit.ru/persons/teachers',30            'ÐÑдиÑоÑии': 'https://api.ptpit.ru/rooms'31        }32        const _cache = await cache.getAll();33        console.log(Object.values(_cache).map(c => Object.values(c)[1]))34        const getFromCache = item => _cache.pressed?.value[item] || _cache[item]?.value35        const _source = getFromCache('source') || sources[0]36        const _second = getFromCache(_source);37        let _week = getFromCache('week') || weeks[1]38        const dayOfWeek = dayjs().format('dddd')39        // switch week40        if (dayOfWeek === 'Sunday' && _week && !_cache.isClearedOnSunday) {41            console.log('clean date cache on Sunday')42            await cache.remove('pressed')43            await cache.set(_source, _second)44            _week = weeks[1]45            cache.set('isClearedOnSunday', true)46        }47        if(dayOfWeek !== 'Sunday') {48            cache.remove('isClearedOnSunday')49        }50        // console.log(_cache);51        [['week', _week], ['second', _second], ['source', _source]].forEach(items => {52            pickers.set(...items)53        });54        [55            ['group', _cache['ÐÑÑппÑ']],56            ['teacher', _cache['ÐÑеподаваÑели']],57            ['room', _cache['ÐÑдиÑоÑии']]58        ].forEach(items => {59            entities.set(items[0], 'preview', items[1]?.value || (entities[items[0]].list || [])[0])60            // preload previews from cache or from preloaded list61        });62        //is some list expired?63        sources.forEach(type => {64            const listOf = getListOf(type)65            const listOfFromCache = _cache[listOf] || {}66            if(dayjs().diff(listOfFromCache.created, 'day') >= 7) {67                cache.remove(listOf)68                console.log(type + ' is expired')69            }70            else {71                console.log(type + ' is not expired')72                entities.set(types[type],'list', listOfFromCache.value)73            }74        })75        // for clicked source76        const listOf = getListOf(_source)77        const listOfFromCache = _cache[listOf] || {}78        const fetchList = async () => {79            console.log('fetch list')80            const response = await fetch(baseEndpoints[_source])81            const _call = await response.json()82            this.call = _call83            entities.set(types[_source], 'list', _call)84            cache.set(listOf, _call).then()85        }86        const list = listOfFromCache.value87        console.log(list)88        if(list) {89            this.call = list90            entities.set(types[_source], 'list', list)91        }92        else {93            await fetchList()94        }95        this.pressedConfig = _cache.pressed?.value96        this.isPressed = !!this.pressedConfig97        if (this.isPressed) {98            await this.getTimetable(true)99        }100        else {101            app.isReady = true102        }103        setTimeout(() => app.isInit = true, 500)104        let isInCache = (e) => (105            Object.values(_cache).map(c => Object.values(c)[1]).includes(e.name)106        );107        console.log(_cache)108    }109    prep = async () => {110        this.getTimetable()111        const {source, week, second} = pickers112        this.pressedConfig = {113            source, week, second114        }115        cache.set('pressed', {116            source, week, second117        })118        cache.set(source, second)119    }120    moodleActions(payload) {121        const translate = (type) => {122            switch (type) {123                case 'task': return 'ÐадаÑа'124                case 'meeting': return 'ÐÑÑÑеÑа'125                case 'resource': return 'РеÑÑÑÑ'126                default: return type127            }128        }129        this.modalVisible = true130        this.moodle = payload.map(payload => [131            translate(payload.type),132            payload.url,133            `${dayjs(payload.date).format('DD.MM.YYYY')} ${payload.time}`134        ])135    }136    async getTimetable(isPreload) {137        try {138            const time = [139                '8:30\n10:05',140                '10:25\n12:00',141                '12:20\n14:10',142                '14:15\n15:50',143                '16:10\n17:55',144                '18:00\n19:35',145            ]146            this.isPressed = true147            app.isReady = false148            const targetFrom = item => isPreload ? this.pressedConfig[item] : pickers[item]149            const inputs = {150                id: this.call.find(item => item.name === targetFrom('second')).id,151                week: targetFrom('week').split(' - ')[0].split('.').reverse().join('-')152            }153            const paths = {154                'ÐÑÑппÑ': `https://api.ptpit.ru/timetable/groups/${inputs.id}/${inputs.week}`,155                'ÐÑеподаваÑели': `https://api.ptpit.ru/timetable/teachers/${inputs.id}/${inputs.week}`,156                'ÐÑдиÑоÑии': `https://api.ptpit.ru/rooms/${inputs.id}/timetable/${inputs.week}`157            }158            const dates = new Set()159            const response = await fetch(paths[targetFrom('source')])160            const json = await response.json();161            json.forEach(pair => {162                dates.add(pair.date)163            })164            this.tables = Array.from(dates).map(date => {165                const dayOfWeek = dayjs(date).locale('ru').format('dddd')166                const parseDate = `${dayOfWeek[0].toUpperCase() + dayOfWeek.slice(1)} (${dayjs(date).format('DD.MM')})`167                return {168                    [parseDate]: json.filter(e => e.date === date)169                        .map(pair => {170                            return [171                                pair.num,172                                time[pair.num - 1],173                                {174                                    moodle: pair.moodle,175                                    subject_name: pair.subject_name176                                },177                                pair.subgroup || 'â',178                                pickers.source === 'ÐÑеподаваÑели' ? pair.group_name179                                : pair.teacher_surname && `${pair.teacher_surname} ${pair.teacher_name[0]}.${pair.teacher_secondname[0]}.`,180                                pickers.source === 'ÐÑдиÑоÑии' ? pair.group_name : pair.room_name181                            ]182                        })183                }184            })185            app.isReady = true186        }187        catch (e) {188            console.error(e)189            app.isReady = true190        }191    }192    constructor() {193        makeAutoObservable(this)194    }195}...index.test.js
Source:index.test.js  
1import { app } from 'electron';2import getConfig from 'main-process/config';3import createWindow from 'main-process/main-window';4import main from './index';5jest.mock('electron', () => ({6  app: {7    isReady: jest.fn(),8    once: jest.fn(),9    quit: jest.fn(),10  },11}));12jest.mock('main-process/config', () =>13  jest.fn(() => Promise.resolve('config')),14);15jest.mock('main-process/main-window', () => jest.fn());16describe('main-process entry', () => {17  beforeEach(() => {18    jest.clearAllMocks();19  });20  it('should call createWindow if ready', () => {21    app.isReady.mockImplementation(() => false);22    return main()23      .then(() => {24        expect(createWindow).not.toHaveBeenCalled();25      })26      .then(() => {27        app.isReady.mockImplementation(() => true);28        return main();29      })30      .then(() => {31        expect(createWindow).toHaveBeenCalledWith(undefined, 'config');32      });33  });34  it('should add a ready event listener to call createWindow if not ready', () => {35    app.isReady.mockImplementation(() => true);36    return main()37      .then(() => {38        expect(app.once.mock.calls).toHaveLength(1);39        expect(app.once.mock.calls[0][0]).not.toBe('ready');40      })41      .then(() => {42        app.isReady.mockImplementation(() => false);43        app.once.mockReset();44        createWindow.bind = jest.fn();45        return main();46      })47      .then(() => {48        expect(app.once.mock.calls[0][0]).toBe('ready');49        expect(createWindow.bind).toHaveBeenCalledWith(50          null,51          undefined,52          'config',53        );54      });55  });56  it('should always set an event listener for window-all-closed to quit', () => {57    app.isReady.mockImplementation(() => false);58    return main()59      .then(() => {60        expect(app.once).toHaveBeenCalledWith('window-all-closed', app.quit);61      })62      .then(() => {63        app.isReady.mockImplementation(() => true);64        app.once.mockReset();65        return main();66      })67      .then(() => {68        expect(app.once).toHaveBeenCalledWith('window-all-closed', app.quit);69      });70  });71  it('should log any unexpected errors and exit the process', () => {72    const error = 'something bad happened';73    global.process.exit = jest.fn();74    console.log = jest.fn(); // eslint-disable-line no-console75    getConfig.mockImplementation(() => Promise.reject(error));76    return main().catch(caughtError => {77      expect(caughtError).toEqual(error);78      expect(global.process.exit).toHaveBeenCalledWith(1);79    });80  });...app_test.js
Source:app_test.js  
1/*global App, Promise */2'use strict';3require('/views/shared/js/app.js');4suite('App', function() {5  // Taken from app.js6  const APPLICATION_READY_CLASS_NAME = 'js-app-ready';7  teardown(function() {8    document.body.classList.remove(APPLICATION_READY_CLASS_NAME);9  });10  test('isReady is false by default', function() {11    assert.equal(App.isReady(), false);12  });13  test('setReady sets body class and isReady', function() {14    App.setReady();15    assert.equal(App.isReady(), true);16    assert.ok(document.body.classList.contains(APPLICATION_READY_CLASS_NAME));17  });18  test('setReady throws exception if called more than once', function() {19    App.setReady();20    assert.throws(function() {21      App.setReady();22    });23  });24  test('whenReady is resolved immediately if app is ready', function(done) {25    App.setReady();26    App.whenReady().then(function() {27      assert.ok(App.isReady());28    }).then(done, done);29  });30  test('whenReady is resolved when setReady is called', function(done) {31    var stub = sinon.stub();32    this.sinon.spy(App, 'setReady');33    var whenReadyPromise = App.whenReady();34    whenReadyPromise.then(stub).then(function() {35      assert.ok(App.isReady());36      sinon.assert.callOrder(App.setReady, stub);37    }).then(done, done);38    Promise.resolve().then(function() {39      App.setReady();40    });41  });42  test('whenReady is rejected in case of error', function(done) {43    var error = new Error('Test error');44    this.sinon.stub(MutationObserver.prototype, 'observe', function() {45      throw error;46    });47    App.whenReady().then(function() {48      throw new Error('Success callback should not have been called.');49    }, function(e) {50      assert.equal(e, error);51    }).then(done, done);52    App.setReady();53  });54  test('whenReady is rejected in case of error in MutationObserver callback',55    function(done) {56    var error = new Error('Test error');57    // This is called inside MutationObserver callback58    this.sinon.stub(MutationObserver.prototype, 'disconnect', function() {59      throw error;60    });61    App.whenReady().then(function() {62      throw new Error('Success callback should not have been called.');63    }, function(e) {64      assert.equal(e, error);65    }).then(done, done);66    App.setReady();67  });...main.js
Source:main.js  
...3const path = require('path')4let win5function createWindow() {6    console.log('ready')7    console.log('isReady: ', app.isReady()) // true8    win = new BrowserWindow({9        width: 800,10        height: 600,11        webPreferences: {12            nodeIntegration: true13        }14    })15    win.loadURL(16        url.format({17            pathname: path.join(__dirname, 'index.html'),18            protocol: 'file:',19            slashes: true20        })21    )22    win.webContents.openDevTools()23}24app.on('ready', createWindow)25// will-finish-launchingë readyë³´ë¤ ë¨¼ì  ì¤íëë¤.26app.on('will-finish-launching', () => {27    console.log('will-finish-launching')28})29// ì í리ì¼ì´ì
ì´ ìëì°ë¥¼ ë«ê¸° ì§ì ì ë°ìí©ëë¤. Event.preventDefault()를 í¸ì¶íë©´ 기본 ëìì¸ ì í리ì¼ì´ì
 ì¢
ë£ë¥¼ íì§ ììµëë¤.30app.on('before-quit', () => {31    console.log('before-quit')32})33// ëª¨ë  ìëì°ê° ë«íê³  ì í리ì¼ì´ì
ì´ ì¢
ë£ë  ë ë°ìíë¤. Event.preventDefault()를 í¸ì¶íë©´ 기본 ëìì¸ ì í리ì¼ì´ì
 ì¢
ë£ë¥¼ íì§ ììµëë¤.34app.on('will-quit', () => {35    console.log('will-quit')36})37console.log('isReady: ', app.isReady()) //false38// whenReadyë Promise를 ë°ííê³  isReady ë©ìë를 ë´ë¶ìì í¸ì¶íë©´ trueê° ëë ìì ì ê°ì ë°ííë¤.39app.whenReady().then(res => {40    console.log('whenReady1: ', res) // undefined41    console.log('whenReady2: ', app.isReady()) // true...02主进程app的事件.js
Source:02主进程app的事件.js  
...3//   console.log('ready')4// })5//å建çªå£6function createWindow() {7  console.log(`4app is ready ? --- ${app.isReady()}`) // true8  const mainWidow = new BrowserWindow({9    width: 800,10    height: 650,11    webPreferences: {12      contextIsolation: true13    }14  })15  mainWidow.loadURL('https://www.baidu.com')16  console.log(`3app is ready ? --- ${app.isReady()}`) //true17  //getPath:  ä½ å¯ä»¥éè¿è¿äºå称请æ±ä¸åè·¯å¾ï¼ åºç¨ï¼ å¯ä»¥å¨ä¸è½½èµæºï¼æå®ä¸è½½ç®å½å°åï¼ ä¸ä¼ ï¼ 读åä¸äºæ¬å°æä»¶ä¿¡æ¯æå®ç®å½18  console.log(app.getPath('desktop'))19  console.log(app.getPath('music'))20  console.log(app.getPath('temp'))21  console.log(app.getPath('userData'))22}23// app.on('ready', createWindow) //è¿ä¸ªæ¯ä»¥åçåæ³24console.log(`1app is ready ? --- ${app.isReady()}`) //false25app.whenReady().then(createWindow)26console.log(`2app is ready ? --- ${app.isReady()}`) //false27app.on('open-url', (e) => {28  console.log('æå¼urlå°å')29  e.preventDefault()30})31//çå¬éåº32app.on('before-quit', () => {33  console.log('app quit')34})35//失å»ç¦ç¹36app.on('browser-window-blur', () => {37  console.log('失å»ç¦ç¹')38  // setTimeout(() => {39  //   app.quit() //失å»ç¦ç¹åï¼ä¸ç§éåºåºç¨40  // },3000)...protocol.js
Source:protocol.js  
...3module.exports = process.atomBinding('protocol')4// Fallback protocol APIs of default session.5Object.setPrototypeOf(module.exports, new Proxy({}, {6  get (target, property) {7    if (!app.isReady()) return8    const protocol = session.defaultSession.protocol9    if (!Object.getPrototypeOf(protocol).hasOwnProperty(property)) return10    // Returning a native function directly would throw error.11    return (...args) => protocol[property](...args)12  },13  ownKeys () {14    if (!app.isReady()) return []15    return Object.getOwnPropertyNames(Object.getPrototypeOf(session.defaultSession.protocol))16  },17  getOwnPropertyDescriptor (target) {18    return { configurable: true, enumerable: true }19  }...prepare.js
Source:prepare.js  
1'use strict';2require('assert');3var app = require('../');4app.init({5  updateRemotely: false6});7var _stdout = '';8app.vorpal.pipe(function(str) {9  _stdout += str;10  return '';11});12app.isReady = false;13app.ready = function(done) {14  if (!app.isReady) {15    app.clerk.indexer.update({force: true, static: false}, function (err) {16      app.isReady = true;17      done();18    });19  } else {20    done();21  }22}23app.stdout = function () {24  var out = _stdout;25  _stdout = '';26  return out;27}...app.js
Source:app.js  
1'use strict';2const assert = require('assert');3module.exports = app => {4  app.isReady = true;5  app.beforeStart(function*() {6    if (!app.isReady) throw new Error('not ready');7  });8  app.isReady = false;...Using AI Code Generation
1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('Using AI Code Generation
1describe('My First Test', function() {2  it('Visits the Kitchen Sink', function() {3    cy.contains('type').click()4    cy.url().should('include', '/commands/actions')5    cy.get('.action-email')6      .type('Using AI Code Generation
1describe("My First Test", () => {2    it("Visits the Kitchen Sink", () => {3        cy.contains("type").click();4        cy.url().should("include", "/commands/actions");5        cy.get(".action-email")6            .type("Using AI Code Generation
1describe('My First Test', function() {2  it('Does not do much!', function() {3    cy.pause()4    cy.contains('type').click()5    cy.url().should('include', '/commands/actions')6    cy.get('.action-email').type('Using AI Code Generation
1describe('My First Test', () => {2  it('Does not do much!', () => {3    expect(true).to.equal(true)4  })5})6describe('My First Test', () => {7  it('Does not do much!', () => {8    cy.window().its('app').should('be.not.null')9  })10})11describe('My First Test', () => {12  it('Does not do much!', () => {13    cy.window().its('app').should('be.not.null')14  })15})16describe('My First Test', () => {17  it('Does not do much!', () => {18    cy.window().its('app').should('be.not.null')19  })20})21describe('My First Test', () => {22  it('Does not do much!', () => {23    cy.window().its('app').should('be.not.null')24  })25})26describe('My First Test', () => {27  it('Does not do much!', () => {28    cy.window().its('app').should('be.not.null')29  })30})31describe('My First Test', () => {32  it('Does not do much!', () => {33    cy.window().its('app').should('be.not.null')34  })35})36describe('My First Test', () => {37  it('Does not do much!', () => {38    cy.window().its('app').should('be.not.null')39  })40})41describe('My First Test', () => {42  it('Does not do much!', () => {43    cy.window().its('app').should('be.not.nullUsing AI Code Generation
1describe('test', () => {2  it('test', () => {3    cy.get('h1').should('contain', 'Kitchen Sink')4  })5})6describe('test', () => {7  it('test', () => {8    cy.get('h1').should('contain', 'Kitchen Sink')9  })10})11cy.fixture('file-1603361875946-0.jpg', 'base64')12  .then(Cypress.Blob.base64StringToBlob)13  .then(fileContent => {14    cy.get('input[type=file]').upload({ fileContent, fileName: 'file-1603361875946-0.jpg', mimeType: 'image/jpeg' });15  });Using AI Code Generation
1describe('Cypress app.isReady test', () => {2    it('Cypress app.isReady test', () => {3        cy.window().then((win) => {4            console.log(win.app.isReady)5        })6    })7})Using AI Code Generation
1describe('Cypress app is ready', function() {2  it('Check if app is ready', function() {3    cy.isReady();4  });5});6describe('Cypress app is ready', function() {7  it('Check if app is ready', function() {8    cy.isReady();9  });10});11Cypress.Commands.add('isReady', () => {12  cy.window().its('app').should('be.an', 'object');13});14import './commands';15describe('Cypress app is ready', function() {16  it('Check if app is ready', function() {17    cy.isReady();18  });19});20Cypress.Commands.add('isReady', () => {21  cy.window().its('app').should('be.an', 'object');22});23import './commands';24describe('Cypress app is ready', function() {25  it('Check if app is ready', function() {26    cy.isReady();27  });28});29Cypress.Commands.add('isReady', () => {30  cy.window().its('app').should('be.an', 'object');31});32import './commands';33describe('Cypress app is ready', function() {34  it('Check if app is ready', function() {35    cy.isReady();36  });37});38Cypress.Commands.add('isReady', () => {39  cy.window().its('app').should('be.an', 'object');40});41import './commands';Cypress is a renowned Javascript-based open-source, easy-to-use end-to-end testing framework primarily used for testing web applications. Cypress is a relatively new player in the automation testing space and has been gaining much traction lately, as evidenced by the number of Forks (2.7K) and Stars (42.1K) for the project. LambdaTest’s Cypress Tutorial covers step-by-step guides that will help you learn from the basics till you run automation tests on LambdaTest.
You can elevate your expertise with end-to-end testing using the Cypress automation framework and stay one step ahead in your career by earning a Cypress certification. Check out our Cypress 101 Certification.
Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.
Get 100 minutes of automation test minutes FREE!!
