vue项目接入e2e自动化测试


项目开发到一定阶段,需要接入自动化测试,调研了一线现有的自动化测试方案,以为vue-cli默认使用的nightwatch的0.9+的版本,其适用的chrome的版本很低,我们自己的浏览器早都80+了,他还适用70多,所以没有采用默认的,同时我们的项目是开始没有采用脚手架的配置,所以是单独安装配置的:
在这里插入图片描述
下面开始我们的配置: night watch

1.安装night-watch

npm install nightwatch

在这里插入图片描述
可以看到最新的1.3.7(官网最新的应该是1.3.8,npm仓库最新的是1.3.7)安装成功

2.安装浏览器驱动

在这里插入图片描述
可以根据需求来进行安装,我这里只安装chrome的内核驱动:

npm install chromedriver --save-dev

过程会稍微慢点,失败的话可以尝试cnpm
在这里插入图片描述

3.关于Selenium(音译:斯利涅姆) Server

有点类似与nginx,nightwath 自己不能直接去调起浏览器,特别是当前市场上的很多浏览器,nightwatch通过它来对接各个浏览器,在nightwath1.0以上之后:
在这里插入图片描述

1.自版本1.0以上之后,如果你只需要一个浏览器调试可以不用安装selenium server,
2.或者你需要在ie上调试

因为我们这里只需要一个chrome driver,所以也就不需要了

4.配置文件

然后我们需要在项目的根目录创建一个用于启动nightwatch的配置文件:nightwatch.json或者nightwatch.conf.js
这里我们偷个懒:
在这里插入图片描述
在版本1.3之后,如果根目录如果没有配置上面提到的两个文件中的任何一个,那个nightwatch会自动为我们创建一个,反之则不会有任何操作。

nightwatch --help

在这里插入图片描述
可以看到有这么多运行的参数

nightwatch

直接运行nightwatch,会报错,但是我们可以看到我们的根目录已经默认生成了一个默认的nightwatch配置:
在这里插入图片描述

// Autogenerated by Nightwatch
// Refer to the online docs for more details: https://nightwatchjs.org/gettingstarted/configuration/
const Services = {}; loadServices();

