How to use throwFormErrorText method in Cypress

Best JavaScript code snippet using cypress

verify.js

Source:verify.js Github

copy

Full Screen

...25  debug('checking if executable exists', executable);26  return util.isExecutableAsync(executable).then(isExecutable => {27    debug('Binary is executable? :', isExecutable);28    if (!isExecutable) {29      return throwFormErrorText(errors.binaryNotExecutable(executable))();30    }31  }).catch({32    code: 'ENOENT'33  }, () => {34    if (util.isCi()) {35      return throwFormErrorText(errors.notInstalledCI(executable))();36    }37    return throwFormErrorText(errors.missingApp(binaryDir))(stripIndent`38      Cypress executable not found at: ${chalk.cyan(executable)}39    `);40  });41};42const runSmokeTest = (binaryDir, options) => {43  let executable = state.getPathToExecutable(binaryDir);44  const onSmokeTestError = (smokeTestCommand, linuxWithDisplayEnv) => {45    return err => {46      debug('Smoke test failed:', err);47      let errMessage = err.stderr || err.message;48      debug('error message:', errMessage);49      if (err.timedOut) {50        debug('error timedOut is true');51        return throwFormErrorText(errors.smokeTestFailure(smokeTestCommand, true))(errMessage);52      }53      if (linuxWithDisplayEnv && util.isBrokenGtkDisplay(errMessage)) {54        util.logBrokenGtkDisplayWarning();55        return throwFormErrorText(errors.invalidSmokeTestDisplayError)(errMessage);56      }57      return throwFormErrorText(errors.missingDependency)(errMessage);58    };59  };60  const needsXvfb = xvfb.isNeeded();61  debug('needs Xvfb?', needsXvfb);62  /**63   * Spawn Cypress running smoke test to check if all operating system64   * dependencies are good.65   */66  const spawn = linuxWithDisplayEnv => {67    const random = _.random(0, 1000);68    const args = ['--smoke-test', `--ping=${random}`];69    if (needsSandbox()) {70      // electron requires --no-sandbox to run as root71      debug('disabling Electron sandbox');72      args.unshift('--no-sandbox');73    }74    if (options.dev) {75      executable = 'node';76      args.unshift(path.resolve(__dirname, '..', '..', '..', 'scripts', 'start.js'));77    }78    const smokeTestCommand = `${executable} ${args.join(' ')}`;79    debug('running smoke test');80    debug('using Cypress executable %s', executable);81    debug('smoke test command:', smokeTestCommand);82    debug('smoke test timeout %d ms', options.smokeTestTimeout);83    const env = _.extend({}, process.env, {84      ELECTRON_ENABLE_LOGGING: true85    });86    const stdioOptions = _.extend({}, {87      env,88      timeout: options.smokeTestTimeout89    });90    return Promise.resolve(util.exec(executable, args, stdioOptions)).catch(onSmokeTestError(smokeTestCommand, linuxWithDisplayEnv)).then(result => {91      // TODO: when execa > 1.1 is released92      // change this to `result.all` for both stderr and stdout93      // use lodash to be robust during tests against null result or missing stdout94      const smokeTestStdout = _.get(result, 'stdout', '');95      debug('smoke test stdout "%s"', smokeTestStdout);96      if (!util.stdoutLineMatches(String(random), smokeTestStdout)) {97        debug('Smoke test failed because could not find %d in:', random, result);98        const smokeTestStderr = _.get(result, 'stderr', '');99        const errorText = smokeTestStderr || smokeTestStdout;100        return throwFormErrorText(errors.smokeTestFailure(smokeTestCommand, false))(errorText);101      }102    });103  };104  const spawnInXvfb = linuxWithDisplayEnv => {105    return xvfb.start().then(() => {106      return spawn(linuxWithDisplayEnv);107    }).finally(xvfb.stop);108  };109  const userFriendlySpawn = linuxWithDisplayEnv => {110    debug('spawning, should retry on display problem?', Boolean(linuxWithDisplayEnv));111    return spawn(linuxWithDisplayEnv).catch({112      code: 'INVALID_SMOKE_TEST_DISPLAY_ERROR'113    }, () => {114      return spawnInXvfb(linuxWithDisplayEnv);115    });116  };117  if (needsXvfb) {118    return spawnInXvfb();119  } // if we are on linux and there's already a DISPLAY120  // set, then we may need to rerun cypress after121  // spawning our own Xvfb server122  const linuxWithDisplayEnv = util.isPossibleLinuxWithIncorrectDisplay();123  return userFriendlySpawn(linuxWithDisplayEnv);124};125function testBinary(version, binaryDir, options) {126  debug('running binary verification check', version); // if running from 'cypress verify', don't print this message127  if (!options.force) {128    logger.log(stripIndent`129    It looks like this is your first time using Cypress: ${chalk.cyan(version)}130    `);131  }132  logger.log(); // if we are running in CI then use133  // the verbose renderer else use134  // the default135  let renderer = util.isCi() ? verbose : 'default';136  if (logger.logLevel() === 'silent') renderer = 'silent';137  const rendererOptions = {138    renderer139  };140  const tasks = new Listr([{141    title: util.titleize('Verifying Cypress can run', chalk.gray(binaryDir)),142    task: (ctx, task) => {143      debug('clearing out the verified version');144      return state.clearBinaryStateAsync(binaryDir).then(() => {145        return Promise.all([runSmokeTest(binaryDir, options), Promise.resolve().delay(1500) // good user experience146        ]);147      }).then(() => {148        debug('write verified: true');149        return state.writeBinaryVerifiedAsync(true, binaryDir);150      }).then(() => {151        util.setTaskTitle(task, util.titleize(chalk.green('Verified Cypress!'), chalk.gray(binaryDir)), rendererOptions.renderer);152      });153    }154  }], rendererOptions);155  return tasks.run();156}157const maybeVerify = (installedVersion, binaryDir, options) => {158  return state.getBinaryVerifiedAsync(binaryDir).then(isVerified => {159    debug('is Verified ?', isVerified);160    let shouldVerify = !isVerified; // force verify if options.force161    if (options.force) {162      debug('force verify');163      shouldVerify = true;164    }165    if (shouldVerify) {166      return testBinary(installedVersion, binaryDir, options).then(() => {167        if (options.welcomeMessage) {168          logger.log();169          logger.log('Opening Cypress...');170        }171      });172    }173  });174};175const start = (options = {}) => {176  debug('verifying Cypress app');177  const packageVersion = util.pkgVersion();178  let binaryDir = state.getBinaryDir(packageVersion);179  _.defaults(options, {180    dev: false,181    force: false,182    welcomeMessage: true,183    smokeTestTimeout: VERIFY_TEST_RUNNER_TIMEOUT_MS184  });185  if (options.dev) {186    return runSmokeTest('', options);187  }188  const parseBinaryEnvVar = () => {189    const envBinaryPath = util.getEnv('CYPRESS_RUN_BINARY');190    debug('CYPRESS_RUN_BINARY exists, =', envBinaryPath);191    logger.log(stripIndent`192      ${chalk.yellow('Note:')} You have set the environment variable:193      ${chalk.white('CYPRESS_RUN_BINARY=')}${chalk.cyan(envBinaryPath)}194      This overrides the default Cypress binary path used.195    `);196    logger.log();197    return util.isExecutableAsync(envBinaryPath).then(isExecutable => {198      debug('CYPRESS_RUN_BINARY is executable? :', isExecutable);199      if (!isExecutable) {200        return throwFormErrorText(errors.CYPRESS_RUN_BINARY.notValid(envBinaryPath))(stripIndent`201          The supplied binary path is not executable202          `);203      }204    }).then(() => {205      return state.parseRealPlatformBinaryFolderAsync(envBinaryPath);206    }).then(envBinaryDir => {207      if (!envBinaryDir) {208        return throwFormErrorText(errors.CYPRESS_RUN_BINARY.notValid(envBinaryPath))();209      }210      debug('CYPRESS_RUN_BINARY has binaryDir:', envBinaryDir);211      binaryDir = envBinaryDir;212    }).catch({213      code: 'ENOENT'214    }, err => {215      return throwFormErrorText(errors.CYPRESS_RUN_BINARY.notValid(envBinaryPath))(err.message);216    });217  };218  return Promise.try(() => {219    debug('checking environment variables');220    if (util.getEnv('CYPRESS_RUN_BINARY')) {221      return parseBinaryEnvVar();222    }223  }).then(() => {224    return checkExecutable(binaryDir);225  }).tap(() => {226    return debug('binaryDir is ', binaryDir);227  }).then(() => {228    return state.getBinaryPkgAsync(binaryDir);229  }).then(pkg => {230    return state.getBinaryPkgVersion(pkg);231  }).then(binaryVersion => {232    if (!binaryVersion) {233      debug('no Cypress binary found for cli version ', packageVersion);234      return throwFormErrorText(errors.missingApp(binaryDir))(`235      Cannot read binary version from: ${chalk.cyan(state.getBinaryPkgPath(binaryDir))}236    `);237    }238    debug(`Found binary version ${chalk.green(binaryVersion)} installed in: ${chalk.cyan(binaryDir)}`);239    if (binaryVersion !== packageVersion) {240      // warn if we installed with CYPRESS_INSTALL_BINARY or changed version241      // in the package.json242      logger.log(`Found binary version ${chalk.green(binaryVersion)} installed in: ${chalk.cyan(binaryDir)}`);243      logger.log();244      logger.warn(stripIndent`245      ${logSymbols.warning} Warning: Binary version ${chalk.green(binaryVersion)} does not match the expected package version ${chalk.green(packageVersion)}246        These versions may not work properly together.247      `);248      logger.log();249    }250    return maybeVerify(binaryVersion, binaryDir, options);251  }).catch(err => {252    if (err.known) {253      throw err;254    }255    return throwFormErrorText(errors.unexpected)(err.stack);256  });257};258const isLinuxLike = () => os.platform() !== 'win32';259/**260 * Returns true if running on a system where Electron needs "--no-sandbox" flag.261 * @see https://crbug.com/638180262 *263 * On Debian we had problems running in sandbox even for non-root users.264 * @see https://github.com/cypress-io/cypress/issues/5434265 * Seems there is a lot of discussion around this issue among Electron users266 * @see https://github.com/electron/electron/issues/17972267*/268const needsSandbox = () => isLinuxLike();269module.exports = {...

Full Screen

Full Screen

xvfb.js

Source:xvfb.js Github

copy

Full Screen

...42  start: function start() {43    debug('Starting Xvfb');44    return xvfb.startAsync()["return"](null)["catch"]({45      nonZeroExitCode: true46    }, throwFormErrorText(errors.nonZeroExitCodeXvfb))["catch"](function (err) {47      if (err.known) {48        throw err;49      }50      return throwFormErrorText(errors.missingXvfb)(err);51    });52  },53  stop: function stop() {54    debug('Stopping Xvfb');55    return xvfb.stopAsync()["return"](null)["catch"](function () {// noop56    });57  },58  isNeeded: function isNeeded() {59    if (os.platform() !== 'linux') {60      return false;61    }62    if (process.env.DISPLAY) {63      var issueUrl = util.getGitHubIssueUrl(4034);64      var message = stripIndent(_templateObject(), process.env.DISPLAY, issueUrl);...

Full Screen

Full Screen

versions.js

Source:versions.js Github

copy

Full Screen

...12    if (util.getEnv('CYPRESS_RUN_BINARY')) {13      var envBinaryPath = path.resolve(util.getEnv('CYPRESS_RUN_BINARY'));14      return state.parseRealPlatformBinaryFolderAsync(envBinaryPath).then(function (envBinaryDir) {15        if (!envBinaryDir) {16          return throwFormErrorText(errors.CYPRESS_RUN_BINARY.notValid(envBinaryPath))();17        }18        debug('CYPRESS_RUN_BINARY has binaryDir:', envBinaryDir);19        return envBinaryDir;20      }).catch({ code: 'ENOENT' }, function (err) {21        return throwFormErrorText(errors.CYPRESS_RUN_BINARY.notValid(envBinaryPath))(err.message);22      });23    }24    return state.getBinaryDir();25  }).then(state.getBinaryPkgVersionAsync).then(function (binaryVersion) {26    return {27      package: util.pkgVersion(),28      binary: binaryVersion || 'not installed'29    };30  });31};32module.exports = {33  getVersions: getVersions...

Full Screen

Full Screen

Using AI Code Generation

copy

Full Screen

1import { throwFormErrorText } from 'cypress-iframe-forms'2describe('My First Test', () => {3    it('Does not do much!', () => {4        cy.contains('type').click()5        throwFormErrorText('This field is required')6    })7})8import { throwFormErrorText } from 'cypress-iframe-forms'9describe('My First Test', () => {10    it('Does not do much!', () => {11        cy.contains('type').click()12        throwFormErrorText('This field is required')13    })14})15import { throwFormErrorText } from 'cypress-iframe-forms'16describe('My First Test', () => {17    it('Does not do much!', () => {18        cy.contains('type').click()19        throwFormErrorText('This field is required')20    })21})22import { throwFormErrorText } from 'cypress-iframe-forms'23describe('My First Test', () => {24    it('Does not do much!', () => {25        cy.contains('type').click()26        throwFormErrorText('This field is required')27    })28})29import { throwFormErrorText } from 'cypress-iframe-forms'30describe('My First Test', () => {31    it('Does not do much!', () => {32        cy.contains('type').click()33        throwFormErrorText('This field is required')34    })35})36import { throwFormErrorText } from 'cypress-iframe-forms'37describe('My First Test', () => {38    it('Does not do much!', () => {39        cy.contains('type').click()40        throwFormErrorText('This field is required')41    })42})43import { throwFormErrorText } from 'cypress-iframe

Full Screen

Using AI Code Generation

copy

Full Screen

1import { throwFormErrorText } from 'cypress-iframe-forms';2describe('My First Test', () => {3  it('Does not do much!', () => {4    cy.get('iframe').then($iframe => {5      const $body = $iframe.contents().find('body')6      throwFormErrorText($body, 'Please enter a valid email address.')7    })8  })9})

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add('throwFormErrorText', (errorText) => {2    cy.get('.error').should('have.text', errorText);3});4it('should throw error when username is not entered', function () {5    cy.visit('/login');6    cy.get('#password').type('password');7    cy.get('#login').click();8    cy.throwFormErrorText('Please enter a username');9});10Running:  test.spec.js                                                       (1 of 1)11    ✓ should throw error when username is not entered (165ms)12  1 passing (1s)

Full Screen

Using AI Code Generation

copy

Full Screen

1Cypress.Commands.add("throwFormErrorText", (formErrorText, formErrorSelector) => {2  cy.get(formErrorSelector).then(($formError) => {3    if ($formError.text() !== formErrorText) {4      throw new Error("Form error text is not as expected");5    }6  });7});8describe("Form", () => {9  it("should show error text when form is submitted with invalid data", () => {10    cy.visit("/");11    cy.get("form").submit();12    cy.throwFormErrorText("Please enter valid email address", "#error");13  });14});15    at tryCatcher (node_modules/bluebird/js/release/util.js:16:23)16    at Promise._settlePromiseFromHandler (node_modules/bluebird/js/release/promise.js:547:31)17    at Promise._settlePromise (node_modules/bluebird/js/release/promise.js:604:18)18    at Promise._settlePromise0 (node_modules/bluebird/js/release/promise.js:649:10)19    at Promise._settlePromises (node_modules/bluebird/js/release/promise.js:725:18)20    at _drainQueueStep (node_modules/bluebird/js/release/async.js:93:12)21    at _drainQueue (node_modules/bluebird/js/release/async.js:86:9)22    at Async._drainQueues (node_modules/bluebird/js/release/async.js:102:5)23    at Immediate.Async.drainQueues [as _onImmediate] (node_modules/bluebird/js/release/async.js:15:14)24    at runCallback (timers.js:705:18)25    at tryOnImmediate (timers.js:676:5)26    at processImmediate (timers.js:658:5)27cy.get(formErrorSelector).then(($formError) => {28    if ($formError.text() !== formErrorText) {29      throw new Error("

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