js e2e测试-nightwatch入门

来源:互联网 发布:网络用语1是什么意思 编辑:程序博客网 时间:2024/05/29 13:42

nightwatch是基于selenium(webdriver)的e2e测试框架。

selenium还需要java环境。提前安装java环境。

实现效果:自动打开bing页面,搜索内容,关闭页面。

1 安装

mkdir nightwatchDemocd nightwatchDemonpm init -ynpm install nightwatch selenium-server chromedriver --save

2 创建nightwatch.conf.js

const path = require('path');module.exports = {  // 测试文件入口  src_folders: ['tests'],  // 输出报表路径  output_folder: 'reports',  // selenium配置  selenium: {    start_process: true,    server_path: require('selenium-server').path,    host: '127.0.0.1',    // selenium log输出    log_path: 'reports',    port: 9090,    cli_args: {      'webdriver.chrome.driver': require('chromedriver').path,      'webdriver.gecko.driver': require('chromedriver').path    }  },  test_settings: {    default: {      launch_url: 'http://localhost',      selenium_port: 9090,      selenium_host: 'localhost',      silent: true,      screenshots: {        enabled: false,        path: ''      }    },    chrome: {      desiredCapabilities: {        browserName: 'chrome',        javascriptEnabled: true,        acceptSslCerts: true      }    }  }};

3 根据配置的src_folders创建tests文件夹,下面创建个demo.js

module.exports = {  'Find the answer.': function(client) {    // 定义 Bing 页面中的节点.    const searchInput = '#sb_form_q';    const searchBtn = '#sb_form_go';    const question = '测试nightwatch自动打开网站搜索';    // 启动浏览器并打开 bing.com.    client.url('http://bing.com').maximizeWindow();    // 确保 "body" 和输入框可以使用.    client.expect.element('body').to.be.present;    client.expect.element(searchInput).to.be.visible;    client.pause(2000); // 稍等两秒.    // 输入 "what is microsoft" 然后搜索.    client.setValue(searchInput, question);    client.click(searchBtn);    client.pause(2000);    // 截一张图然后保存到 "reports/answer.png".    client.expect.element('body').to.be.present;    client.saveScreenshot('reports/answers.png');    client.end();  }};

4 修改package.json的script字段

"scripts": {    "test": "./node_modules/.bin/nightwatch --env" },

5 运行 npm run test

成功完成,输出日志。

原创粉丝点击