module.exports = {
  // An array of folders (excluding subfolders) where your tests are located;
  // if this is not specified, the test source must be passed as the second argument to the test runner.
  src_folders: [],

  // See https://nightwatchjs.org/guide/working-with-page-objects/
  page_objects_path: '',

  // See https://nightwatchjs.org/guide/extending-nightwatch/#writing-custom-commands
  custom_commands_path:  '',

  // See https://nightwatchjs.org/guide/extending-nightwatch/#writing-custom-assertions
  custom_assertions_path: '',

  // See https://nightwatchjs.org/guide/#external-globals
  globals_path : '',

  webdriver: {},

  test_settings: {
    default: {
      disable_error_log: false,
      launch_url: 'https://nightwatchjs.org',

      screenshots: {
        enabled: false,
        path: 'screens',
        on_failure: true
      },

      desiredCapabilities: {
        browserName : 'firefox'
      },

      webdriver: {
        start_process: true,
        server_path: (Services.geckodriver ? Services.geckodriver.path : '')
      }
    },

    safari: {
      desiredCapabilities : {
        browserName : 'safari',
        alwaysMatch: {
          acceptInsecureCerts: false
        }
      },
      webdriver: {
        port: 4445,
        start_process: true,
        server_path: '/usr/bin/safaridriver'
      }
    },

    firefox: {
      desiredCapabilities : {
        browserName : 'firefox',
        alwaysMatch: {
          // Enable this if you encounter unexpected SSL certificate errors in Firefox
          // acceptInsecureCerts: true,
          'moz:firefoxOptions': {
            args: [
              // '-headless',
              // '-verbose'
            ],
          }
        }
      },
      webdriver: {
        start_process: true,
        port: 4444,
        server_path: (Services.geckodriver ? Services.geckodriver.path : ''),
        cli_args: [
          // very verbose geckodriver logs
          // '-vv'
        ]
      }
    },

    chrome: {
      desiredCapabilities : {
        browserName : 'chrome',
        chromeOptions : {
          // This tells Chromedriver to run using the legacy JSONWire protocol (not required in Chrome 78)
          // w3c: false,
          // More info on Chromedriver: https://sites.google.com/a/chromium.org/chromedriver/
          args: [
            //'--no-sandbox',
            //'--ignore-certificate-errors',
            //'--allow-insecure-localhost',
            //'--headless'
          ]
        }
      },

      webdriver: {
        start_process: true,
        port: 9515,
        server_path: (Services.chromedriver ? Services.chromedriver.path : ''),
        cli_args: [
          // --verbose
        ]
      }
    },

    //
    // Configuration for when using the browserstack.com cloud service               |
    //                                                                               |
    // Please set the username and access key by setting the environment variables:  |
    // - BROWSERSTACK_USER                                                           |
    // - BROWSERSTACK_KEY                                                            |
    // .env files are supported                                                      |
    //
    browserstack: {
      selenium: {
        host: 'hub-cloud.browserstack.com',
        port: 443
      },
      // More info on configuring capabilities can be found on:
      // https://www.browserstack.com/automate/capabilities?tag=selenium-4
      desiredCapabilities: {
        'bstack:options' : {
          local: 'false',
          userName: '${BROWSERSTACK_USER}',
          accessKey: '${BROWSERSTACK_KEY}',
        }
      },

      disable_error_log: true,
      webdriver: {
        keep_alive: true,
        start_process: false
      }
    },

    'browserstack.chrome': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions : {
          // This tells Chromedriver to run using the legacy JSONWire protocol
          // More info on Chromedriver: https://sites.google.com/a/chromium.org/chromedriver/
          w3c: false
        }
      }
    },

    'browserstack.firefox': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'firefox'
      }
    },

    'browserstack.ie': {
      extends: 'browserstack',
      desiredCapabilities: {
        browserName: 'IE',
        browserVersion: '11.0',
        'bstack:options' : {
          os: 'Windows',
          osVersion: '10',
          local: 'false',
          seleniumVersion: '3.5.2',
          resolution: '1366x768'
        }
      }
    },

    //
    // Configuration for when using the Selenium service, either locally or remote,  |
    //  like Selenium Grid                                                           |
    //
    selenium: {
      // Selenium Server is running locally and is managed by Nightwatch
      selenium: {
        start_process: true,
        port: 4444,
        server_path: (Services.seleniumServer ? Services.seleniumServer.path : ''),
        cli_args: {
          'webdriver.gecko.driver': (Services.geckodriver ? Services.geckodriver.path : ''),
          'webdriver.chrome.driver': (Services.chromedriver ? Services.chromedriver.path : '')
        }
      }
    },

    'selenium.chrome': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'chrome',
        chromeOptions : {
          w3c: false
        }
      }
    },

    'selenium.firefox': {
      extends: 'selenium',
      desiredCapabilities: {
        browserName: 'firefox',
        'moz:firefoxOptions': {
          args: [
            // '-headless',
            // '-verbose'
          ]
        }
      }
    }
  }
};

function loadServices() {
  try {
    Services.seleniumServer = require('selenium-server');
  } catch (err) {}

  try {
    Services.chromedriver = require('chromedriver');
  } catch (err) {}

  try {
    Services.geckodriver = require('geckodriver');
  } catch (err) {}
}

在这里插入图片描述
因为默认的配置,默认去找firefox的配置,上面我只安装了chrome的配置,所以并没有,因此报错了。
下面我们来看一下这个配置文件的配置的作用:

属性类型默认值描述
test_settingsobject定义所有测试环境的一个大对象,需要注意的是,一个defined 环境变量一般是必须的
webdriverobject顾名思义,配置所有web驱动的地方
src_foldersstring|array指定测试用例位置,这里如果没有定义,必须在运行时在命令行指定
seleniumobject配置selenuim server的地方
custom_commands_pathobject自定义命令的位置
custom_assertions_pathobject自定义断言的位置
page_objects_pathobject
globals_pathobject外部全局模块的位置,该模块将作为属性全局变量在主客户端实例上加载并可供测试使用。全局变量也可以在test_settings环境中定义/覆盖。
5.修改配置文件

