How to use _mergeState method in Cypress

Best JavaScript code snippet using cypress

merge.js

Source:merge.js Github

copy

Full Screen

1import assert from 'power-assert'2import {Chan} from './chan'3import {arrayPool} from './pools'4import {TimeoutChan} from './special-chans'5import {CLOSED, FAILED, ERROR} from './constants'6import {SEND_TYPE_VALUE, SEND_TYPE_ERROR} from './constants'7import {P_RESOLVED_WITH_TRUE, P_RESOLVED_WITH_FALSE} from './constants'8import {EventEmitterMixin} from './event-emitter'9const CANNOT_SEND_ERROR_MSG = `Sending and piping into a merge channel, as well as converting ` +10  `it into a send-only chan, is not supported. As a workaround, you can add one more channel ` +11  `into the merged set, and send/pipe into it.`12const EMPTY = []13const STATE_AWAITING_SEND = 014const STATE_ENQUEUEING_TAKES = 115const STATE_AWAITING_TAKE = 216const STATE_MERGING_SYNC = 317const STATE_ENDED = 418const STATE_NAMES = [19  'STATE_AWAITING_SEND', 'STATE_ENQUEUEING_TAKES', 'STATE_AWAITING_TAKE',20  'STATE_MERGING_SYNC', 'STATE_ENDED'21]22export class MergeChan extends Chan {23  constructor(srcs, bufferSize) {24    super(bufferSize)25    this._srcs = srcs26    this._mergeState = STATE_AWAITING_SEND27    this._syncSrcs = arrayPool.take()28    this._init(srcs)29    if (this._totalDataSrcs) {30      this._maybeSendNext()31    } else {32      this._end()33    }34  }35  _init(srcs) {36    this._onDrain = () => this._maybeSendNext()37    this.on('drain', this._onDrain)38    let timeoutSrcs = EMPTY39    let dataSrcs = arrayPool.take()40    for (let i = 0; i < srcs.length; ++i) {41      let chan = srcs[i]42      if (!chan.isClosed) {43        let isTimeout = chan instanceof TimeoutChan44        let src = this._makeSrc(chan, isTimeout)45        if (isTimeout) {46          if (timeoutSrcs === EMPTY) timeoutSrcs = arrayPool.take()47          timeoutSrcs.push(src)48        } else {49          dataSrcs.push(src)50        }51      }52    }53    this._timeoutSrcs = timeoutSrcs54    this._dataSrcs = dataSrcs55    this._totalTimeoutSrcs = timeoutSrcs.length56    this._totalDataSrcs = dataSrcs.length57  }58  _makeSrc(chan, isTimeout) {59    let src = { chan, cancel: undefined, onClosed: undefined,60      onTakenValue: undefined, onTakenError: undefined }61    if (isTimeout) {62      src.onTakenValue = onTakenValueFromTimeoutChan63    } else {64      src.onTakenValue = value => this._onTaken(value, SEND_TYPE_VALUE, src)65      src.onClosed = () => this._onSrcClosed(src)66      src.chan.on('closed', src.onClosed)67    }68    src.onTakenError = error => this._onTaken(error, SEND_TYPE_ERROR, src)69    return src70  }71  _maybeSendNext() {72    assert(this._mergeState == STATE_AWAITING_SEND || this._mergeState == STATE_AWAITING_TAKE)73    let canSendSync = this._super$canSendSync74    let canTakeMore = true75    let clearSyncState = true76    this._mergeState = STATE_MERGING_SYNC77    while (canSendSync && canTakeMore) {78      let syncResult = this._takeNextSync(clearSyncState)79      clearSyncState = false80      if (syncResult === FAILED) {81        canTakeMore = false82      } else {83        if (syncResult === ERROR) {84          syncResult = this._super$_sendSync(ERROR.value, true)85          assert(syncResult === true)86        } else {87          syncResult = this._super$_sendSync(syncResult, false)88          assert(syncResult === true)89        }90        canSendSync = this._super$canSendSync91      }92    }93    assert(canSendSync || canTakeMore)94    if (!this._totalDataSrcs) {95      // no srcs left alive => end merging96      this._end()97    } else if (!canSendSync) {98      // dst can't accept more data synchronously => wait until it can, then resume99      this._mergeState = STATE_AWAITING_SEND100      this.setNeedsDrain()101      this._cancelTakes()102    } else {103      assert(canTakeMore == false && this._canTakeNextSync() == false)104      this._mergeState = STATE_AWAITING_TAKE105      // srcs can't provide more data => wait until they can106      this._enqueueTakesFrom(this._timeoutSrcs, this._totalTimeoutSrcs)107      this._enqueueTakesFrom(this._dataSrcs, this._totalDataSrcs)108    }109  }110  get canTakeSync() {111    return super.canTakeSync || (this._mergeState != STATE_ENDED && this._canTakeNextSync())112  }113  _canTakeNextSync() {114    let srcs = this._timeoutSrcs115    let totalSrcs = this._totalTimeoutSrcs116    for (let i = 0; i < totalSrcs; ++i) {117      if (srcs[i].chan.canTakeSync) {118        return true119      }120    }121    srcs = this._dataSrcs122    totalSrcs = this._totalDataSrcs123    for (let i = 0; i < totalSrcs; ++i) {124      if (srcs[i].chan.canTakeSync) {125        return true126      }127    }128    return false129  }130  _takeSync() {131    if (this.isClosed) {132      return false133    }134    if (super._takeSync()) {135      return true136    }137    let result = this._takeNextSync(true)138    if (result === FAILED) {139      return false140    } else if (result === ERROR) {141      return result142    } else {143      this._value = result144      return true145    }146  }147  _takeNextSync(clearState) {148    let totalTimeoutSrcs = this._totalTimeoutSrcs149    let timeoutSrcs = this._timeoutSrcs150    for (let i = 0; i < totalTimeoutSrcs; ++i) {151      let {chan} = timeoutSrcs[i]152      if (chan.canTakeSync) {153        return chan._takeSync()154      }155    }156    let syncSrcs = this._syncSrcs157    let totalSyncSrcs158    if (clearState) {159      // clearState equals true when takeNextSync is running the first time during160      // the current event loop tick161      syncSrcs.length = 0162      let dataSrcs = this._dataSrcs163      let totalDataSrcs = this._totalDataSrcs164      let i = 0; while (i < totalDataSrcs) {165        let src = dataSrcs[i]166        // otherwise, src would have been removed from the list, see onSrcClosed()167        assert(src.chan.isClosed == false)168        if (src.chan.canTakeSync) {169          syncSrcs.push(src)170        }171        ++i172      }173      totalSyncSrcs = syncSrcs.length174    } else {175      // if we're running in the same tick as previous takeNextSync call, no channel176      // that was empty in the previous call can become non-empty; but the other way177      // is certainly possible178      totalSyncSrcs = syncSrcs.length179      let i = 0; while (i < totalSyncSrcs) {180        let src = syncSrcs[i], {chan} = src181        if (chan.canTakeSync) {182          ++i183        } else {184          syncSrcs.splice(i, 1); --totalSyncSrcs185        }186      }187    }188    if (totalSyncSrcs) {189      let i = (totalSyncSrcs == 1) ? 0 : Math.floor(totalSyncSrcs * Math.random())190      let ch = syncSrcs[i].chan191      let result = ch._takeSync()192      assert(result !== false)193      return result === ERROR ? result : ch.value194    }195    return FAILED196  }197  _enqueueTakesFrom(srcs, total) {198    assert(this._mergeState == STATE_AWAITING_TAKE)199    if (total == 0) return200    this._mergeState = STATE_ENQUEUEING_TAKES201    for (let i = 0; i < total; ++i) {202      let src = srcs[i]203      if (!src.cancel) {204        src.cancel = src.chan._take(src.onTakenValue, src.onTakenError, true)205      }206    }207    this._mergeState = STATE_AWAITING_TAKE208  }209  _cancelTakes() {210    this._cancelTakesFrom(this._timeoutSrcs, this._totalTimeoutSrcs)211    this._cancelTakesFrom(this._dataSrcs, this._totalDataSrcs)212  }213  _cancelTakesFrom(srcs, total) {214    for (let i = 0; i < total; ++i) {215      let src = srcs[i]216      if (src.cancel) {217        src.cancel()218        src.cancel = undefined219      }220    }221  }222  _onTaken(value, type, src) {223    assert(this._mergeState == STATE_AWAITING_TAKE, onTakenInvalidStateMsg(this._mergeState, src))224    src.cancel = undefined225    if (value == CLOSED) return226    let sent = this._super$_sendSync(value, type)227    assert(sent == true)228    this._maybeSendNext()229  }230  _onSrcClosed(src) {231    // otherwise this event would have not been received, see end()232    assert(this._mergeState != STATE_ENDED)233    src.chan.removeListener('closed', src.onClosed)234    let index = this._dataSrcs.indexOf(src)235    assert(index >= 0)236    this._dataSrcs.splice(index, 1)237    if (!--this._totalDataSrcs && this._mergeState != STATE_MERGING_SYNC) {238      this._end()239    }240  }241  _close() {242    super._close()243    if (this._mergeState != STATE_ENDED) {244      this._end()245    }246  }247  _end() {248    assert(this._mergeState != STATE_ENDED)249    this._mergeState = STATE_ENDED250    this.removeListener('drain', this._onDrain)251    freeSrcs(this._dataSrcs, this._totalDataSrcs)252    let totalTimeoutSrcs = this._totalTimeoutSrcs253    if (totalTimeoutSrcs) {254      assert(this._timeoutSrcs !== EMPTY)255      freeSrcs(this._timeoutSrcs, totalTimeoutSrcs)256    }257    arrayPool.put(this._syncSrcs)258    if (!this.isClosed) this.close()259  }260  _cancelTake(item) {261    let buf = this._buffer262    let index = buf.indexOf(item)263    if (index == -1) return264    buf.splice(index, 1)265    if (buf.length == 0) {266      this._cancelTakes()267    }268  }269  get _constructorName() {270    return 'chan.merge'271  }272  get _constructorArgsDesc() {273    return this._srcs274  }275  _maybeCanTakeSync(fn, mayReturnPromise) {276    if (this.canTakeSync) {277      return mayReturnPromise ? P_RESOLVED_WITH_TRUE : (fn(true), undefined)278    }279    if (this._mergeState == STATE_ENDED) {280      return mayReturnPromise ? P_RESOLVED_WITH_FALSE : (fn(false), undefined)281    }282    fn = callOnce1(fn)283    let srcs = this._dataSrcs284    for (let i = 0; i < srcs.length; ++i) {285      srcs[i].chan._maybeCanTakeSync(fn, false)286    }287    super._maybeCanTakeSync(fn, false)288  }289  get canSend() {290    return false291  }292  get canSendSync() {293    return false294  }295  _maybeCanSendSync(fn, mayReturnPromise) {296    if (mayReturnPromise) {297      return this.isActive ? P_RESOLVED_WITH_TRUE : P_RESOLVED_WITH_FALSE298    } else {299      fn(this.isActive)300    }301  }302  send(value, type) {303    this._throwSendingNotSupported()304  }305  _sendSync(value, type) {306    this._throwSendingNotSupported()307  }308  _send(value, type, fnVal, fnErr, needsCancelFn) {309    this._throwSendingNotSupported()310  }311  emit(event/* ...args */) {312    if (event == 'pipe') {313      this._throwSendingNotSupported()314    }315    this._super$emit.apply(this, arguments)316  }317  get sendOnly() {318    this._throwSendingNotSupported()319  }320  _throwSendingNotSupported() {321    throw new Error(CANNOT_SEND_ERROR_MSG)322  }323}324function freeSrcs(srcs, total) {325  for (let i = 0; i < total; ++i) {326    let src = srcs[i]327    if (src.onClosed) {328      src.chan.removeListener('closed', src.onClosed)329    }330    if (src.cancel) {331      src.cancel()332    }333  }334  arrayPool.put(srcs)335}336function onTakenValueFromTimeoutChan(value) {337  assert(false, `taken value ${value} from a timeout chan`)338}339function onTakenInvalidStateMsg(state, src) {340  return state == STATE_ENQUEUEING_TAKES341    ? `one of the source channels, ${src.chan}, called its _take callback synchronously ` +342      `despite the fact that it reported that it cannot be synchronously taken from`343    : `internal inconsistency error`344}345function callOnce1(fn) {346  let doCall = true; return arg => {347    if (doCall) {348      doCall = false349      fn(arg)350    }351  }352}353Object.defineProperties(MergeChan.prototype, {354  _super$emit: {355    value: EventEmitterMixin.emit,356    writable: true,357    enumerable: false,358    configurable: true359  },360  _super$_sendSync: {361    value: Chan.prototype._sendSync,362    writable: true,363    enumerable: false,364    configurable: true365  },366  _super$canSendSync: Object.getOwnPropertyDescriptor(Chan.prototype, 'canSendSync')...

Full Screen

Full Screen

project_static.js

Source:project_static.js Github

copy

Full Screen

...50function _mergeDetails(clientProject, project) {51    return lodash_1.default.extend({}, clientProject, project, { state: 'VALID' });52}53exports._mergeDetails = _mergeDetails;54function _mergeState(clientProject, state) {55    return lodash_1.default.extend({}, clientProject, { state });56}57exports._mergeState = _mergeState;58function _getProject(clientProject, authToken) {59    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {60        debug('get project from api', clientProject.id, clientProject.path);61        try {62            const project = yield api_1.default.getProject(clientProject.id, authToken);63            debug('got project from api');64            return _mergeDetails(clientProject, project);65        }66        catch (err) {67            debug('failed to get project from api', err.statusCode);68            switch (err.statusCode) {69                case 404:70                    // project doesn't exist71                    return _mergeState(clientProject, 'INVALID');72                case 403:73                    // project exists, but user isn't authorized for it74                    return _mergeState(clientProject, 'UNAUTHORIZED');75                default:76                    throw err;77            }78        }79    });80}81exports._getProject = _getProject;82function getProjectStatuses(clientProjects = []) {83    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {84        debug(`get project statuses for ${clientProjects.length} projects`);85        const authToken = yield user_1.default.ensureAuthToken();86        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });87        const projects = ((yield api_1.default.getProjects(authToken)) || []);88        debug(`got ${projects.length} projects`);89        const projectsIndex = lodash_1.default.keyBy(projects, 'id');90        return Promise.all(lodash_1.default.map(clientProjects, (clientProject) => {91            debug('looking at', clientProject.path);92            // not a CI project, just mark as valid and return93            if (!clientProject.id) {94                debug('no project id');95                return _mergeState(clientProject, 'VALID');96            }97            const project = projectsIndex[clientProject.id];98            if (project) {99                debug('found matching:', project);100                // merge in details for matching project101                return _mergeDetails(clientProject, project);102            }103            debug('did not find matching:', project);104            // project has id, but no matching project found105            // check if it doesn't exist or if user isn't authorized106            return _getProject(clientProject, authToken);107        }));108    });109}110exports.getProjectStatuses = getProjectStatuses;111function getProjectStatus(clientProject) {112    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {113        debug('get project status for client id %s at path %s', clientProject.id, clientProject.path);114        if (!clientProject.id) {115            debug('no project id');116            return Promise.resolve(_mergeState(clientProject, 'VALID'));117        }118        const authToken = yield user_1.default.ensureAuthToken();119        debug('got auth token: %o', { authToken: keys_1.default.hide(authToken) });120        return _getProject(clientProject, authToken);121    });122}123exports.getProjectStatus = getProjectStatus;124function remove(path) {125    return cache_1.default.removeProject(path);126}127exports.remove = remove;128function add(path, options) {129    return (0, tslib_1.__awaiter)(this, void 0, void 0, function* () {130        // don't cache a project if a non-default configFile is set...

Full Screen

Full Screen

pre-commit.js

Source:pre-commit.js Github

copy

Full Screen

1'use strict';2const fse = require('fs-extra');3const AffianceError = require('../error');4const gitRepo = require('../gitRepo');5const HookContextBase = require('./base');6const utils = require('../utils');7const fileUtils = require('../fileUtils');8module.exports = class HookContextPreCommit extends HookContextBase {9  constructor(config, argv, input) {10    super(config, argv, input);11    this.hookScriptName = 'pre-commit';12    this.hookConfigName = 'PreCommit';13    this._isAmendment = null;14  }15  isAmendment() {16    if (this._isAmendment === null) {17      let gitCommand = utils.grandParentCommand();18      // It's easy if 'git commit --amend' was used19      let easyAmendRegex = /\scommit(\s.*)?\s--amend(\s|$)/;20      this._isAmendment = !!gitCommand.match(easyAmendRegex);21      if(this._isAmendment) { return this._isAmendment; }22      // Check for git aliases that call `commit --amend`23      let commandOutput = utils.execSync('git config --get-regexp "^alias\\." "commit(\\s.*)?\\s--amend(\\s|$)"');24      if (!commandOutput) { return this._isAmendment; }25      let aliasRegex = /^alias\.([-\w]+)/gm;26      let matches = null;27      while ((matches = aliasRegex.exec(commandOutput)) !== null) {28        let matchRegex = new RegExp('git(\\.exe)?\\s+' + matches[1]);29        this._isAmendment = !!gitCommand.match(matchRegex);30        if(this._isAmendment) { return this._isAmendment; }31      }32    }33    return this._isAmendment;34  }35  anyChanges() {36    let commandResults = utils.execSync('git status -z --untracked-files=no').trim();37    let modifiedFiles = commandResults.split('\0').map((line) => {38      return line.replace(/[^\s]+\s+(.+)/, '$1');39    });40    return (modifiedFiles.length > 0);41  }42  setupEnvironment() {43    this.storeModifiedTimes();44    this.storeMergeState();45    this.storeCherryPickState();46    if (!gitRepo.isInitialCommit() && this.anyChanges()) {47      this._stashAttempted = true;48      let stashMessage = `Affiance: Stash of repo state before hook run at ${Date.now()}`;49      let command = `git -c commit.gpgsign=false stash save --keep-index --quiet "${stashMessage}"`;50      let commandResults = utils.execSync(command).trim();51      if (commandResults === false) {52        throw AffianceError.error(53          AffianceError.HookSetupFailed,54          'Unable to setup environment for commit-msg hook run.'55        );56      }57      let stashListResults = utils.execSync('git stash list -1').trim();58      this._changesStashed = !!stashListResults.match(new RegExp(stashMessage, 'g'));59    }60    this.restoreModifiedTimes();61  }62  // Restore unstaged changes and reset file modification times so it appears63  // as if nothing ever changed.64  //65  // We want to restore the modification times for each of the files after66  // every step to ensure as little time as possible has passed while the67  // modification time on the file was newer. This helps us play more nicely68  // with file watchers.69  cleanupEnvironment() {70    if (!(gitRepo.isInitialCommit() || (this._stashAttempted && !this._changesStashed)) ) {71      this.clearWorkingTree();72      this.restoreModifiedTimes();73    }74    if (this._changesStashed) {75      this.restoreWorkingTree();76      this.restoreModifiedTimes();77    }78    this.restoreMergeState();79    this.restoreCherryPickState();80    this.restoreModifiedTimes();81  }82  clearWorkingTree() {83    let removedSubmodules = gitRepo.stagedSubmoduleRemovals();84    let commandResult = utils.execSync('git reset --hard');85    if (commandResult === false) {86      throw AffianceError.error(87        AffianceError.HookCleanupFailed,88        'Unable to cleanup working tree for commit-msg hook run'89      );90    }91    for(let i in removedSubmodules) {92      fse.removeSync(removedSubmodules[i].path);93    }94  }95  restoreWorkingTree() {96    let commandResult = utils.execSync('git stash pop --index --quiet');97    if (commandResult === false) {98      throw AffianceError.error(99        AffianceError.HookCleanupFailed,100        'Unable to cleanup working tree for commit-msg hook run'101      );102    }103  }104  modifiedFiles() {105    if (!this._modifiedFiles) {106      let currentStaged = gitRepo.modifiedFiles({staged: true});107      this._modifiedFiles = currentStaged;108      if (this.isAmendment()) {109        let subCommand = 'show --format=%n';110        let previouslyModified = gitRepo.modifiedFiles({subCommand: subCommand});111        this._modifiedFiles = this._modifiedFiles.concat(this.filterModifiedFiles(previouslyModified));112      }113    }114    return this._modifiedFiles;115  }116  modifiedLinesInFile(filePath) {117    this._modifiedLinesByFile = this._modifiedLinesByFile || {};118    if (!this._modifiedLinesByFile[filePath]) {119      this._modifiedLinesByFile[filePath] = gitRepo.extractModifiedLines(filePath, {staged: true});120      if (this.isAmendment()) {121        let subCommand = 'show --format=%n';122        this._modifiedLinesByFile[filePath] = this._modifiedLinesByFile[filePath].concat(123          gitRepo.extractModifiedLines(filePath, {subCommand: subCommand})124        );125        this._modifiedLinesByFile[filePath].sort();126      }127    }128    return this._modifiedLinesByFile[filePath];129  }130  storeModifiedTimes() {131    this._modifiedTimes = {};132    let stagedFiles = this.modifiedFiles();133    let unstagedFiles = gitRepo.modifiedFiles({staged: false});134    stagedFiles.concat(unstagedFiles).forEach((filePath) => {135      if (fileUtils.isBrokenSymlink(filePath)) { return; }136      if (!fse.existsSync(filePath)) { return; }137      this._modifiedTimes[filePath] = fileUtils.modifiedTime(filePath);138    });139  }140  restoreModifiedTimes() {141    for(let modifiedFilePath in this._modifiedTimes) {142      if (fileUtils.isBrokenSymlink(modifiedFilePath)) { continue; }143      if (!fse.existsSync(modifiedFilePath)) { continue; }144      // `utimesSync` expects timestamps at the second resolution,145      // but we store the timestamp in ms.146      // Divide our stored value by 1000 to satisfy the api.147      let mtime = this._modifiedTimes[modifiedFilePath] / 1000;148      fse.utimesSync(modifiedFilePath, mtime, mtime);149    }150  }151  storeMergeState() {152    if (!this._mergeState) {153      this._mergeState = gitRepo.mergeState();154    }155    return this._mergeState;156  }157  restoreMergeState() {158    if (!this._mergeState) { return; }159    let gitDir = gitRepo.gitDir(gitRepo.repoRoot());160    if (this._mergeState.mergeHead) {161      let mergeModeFilePath = gitDir + '/MERGE_MODE';162      fse.ensureFileSync(mergeModeFilePath);163      let mergeHeadFilePath = gitDir + '/MERGE_HEAD';164      fse.writeFileSync(mergeHeadFilePath, this._mergeState.mergeHead);165      this._mergeState.mergeHead = null;166    }167    if (this._mergeState.mergeMsg) {168      let mergeMsgFilePath = gitDir + '/MERGE_MSG';169      fse.writeFileSync(mergeMsgFilePath, `${this._mergeState.mergeMsg}\n`);170      this._mergeState.mergeMsg = null;171    }172    this._mergeState = null;173  }174  storeCherryPickState() {175    if (!this._cherryPickState) {176      this._cherryPickState = gitRepo.cherryPickState();177    }178    return this._cherryPickState;179  }180  restoreCherryPickState() {181    if (!this._cherryPickState) { return; }182    let gitDir = gitRepo.gitDir(gitRepo.repoRoot());183    if (this._cherryPickState.cherryPickHead) {184      let cherryPickHeadFilePath = gitDir + '/CHERRY_PICK_HEAD';185      fse.writeFileSync(cherryPickHeadFilePath, this._cherryPickState.cherryPickHead);186      this._cherryPickState.cherryPickHead = null;187    }188    this._cherryPickState = null;189  }...

Full Screen

Full Screen

Step_2.js

Source:Step_2.js Github

copy

Full Screen

...22          <div className={grid.col50}>23            <Dropdown24              options={state.formValues.type_of_paper}25              labeltext='Type of paper'26              onChange={(value) => _mergeState({ order: { type_of_paper: value } })}27              value={state.order.type_of_paper}28              searchable={false}29              placeholder='Select essay type'/>30            <Dropdown31              options={state.formValues.academic_level}32              value={state.order.academic_level}33              placeholder='Select academic level'34              labeltext='Academic level'35              searchable={false}36              onChange={(value) => _mergeState({ order: { academic_level: value } })}/>37            <Dropdown38              options={state.formValues.subject_or_discipline}39              value={state.order.subject_or_discipline}40              placeholder='Subject, discipline'41              labeltext='Subject, discipline'42              searchable={false}43              onChange={(value) => _mergeState({ order: { subject_or_discipline: value } })}/>44            <Input45              name='topic'46              type='text'47              placeholder="Writer's choice"48              onChange={(event) => _mergeState({ order: { topic: event.target.value } })}49              labeltext='Topic'/>50          </div>51          <div className={grid.col50}>52            <Textarea53              name='paper_details'54              placeholder='Add details'55              labeltext='Paper details'56              value={state.order.paper_details}57              onChange={(event) => _mergeState({ order: { paper_details: event.target.value } })}/>58            <div className={styles.child140}>59              <Counter60                id='number_of_sources'61                labeltext='Sources number'62                count={state.order.number_of_sources}63                _mergeState={_mergeState}/>64              <Dropdown65                options={state.formValues.paper_format}66                value={state.order.paper_format}67                labeltext='Paper format'68                searchable={false}69                onChange={(value) => _mergeState({ order: { paper_format: value } })}/>70            </div>71            <FileDropZone72              files={state.order.files}73              _mergeState={_mergeState}/>74          </div>75        </div>76        <button77          onClick={nextStepHandler}78          className={`btn btn--primary ${styles.nextBtn}`}>Continue79        </button>80      </div>81    );82  }83}

Full Screen

Full Screen

RTCRtpTransceiver.js

Source:RTCRtpTransceiver.js Github

copy

Full Screen

...44          }45          var kind = this.receiver.track.kind;46          WebRTCModule.peerConnectionTransceiverSetDirection(this._peerConnectionId, this.id, val, kind, isShow, (successful, data) => {47              if (successful) {48                  this._mergeState(data.state);49                  this._direction = val;50                  resolve(val);51              } else {52                  reject(data);53                  console.warn("Unable to set direction: " + data);54              }55          });56        });57    }58    get currentDirection() {59        return this._currentDirection;60    }61    get sender() {62        return this._sender;63    }64    get receiver() {65        return this._receiver;66    }67    stop() {68        if (this._stopped) {69            return;70        }71        this._stopped = true;72        return new Promise((resolve, reject) => {73            WebRTCModule.peerConnectionTransceiverStop(this._peerConnectionId, this.id, (successful, data) => {74                if (successful) {75                    this._mergeState(data.state);76                    resolve();77                } else {78                    reject(new Error(data));79                }80            });81        });82    }83    _updateState(state) {84        this._mid = state.mid ? state.mid : null;85        this._direction = state.direction;86        this._currentDirection = state.currentDirection;87        if (state.isStopped) {88            this._stopped = true;89        }...

Full Screen

Full Screen

RelayReadyState.js

Source:RelayReadyState.js Github

copy

Full Screen

...52    }53    if (prevReadyState.done || prevReadyState.error) {54      if (nextReadyState.stale) {55        if (prevReadyState.error) {56          this._mergeState(nextReadyState, newEvents);57        }58        // Do nothing if stale data comes after server data.59      } else if (!nextReadyState.aborted) {60        warning(61          false,62          'RelayReadyState: Invalid state change from `%s` to `%s`.',63          JSON.stringify(prevReadyState),64          JSON.stringify(nextReadyState),65        );66      }67      return;68    }69    this._mergeState(nextReadyState, newEvents);70  }71  _mergeState(72    nextReadyState: PartialReadyState,73    newEvents: ?Array<ReadyStateEvent>,74  ): void {75    this._readyState = {76      ...this._readyState,77      ...nextReadyState,78      events:79        newEvents && newEvents.length80          ? [...this._readyState.events, ...newEvents]81          : this._readyState.events,82    };83    if (this._scheduled) {84      return;85    }...

Full Screen

Full Screen

background.js

Source:background.js Github

copy

Full Screen

...29}30Chromoon.prototype.onPopExec = function(arg){31}32Chromoon.prototype.setState = function(newState){33	this._mergeState(newState);34	// send state to Pop35	this._sendDataToChromeMessage('_set_data_for_pop', this.state);36	// send state to page37	this._sendStateToPage(this.state);38	// on state change39	this._onStateChange();40}41Chromoon.prototype._mergeState = function(newState){42	for(i in newState){43		this.state[i] = newState[i];44	}45}46Chromoon.prototype._onMessage = function(request, sender) {47	switch(request.action){48		case '_set_data_for_bg':49			this._mergeState(request.source);50			this._onStateChange();51			if(this._onStateChangeFromListener){ this._onStateChangeFromListener(this, this.state); };52			break;53		case '_give_me_state_for_pop':54			this._sendDataToChromeMessage('_set_data_for_pop', this.state);55			break;56	}57}...

Full Screen

Full Screen

RTCRtpSender.js

Source:RTCRtpSender.js Github

copy

Full Screen

...13    replaceTrack = (track: MediaStreamTrack | null) => {14        return new Promise((resolve, reject) => {15            WebRTCModule.peerConnectionTransceiverReplaceTrack(this._transceiver._peerConnectionId, this._transceiver.id, track ? track.id : null, (successful, data) => {16                if (successful) {17                    this._transceiver._mergeState(data.state);18                    resolve();19                } else {20                    reject(new Error(data));21                }22            });23        });24    }...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('getIframeBody', () => {2  return (3      .get('iframe[data-cy=iframe]')4      .its('0.contentDocument.body')5      .should('not.be.empty')6      .then(cy.wrap)7  );8});9Cypress.Commands.add('getIframeBody', () => {10  return (11      .get('iframe[data-cy=iframe]')12      .its('0.contentDocument.body')13      .should('not.be.empty')14      .then(cy.wrap)15  );16});17Cypress.Commands.add('getIframeBody', () => {18  return (19      .get('iframe[data-cy=iframe]')20      .its('0.contentDocument.body')21      .should('not.be.empty')22      .then(cy.wrap)23  );24});25Cypress.Commands.add('getIframeBody', () => {26  return (27      .get('iframe[data-cy=iframe]')28      .its('0.contentDocument.body')29      .should('not.be.empty')30      .then(cy.wrap)31  );32});33Cypress.Commands.add('getIframeBody', () => {

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("mergeState", (state) => {2  cy.window().then((win) => {3    win.store._mergeState(state);4  });5});6Cypress.Commands.add("getState", () => {7  cy.window().then((win) => {8    return win.store.getState();9  });10});11Cypress.Commands.add("dispatch", (action) => {12  cy.window().then((win) => {13    win.store.dispatch(action);14  });15});16Cypress.Commands.add("subscribe", (callback) => {17  cy.window().then((win) => {18    win.store.subscribe(callback);19  });20});21Cypress.Commands.add("unsubscribe", (callback) => {22  cy.window().then((win) => {23    win.store.unsubscribe(callback);24  });25});26Cypress.Commands.add("getStore", () => {27  cy.window().then((win) => {28    return win.store;29  });30});31Cypress.Commands.add("getActions", () => {32  cy.window().then((win) => {33    return win.store.getActions();34  });35});36Cypress.Commands.add("clearActions", () => {37  cy.window().then((win) => {38    win.store.clearActions();39  });40});41Cypress.Commands.add("replaceReducer", (reducer) => {42  cy.window().then((win) => {43    win.store.replaceReducer(reducer);44  });45});46Cypress.Commands.add("reset", () => {47  cy.window().then((win) => {48    win.store.reset();49  });50});51Cypress.Commands.add("replaceState", (state) => {52  cy.window().then((win) => {53    win.store.replaceState(state);54  });55});56Cypress.Commands.add("getState", () => {57  cy.window().then((win) => {58    return win.store.getState();59  });60});

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress._mergeState = (obj) => {2  return Cypress._.merge(Cypress.state, obj)3}4Cypress._resetState = () => {5  Cypress.state = {}6}7Cypress._clearLocalStorage = () => {8  window.localStorage.clear()9}10Cypress._clearSessionStorage = () => {11  window.sessionStorage.clear()12}13Cypress._clearCookies = () => {14  window.document.cookie.split(";").forEach(function(c) {15      .replace(/^ +/, "")16      .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");17  });18}19Cypress._clearLocalStorage = () => {20  window.localStorage.clear()21}22Cypress._clearSessionStorage = () => {23  window.sessionStorage.clear()24}25Cypress._clearCookies = () => {26  window.document.cookie.split(";").forEach(function(c) {27      .replace(/^ +/, "")28      .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");29  });30}31Cypress._clearLocalStorage = () => {32  window.localStorage.clear()33}34Cypress._clearSessionStorage = () => {35  window.sessionStorage.clear()36}37Cypress._clearCookies = () => {38  window.document.cookie.split(";").forEach(function(c) {39      .replace(/^ +/, "")40      .replace(/=.*/, "=;expires=" + new Date().toUTCString() + ";path=/");41  });42}43Cypress._clearLocalStorage = () => {44  window.localStorage.clear()45}46Cypress._clearSessionStorage = () => {47  window.sessionStorage.clear()48}

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.overwrite('get', (originalFn, subject, selector, options) => {2  const result = originalFn(subject, selector, options)3  const state = Cypress._.merge({}, Cypress.state(), {4    currentTest: {5    },6  })7  Cypress._.merge(Cypress, {8    state() {9    },10  })11})12Cypress.Commands.overwrite('get', (originalFn, subject, selector, options) => {13  const result = originalFn(subject, selector, options)14  const state = Cypress._.merge({}, Cypress.state(), {15    currentTest: {16    },17  })18  Cypress._.merge(Cypress, {19    state() {20    },21  })22})23Cypress.Commands.overwrite('get', (originalFn, subject, selector, options) => {24  const result = originalFn(subject, selector, options)25  const state = Cypress._.merge({}, Cypress.state(), {26    currentTest: {27    },28  })29  Cypress._.merge(Cypress, {30    state() {31    },32  })33})34Cypress.Commands.overwrite('get', (originalFn, subject, selector, options) => {35  const result = originalFn(subject, selector, options)36  const state = Cypress._.merge({}, Cypress.state(), {37    currentTest: {38    },39  })40  Cypress._.merge(Cypress, {41    state() {42    },43  })44})45Cypress.Commands.overwrite('get', (originalFn, subject, selector, options) => {46  const result = originalFn(subject, selector, options)47  const state = Cypress._.merge({}, Cypress.state(), {48    currentTest: {49    },50  })51  Cypress._.merge(Cypress, {52    state() {

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('fillAndSubmit', (email, password) => {2    cy.get('#email').type(email)3    cy.get('#password').type(password)4    cy.get('#submit').click()5})6describe('Login', () => {7    it('should login with correct credentials', () => {8        cy.fillAndSubmit('

Full Screen

Using AI Code Generation

copy

Full Screen

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('

Full Screen

Cypress Tutorial

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.

Chapters:

  1. What is Cypress? -
  2. Why Cypress? - Learn why Cypress might be a good choice for testing your web applications.
  3. Features of Cypress Testing - Learn about features that make Cypress a powerful and flexible tool for testing web applications.
  4. Cypress Drawbacks - Although Cypress has many strengths, it has a few limitations that you should be aware of.
  5. Cypress Architecture - Learn more about Cypress architecture and how it is designed to be run directly in the browser, i.e., it does not have any additional servers.
  6. Browsers Supported by Cypress - Cypress is built on top of the Electron browser, supporting all modern web browsers. Learn browsers that support Cypress.
  7. Selenium vs Cypress: A Detailed Comparison - Compare and explore some key differences in terms of their design and features.
  8. Cypress Learning: Best Practices - Take a deep dive into some of the best practices you should use to avoid anti-patterns in your automation tests.
  9. How To Run Cypress Tests on LambdaTest? - Set up a LambdaTest account, and now you are all set to learn how to run Cypress tests.

Certification

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.

YouTube

Watch this 3 hours of complete tutorial to learn the basics of Cypress and various Cypress commands with the Cypress testing at LambdaTest.

Run Cypress automation tests on LambdaTest cloud grid

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

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful