二、Cuke test 使用chrome模拟mobile 自动化

2018-07-12  本文已影响74人  别动我名字呀

Cuke test 封装得特别好,不需要测试人员再去集成:case管理、测试报告。 非常适合自动化入门

但也正因为如此,假如碰到一些特殊的场景,想要修改框架,同时对他得封装不熟悉就会非常头疼

以下是场景是因为需要在使用浏览器模拟Mobile 的同时还需要对pc的浏览器操作的解决方案

1.web_driver.js 全部替换

require('chromedriver')
const webDriver = require('selenium-webdriver');
const { Options } = require('selenium-webdriver/chrome')
//创建浏览器驱动
function createBrowserDriver() {
    console.log('Create Driver');
    let browserConfig = process.env.BROWSER || 'chrome';
    let browser = browserConfig.toLowerCase();
    if (['chrome', 'firefox', 'ie'].indexOf(browser) < 0) browser = 'chrome'; //default to chrome
    return new webDriver.Builder().forBrowser(browser).build();
}
// 创建手机驱动
function createMobileDriver() {
    const { Options } = require('selenium-webdriver/chrome')
    console.log('Create Mobile Driver');
    let chrome = require('selenium-webdriver/chrome');
    let { Builder } = require('selenium-webdriver');
    return new Builder()
        .forBrowser('chrome')                          
        .setChromeOptions( new Options().setMobileEmulation({ deviceName: 'iPhone 6/7/8' }))
        .build();
}
    
function choose(params) {
    if(params === 1) return createBrowserDriver();
    if(params === 2) return createMobileDriver();
}

exports. createDriver= choose;

2.hooks.js 文件全部替换

const { After, Before, AfterAll, setDefaultTimeout } = require('cucumber');
const { driver } = require('./web_driver');


//set default step timeout
setDefaultTimeout(90 * 1000);

3.脚本js 代码演示

const { Given, When, Then } = require('cucumber');
const assert = require('assert');
const { createDriver } = require('../support/web_driver');
const { By, until } = require('selenium-webdriver');


Then(/^Browser浏览器访问'([^']*)'$/, async function (url) {
    const driver = createDriver(1);
    await driver.get(url);
    console.log("启动浏览器驱动")
    await driver.sleep(3000);
    let screenshot = await driver.takeScreenshot();
    this.attach(screenshot, 'image/png');    
    driver.quit();
});

Then(/^\*Mobile 访问百度$/, async function () {
    driver=createDriver(2);
    await driver.get('https://www.jianshu.com/');
    await driver.sleep(3000);
    let screenshot = await driver.takeScreenshot();
    this.attach(screenshot, 'image/png'); 
    driver.quit();
});


总结:
以上改动会导致hooks 文件不会在每个动作结束后:截图、清除缓存、关闭浏览器
需要在每个脚本中自己选择添加:
1.创建driver

const driver = createDriver(1); //1Mobil  2:browser

2.截图

let screenshot = await driver.takeScreenshot();
this.attach(screenshot, 'image/png');

3.清除缓存

await driver.manage().deleteAllCookies(); 

4.关闭浏览器

driver.quit();
上一篇下一篇

猜你喜欢

热点阅读