在 webdriverio v5 + mocha 中缓慢加载 qa 环境超时

如何解决在 webdriverio v5 + mocha 中缓慢加载 qa 环境超时

伙计们,我的 qa 环境加载速度非常慢,我想知道是否有人能想到我没有想到的任何其他选项。 真的很感激这里的一些帮助。 详细挑战如下。

挑战细节, browser.url(‘/uri’) 超时,有关失败的更多详细信息,请参阅运行时日志。 但是,将 mochaOpts 超时增加到 120000 次测试通过。对于我所面临的这个特定问题,增加超时似乎是最受欢迎的答案,请参见此处 - https://github.com/mochajs/mocha/issues/2025
可以想象测试非常慢,测试在 chrome 中通过,在 Firefox 中失败

依赖

"@wdio/cli": "^5.18.6","@wdio/dot-reporter": "^5.18.6","@wdio/local-runner": "^5.18.6","@wdio/mocha-framework": "^5.18.6","@wdio/selenium-standalone-service": "^5.16.10","@wdio/spec-reporter": "^5.18.6","@wdio/sync": "^5.18.6","babel-preset-env": "^1.7.0","babel-register": "^6.26.0","chai": "^4.1.2","chromedriver": "^80.0.2","cross-env": "^7.0.2","dotenv": "^8.2.0","eslint": "^7.15.0","eslint-config-airbnb-base": "^14.2.1","eslint-plugin-import": "^2.22.1","eslint-plugin-wdio": "^6.6.0","mochawesome-report-generator": "^3.1.3","rimraf": "^3.0.2","selenium-standalone": "^6.17.0","shelljs": "^0.8.2","wdio-chromedriver-service": "^6.0.1","wdio-mochawesome-reporter": "^3.2.0","webdriverio": "^6.0.15"

Wdio.conf.js

const fs = require('fs');
const properties = require('./test-properties.json');


let baseUrl = 'https://<qa.url>';


if (process.env.ENV === 'live') {
  baseUrl = 'https://<qa.url>';
} else if (process.env.ENV === 'stage') {
  baseUrl = 'https://<qa.url>';
}


const outputFolder = './output';