因为我只安装了chromedriver,所以报错了,现在我们来修改配置,把项目跑起来吧
在这里插入图片描述

5.1 更新默认使用chromedriver

修改默认的firefox为chrome

default: {
      disable_error_log: false,
      launch_url: 'https://nightwatchjs.org',

      screenshots: {
        enabled: false,
        path: 'screens',
        on_failure: true
      },

      desiredCapabilities: {
        browserName : 'chrome'
        // browserName : 'firefox'
      },

      webdriver: {
        start_process: true,
        port: 9515,
        server_path: (Services.chromedriver ? Services.chromedriver.path : '')
      }
    },

再执行nightwatch
在这里插入图片描述

5.2 配置测试文件路径

在这里插入图片描述
这是我当前的路径

  1. 在test目录下新建nightwatch文件夹
  2. 在nightwatch目录下新建spec文件夹
  3. 在spec下新建一个测试文件 first.js

first.js

// For authoring Nightwatch tests, see
// http://nightwatchjs.org/guide#usage

module.exports = {
  'my first tests': function (browser) {
    browser
    // 这里的url和端口要和vue dev配置的host和port一致
      .url('http://localhost:8080')
      .waitForElementVisible('#app', 5000)
      .assert.elementPresent('.hello')
      .assert.containsText('h1', 'Welcome to Your Vue.js App')
      .assert.elementCount('img', 1)
      .end()
  }
}

然后修改nightwatch.config.js

module.exports = {
  // An array of folders (excluding subfolders) where your tests are located;
  // if this is not specified, the test source must be passed as the second argument to the test runner.
  src_folders: ['test/nightwatch/spec'],
  // src_folders: [],

到这里配置完成,开始美美的执行:

nightwatch

在这里插入图片描述
在这里插入图片描述
提示是在5000ms之后,没检测到id为app的组件,原因是什么呢,因为vue在没有编译之间,是不能直接被浏览器解析的,所以我们是看不到这个页面,也就没有办法进行测试了
然后翻nightwatch的文档
在这里插入图片描述
告诉我们如果不是原生的开发,就需要使用这种进行测试

5.3 配置runner.js

这里我参考了vue-cli生成的runner.js

// 1. start the dev server using production config
process.env.NODE_ENV = 'testing'

const webpack = require('webpack')
const DevServer = require('webpack-dev-server')

const webpackConfig = require('../../build/webpack.prod.conf')
const devConfigPromise = require('../../build/webpack.dev.conf')

let server

devConfigPromise.then(devConfig => {
  const devServerOptions = devConfig.devServer
  const compiler = webpack(webpackConfig)
  server = new DevServer(compiler, devServerOptions)
  const port = devServerOptions.port
  const host = devServerOptions.host
  return server.listen(port, host)
})
  .then(() => {
    // 2. run the nightwatch test suite against it
    // to run in additional browsers:
    //    1. add an entry in test/e2e/nightwatch.conf.js under "test_settings"
    //    2. add it to the --env flag below
    // or override the environment flag, for example: `npm run e2e -- --env chrome,firefox`
    // For more information on Nightwatch's config file, see
    // http://nightwatchjs.org/guide#settings-file
    let opts = process.argv.slice(2)
    if (opts.indexOf('--config') === -1) {
      opts = opts.concat(['--config', 'nightwatch.conf.js'])
    }
    if (opts.indexOf('--env') === -1) {
      opts = opts.concat(['--env', 'chrome'])
    }

    const spawn = require('cross-spawn')
    const runner = spawn('./node_modules/.bin/nightwatch', opts, { stdio: 'inherit' })
    console.log(runner)
    runner.on('exit', function (code) {
      server.close()
      process.exit(code)
    })

    runner.on('error', function (err) {
      server.close()
      throw err
    })
  })

上面的代码的意思就是启动vue-dev服务之后,再启动nightwatch的测试,这样就能解决上面我们遇到的问题。

node test/nightwatch/runner.js

在这里插入图片描述
这里就运行成功啦

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值