const browserCapabilities = {
  chrome: {
    browserName: 'chrome','goog:chromeOptions': {
      //  args: ['--headless','--disable-gpu'],},firefox: {
    browserName: 'firefox','moz:firefoxOptions': {
      //  args: ['-headless'],}
};


exports.config = {
  //
  // ====================
  // Runner Configuration
  // ====================
  //
  // WebdriverIO allows it to run your tests in arbitrary locations (e.g. locally or
  // on a remote machine).
  runner: 'local',//
  // ==================
  // Specify Test Files
  // ==================
  // Define which test specs should run. The pattern is relative to the directory
  // from which `wdio` was called. Notice that,if you are calling `wdio` from an
  // NPM script (see https://docs.npmjs.com/cli/run-script) then the current working
  // directory is where your package.json resides,so `wdio` will be called from there.
  //
  specs: ['./tests/specs/**/*.js'],// Patterns to exclude.
  exclude: [
    // 'path/to/excluded/files'
  ],//
  // ============
  // Capabilities
  // ============
  // Define your capabilities here. WebdriverIO can run multiple capabilities at the same
  // time. Depending on the number of capabilities,WebdriverIO launches several test
  // sessions. Within your capabilities you can overwrite the spec and exclude options in
  // order to group specific specs to a specific capability.
  //
  // First,you can define how many instances should be started at the same time. Let's
  // say you have 3 different capabilities (Chrome,Firefox,and Safari) and you have
  // set maxInstances to 1; wdio will spawn 3 processes. Therefore,if you have 10 spec
  // files and you set maxInstances to 10,all spec files will get tested at the same time
  // and 30 processes will get spawned. The property handles how many capabilities
  // from the same test should run tests.
  //
  maxInstances: 1,//
  // If you have trouble getting all important capabilities together,check out the
  // Sauce Labs platform configurator - a great tool to configure your capabilities:
  // https://docs.saucelabs.com/reference/platforms-configurator
  //
  capabilities: properties.browsers.map((browser) => browserCapabilities[browser]),//
  // ===================
  // Test Configurations
  // ===================
  // Define all options that are relevant for the WebdriverIO instance here
  //
  // Level of logging verbosity: trace | debug | info | warn | error | silent
  logLevel: 'debug',//
  // Set specific log levels per logger
  // loggers:
  // - webdriver,webdriverio
  // - @wdio/applitools-service,@wdio/browserstack-service,// @wdio/devtools-service,@wdio/sauce-service
  // - @wdio/mocha-framework,@wdio/jasmine-framework
  // - @wdio/local-runner,@wdio/lambda-runner
  // - @wdio/sumologic-reporter
  // - @wdio/cli,@wdio/config,@wdio/sync,@wdio/utils
  // Level of logging verbosity: trace | debug | info | warn | error | silent
  // logLevels: {
  //     webdriver: 'info',//     '@wdio/applitools-service': 'info'
  // },//
  // If you only want to run your tests until a specific amount of tests have Failed use
  // bail (default is 0 - don't bail,run all tests).
  bail: 0,// Saves a screenshot to a given path if a command fails.
  screenshotPath: `${outputFolder}/errorShots/`,//
  // Set a base URL in order to shorten url command calls. If your `url` parameter starts
  // with `/`,the base url gets prepended,not including the path portion of your baseUrl.
  // If your `url` parameter starts without a scheme or `/` (like `some/path`),the base url
  // gets prepended directly.
  baseUrl,//
  // Default timeout for all waitFor* commands.
  waitforTimeout: 30000,//
  // Default timeout in milliseconds for request
  // if browser driver or grid doesn't send response
  connectionRetryTimeout: 90000,//
  // Default request retries count
  connectionRetryCount: 3,//
  // Test runner services
  // Services take over a specific job you don't want to take care of. They enhance
  // your test setup with almost no effort. Unlike plugins,they don't add new
  // commands. Instead,they hook themselves up into the test process.
  services: ['selenium-standalone'],// Framework you want to run your specs with.
  // The following are supported: Mocha,Jasmine,and Cucumber
  // see also: https://webdriver.io/docs/frameworks.html
  //
  // Make sure you have the wdio adapter package for the specific framework installed
  // before running any tests.
  framework: 'mocha',//
  // The number of times to retry the entire specfile when it fails as a whole
  // specFileRetries: 1,//
  // Whether or not retried specfiles should be retried immediately
  // or deferred to the end of the queue
  // specFileRetriesDeferred: false,//
  // Test reporter for stdout.
  // The only one supported by default is 'dot'
  // see also: https://webdriver.io/docs/dot-reporter.html
  reporters: [
    'dot',[
      'mochawesome',{
        outputDir: `${outputFolder}/logs`,includeScreenshots: true,screenshotUseRelativePath: false,],//
  // Options to be passed to Mocha.
  // See the full list at http://mochajs.org/
  mochaOpts: {
    ui: 'bdd',timeout: 40000,require: 'babel-core/register',//
  // =====
  // Hooks
  // =====
  // WebdriverIO provides several hooks you can use to interfere with the test
  // process in order to enhance
  // it and to build services around it. You can either apply a single function or an array of
  // methods to it. If one of them returns with a promise,WebdriverIO will
  // wait until that promise got resolved to continue.


  /**
       * Gets executed once before all workers get launched.
       * @param {Object} config wdio configuration object
       * @param {Array.<Object>} capabilities list of capabilities details
       */
  onPrepare: () => {
    const screenshotsFolder = `${outputFolder}/screenshots`;
    const errorshotsFolder = `${outputFolder}/errorshots`;


    if (!fs.existsSync(screenshotsFolder)) {
      fs.mkdirsync(screenshotsFolder,{ recursive: true });
    }


    if (!fs.existsSync(errorshotsFolder)) {
      fs.mkdirsync(errorshotsFolder,{ recursive: true });
    }
  },/**
       * Gets executed before a worker process is spawned and can be used to initialise specific
       * service for that worker as well as modify runtime environments in an async fashion.
       * @param  {String} cid      capability id (e.g 0-0)
       * @param  {[type]} caps     object containing capabilities for session that will be
       *                           spawn in the worker
       * @param  {[type]} specs    specs to be run in the worker process
       * @param  {[type]} args     object that will be merged with the main configuration once
       *                           worker is initialised
       * @param  {[type]} execArgv list of string arguments passed to the worker process
       */
  // onWorkerStart: function (cid,caps,specs,args,execArgv) {
  // },/**
       * Gets executed just before initialising the webdriver session and test framework.
       * It allows you to manipulate configurations depending on the capability or spec.
       * @param {Object} config wdio configuration object
       * @param {Array.<Object>} capabilities list of capabilities details
       * @param {Array.<String>} specs List of spec file paths that are to be run
       */
  // beforeSession: function (config,capabilities,specs) {
  // },/**
       * Gets executed before test execution begins. At this point you can access to all global
       * variables like `browser`. It is the perfect place to define custom commands.
       * @param {Array.<Object>} capabilities list of capabilities details
       * @param {Array.<String>} specs List of spec file paths that are to be run
       */
  before() {
    // Chai dependency
    global.expect = require('chai').expect;
  },/**
       * Runs before a WebdriverIO command gets executed.
       * @param {String} commandName hook command name
       * @param {Array} args arguments that command would receive
       */
  // beforeCommand: function (commandName,args) {
  // },/**
       * Hook that gets executed before the suite starts
       * @param {Object} suite suite details
       */
  // beforeSuite: function (suite) {
  // },/**
       * Function to be executed before a test (in Mocha/Jasmine) starts.
       */
  // beforeTest: function (test,context) {
  // },/**
       * Hook that gets executed _before_ a hook within the suite starts (e.g. runs before calling
       * beforeEach in Mocha)
       */
  // beforeHook: function (test,/**
       * Hook that gets executed _after_ a hook within the suite starts (e.g. runs after calling
       * afterEach in Mocha)
       */
  // afterHook: function (test,context,{ error,result,duration,passed,retries }) {
  // },/**
       * Function to be executed after a test (in Mocha/Jasmine).
       */
  afterTest: function afterTest(test,{
    error,retries,}) {
    if (test.passed) return;


    const shotPath = `${outputFolder}/errorshots/${test.fullTitle.replace(/[ :]/g,'-')}.png`;
    browser.saveScreenshot(shotPath);
  },/**
       * Hook that gets executed after the suite has ended
       * @param {Object} suite suite details
       */
  // afterSuite: function (suite) {
  // },/**
       * Runs after a WebdriverIO command gets executed
       * @param {String} commandName hook command name
       * @param {Array} args arguments that command would receive
       * @param {Number} result 0 - command success,1 - command error
       * @param {Object} error error object if any
       */
  // afterCommand: function (commandName,error) {
  // },/**
       * Gets executed after all tests are done. You still have access to all global variables from
       * the test.
       * @param {Number} result 0 - test pass,1 - test fail
       * @param {Array.<Object>} capabilities list of capabilities details
       * @param {Array.<String>} specs List of spec file paths that ran
       */
  // after: function (result,/**
       * Gets executed right after terminating the webdriver session.
       * @param {Object} config wdio configuration object
       * @param {Array.<Object>} capabilities list of capabilities details
       * @param {Array.<String>} specs List of spec file paths that ran
       */
  // afterSession: function (config,/**
       * Gets executed after all workers got shut down and the process is about to exit. An error
       * thrown in the onComplete hook will result in the test run failing.
       * @param {Object} exitCode 0 - success,1 - fail
       * @param {Object} config wdio configuration object
       * @param {Array.<Object>} capabilities list of capabilities details
       * @param {<Object>} results object containing test results
       */
  // onComplete: function(exitCode,config,results) {
  // },/**
       * Gets executed when a refresh happens.
       * @param {String} oldSessionId session ID of the old session
       * @param {String} newSessionId session ID of the new session
       */
  // onReload: function(oldSessionId,newSessionId) {
  // }
};

测试

describe('url test',function() {
    it('browser url',function() {
        browser.url(‘/uri')
    })
})

运行时日志

Execution of 1 spec files started at 2021-05-03T11:07:12.561Z


2021-05-03T11:07:12.563Z DEBUG @wdio/utils:initialiseServices: initialise wdio service "selenium-standalone"
2021-05-03T11:07:12.679Z INFO @wdio/cli:launcher: Run onPrepare hook
2021-05-03T11:07:18.062Z INFO @wdio/local-runner: Start worker 0-0 with arg: --spec,./tests/specs/fieldsValidation.js
[0-0] 2021-05-03T11:07:18.404Z INFO @wdio/local-runner: Run worker command: run
[0-0] RUNNING in chrome - /tests/specs/fieldsValidation.js
[0-0] 2021-05-03T11:07:18.557Z DEBUG @wdio/local-runner:utils: init remote session
2021-05-03T11:07:18.558Z INFO webdriverio: Initiate new session using the webdriver protocol
[0-0] 2021-05-03T11:07:18.560Z INFO webdriver: [POST] http://127.0.0.1:4444/wd/hub/session
[0-0] 2021-05-03T11:07:18.560Z INFO webdriver: DATA {
  capabilities: {
    alwaysMatch: { browserName: 'chrome','goog:chromeOptions': {} },firstMatch: [ {} ]
  },desiredCapabilities: { browserName: 'chrome','goog:chromeOptions': {} }
}
[0-0] 2021-05-03T11:07:22.315Z INFO webdriver: COMMAND navigateto("<QA.URL>")
[0-0] 2021-05-03T11:07:22.316Z INFO webdriver: [POST] http://127.0.0.1:4444/wd/hub/session/d31910ee61b50f976a31942e34d7aa82/url
[0-0] 2021-05-03T11:07:22.316Z INFO webdriver: DATA { url: 'https://<QA.URL>' }
[0-0] Error in "url test brower url"
Timeout of 40000ms exceeded. For async tests and hooks,ensure "done()" is called; if returning a Promise,ensure it resolves. (tests/specs/fieldsValidation.js)
[0-0] 2021-05-03T11:08:02.319Z INFO webdriver: COMMAND deleteSession()
[0-0] 2021-05-03T11:08:02.319Z INFO webdriver: [DELETE] http://127.0.0.1:4444/wd/hub/session/d31910ee61b50f976a31942e34d7aa82
[0-0] 2021-05-03T11:08:38.407Z INFO webdriver: COMMAND takeScreenshot()
2021-05-03T11:08:38.408Z INFO webdriver: [GET] http://127.0.0.1:4444/wd/hub/session/d31910ee61b50f976a31942e34d7aa82/screenshot
[0-0] 2021-05-03T11:08:38.502Z DEBUG webdriver: request Failed due to response error: invalid session id
[0-0] 2021-05-03T11:08:38.503Z ERROR webdriver: Request Failed due to invalid session id: invalid session id
    at getErrorFromresponseBody (/node_modules/webdriver/build/utils.js:121:10)
    at Request._callback (/node_modules/webdriver/build/request.js:121:64)
    at Request.self.callback (/node_modules/request/request.js:185:22)
    at Request.emit (events.js:311:20)
    at Request.EventEmitter.emit (domain.js:482:12)
    at Request.<anonymous> (/node_modules/request/request.js:1154:10)
    at Request.emit (events.js:311:20)
    at Request.EventEmitter.emit (domain.js:482:12)
    at IncomingMessage.<anonymous> (/node_modules/request/request.js:1076:12)
    at Object.onceWrapper (events.js:417:28)
[0-0] 2021-05-03T11:08:38.514Z ERROR @wdio/sync: invalid session id
    at Object.afterTest (/wdio.conf.js:267:13)
[0-0] Error in "AfterTest Hook"
invalid session id
2021-05-03T11:08:38.569Z DEBUG @wdio/local-runner: Runner 0-0 finished with exit code 1
[0-0] Failed in chrome - /tests/specs/fieldsValidation.js
2021-05-03T11:08:38.570Z INFO @wdio/cli:launcher: Run onComplete hook
2021-05-03T11:08:38.570Z INFO @wdio/selenium-standalone-service: shutting down all browsers


 "dot" Reporter:
F


Spec Files:      0 passed,1 Failed,1 total (100% completed) in 00:01:26 


2021-05-03T11:08:38.571Z INFO @wdio/local-runner: Shutting down spawned worker
2021-05-03T11:08:38.821Z INFO @wdio/local-runner: Waiting for 0 to shut down gracefully
2021-05-03T11:08:38.822Z INFO @wdio/local-runner: shutting down
npm ERR! code ELIFECYCLE
npm ERR! errno 1
npm ERR! exercise@1.0.0 start-file: `npm run report:clean && node ./node_modules/@wdio/cli/bin/wdio.js --spec ./tests/specs/fieldsValidation.js`
npm ERR! Exit status 1
npm ERR! 
npm ERR! Failed at the exercise@1.0.0 start-file script.
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.


npm ERR! A complete log of this run can be found in:

调试日志

0 info it worked if it ends with ok
1 verbose cli [
1 verbose cli   '/Users/testUser/.nvm/versions/node/v12.16.1/bin/node',1 verbose cli   '/Users/testUser/.nvm/versions/node/v12.16.1/bin/npm',1 verbose cli   'run',1 verbose cli   'start-file'
1 verbose cli ]
2 info using npm@6.13.4
3 info using node@v12.16.1
4 verbose run-script [ 'prestart-file','start-file','poststart-file' ]
5 info lifecycle -exercise@1.0.0~prestart-file: -exercise@1.0.0
6 info lifecycle -exercise@1.0.0~start-file: -exercise@1.0.0
7 verbose lifecycle -exercise@1.0.0~start-file: unsafe-perm in lifecycle true
8 verbose lifecycle -exercise@1.0.0~start-file: PATH: /Users/testUser/.nvm/versions/node/v12.16.1/lib/node_modules/npm/node_modules/npm-lifecycle/node-gyp-bin:/Users/testUser/projects/-exercise/node_modules/.bin:/Users/testUser/.nvm/versions/node/v12.16.1/bin:/usr/local/share/npm/bin:/usr/local/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/munki:/usr/local/share/npm/bin
9 verbose lifecycle -exercise@1.0.0~start-file: CWD: /Users/testUser/projects/-exercise
10 silly lifecycle -exercise@1.0.0~start-file: Args: [
10 silly lifecycle   '-c',10 silly lifecycle   'npm run report:clean && node ./node_modules/@wdio/cli/bin/wdio.js --spec ./tests/specs/fieldsValidation.js'
10 silly lifecycle ]
11 silly lifecycle -exercise@1.0.0~start-file: Returned: code: 1  signal: null
12 info lifecycle -exercise@1.0.0~start-file: Failed to exec start-file script
13 verbose stack Error: -exercise@1.0.0 start-file: `npm run report:clean && node ./node_modules/@wdio/cli/bin/wdio.js --spec ./tests/specs/fieldsValidation.js`
13 verbose stack Exit status 1
13 verbose stack     at EventEmitter.<anonymous> (/Users/testUser/.nvm/versions/node/v12.16.1/lib/node_modules/npm/node_modules/npm-lifecycle/index.js:332:16)
13 verbose stack     at EventEmitter.emit (events.js:311:20)
13 verbose stack     at ChildProcess.<anonymous> (/Users/testUser/.nvm/versions/node/v12.16.1/lib/node_modules/npm/node_modules/npm-lifecycle/lib/spawn.js:55:14)
13 verbose stack     at ChildProcess.emit (events.js:311:20)
13 verbose stack     at maybeClose (internal/child_process.js:1021:16)
13 verbose stack     at Process.ChildProcess._handle.onexit (internal/child_process.js:286:5)
14 verbose pkgid -exercise@1.0.0
15 verbose cwd /Users/testUser/projects/-exercise
16 verbose Darwin 19.6.0
17 verbose argv "/Users/testUser/.nvm/versions/node/v12.16.1/bin/node" "/Users/testUser/.nvm/versions/node/v12.16.1/bin/npm" "run" "start-file"
18 verbose node v12.16.1
19 verbose npm  v6.13.4
20 error code ELIFECYCLE
21 error errno 1
22 error -exercise@1.0.0 start-file: `npm run report:clean && node ./node_modules/@wdio/cli/bin/wdio.js --spec ./tests/specs/fieldsValidation.js`
22 error Exit status 1
23 error Failed at the -exercise@1.0.0 start-file script.
23 error This is probably not a problem with npm. There is likely additional logging output above.
24 verbose exit [ 1,true ]
Challenge in detail,`browser.url(‘/uri’)` timesout,please see about run time logs for more details on the failure.
However,when I increase the `mochaOpts` timeout to 120000 test passes. Increasing timeout seems to be the most popular answer for this particular problem I’m facing see here - https://github.com/mochajs/mocha/issues/2025.  
As you can imagine test is extremely slow,test passes in chrome and fails in Firefox even for `mochaOpts` timeout to 240000

我也尝试过以下方法

如果您需要更多信息,请告诉我。 非常感谢这方面的帮助。

谢谢大家,

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?
Java在半透明框架/面板/组件上重新绘画。
Java“ Class.forName()”和“ Class.forName()。newInstance()”之间有什么区别?
在此环境中不提供编译器。也许是在JRE而不是JDK上运行?
Java用相同的方法在一个类中实现两个接口。哪种接口方法被覆盖?
Java 什么是Runtime.getRuntime()。totalMemory()和freeMemory()?
java.library.path中的java.lang.UnsatisfiedLinkError否*****。dll
JavaFX“位置是必需的。” 即使在同一包装中
Java 导入两个具有相同名称的类。怎么处理?
Java 是否应该在HttpServletResponse.getOutputStream()/。getWriter()上调用.close()?
Java RegEx元字符(。)和普通点?