如何在Selenium Grid节点上并行执行Cucumber TypeScript测试
实现多浏览器并行测试的方案
你当前的技术栈无需更换测试运行器,直接基于已有的Cucumber框架就可以实现同一份用例在Chrome、Firefox两个Selenium Grid节点并行执行,具体调整步骤如下:
第一步:优化驱动创建逻辑,支持动态读取浏览器类型
修改DriverInstance.ts,新增通用驱动创建方法,通过环境变量动态生成对应浏览器的驱动实例:
import { Builder, ThenableWebDriver } from 'selenium-webdriver'; import { Options as ChromeOptions } from 'selenium-webdriver/chrome'; import { Options as FirefoxOptions } from 'selenium-webdriver/firefox'; export function CreateDriverInstance(): ThenableWebDriver { const browser = process.env.BROWSER || 'chrome'; console.log(`Creating a new ${browser} driver instance`); if (browser === 'firefox') { const firefoxOptions = new FirefoxOptions(); return new Builder() .forBrowser('firefox') .usingServer("http://localhost:4444/wd/hub") .setFirefoxOptions(firefoxOptions) .build(); } else { const chromeOptions = new ChromeOptions(); return new Builder() .forBrowser('chrome') .usingServer("http://localhost:4444/wd/hub") .setChromeOptions(chromeOptions) .build(); } }
第二步:调整步骤定义文件的驱动引用
修改Login.step文件:
- 替换写死的Firefox驱动实例化逻辑,调用上述通用方法
- 新增测试结束后的驱动销毁钩子,避免Selenium Grid会话堆积
// 替换原有驱动实例化代码 import { CreateDriverInstance } from "./Driver_Instance"; import { After } from '@cucumber/cucumber'; let driver = CreateDriverInstance(); let testURL: string = 'www.example.com'; // 末尾新增钩子 After(async () => { await driver.quit(); }) // 其余原有代码保留即可
第三步:配置执行脚本,实现多浏览器并行运行
先安装必要的工具依赖:
npm i cross-env npm-run-all ts-node typescript @cucumber/cucumber -D
在package.json中添加执行脚本:
{ "scripts": { "test:chrome": "cross-env BROWSER=chrome cucumber-js step_definitions/**/*.step.ts", "test:firefox": "cross-env BROWSER=firefox cucumber-js step_definitions/**/*.step.ts", "test:all": "run-p test:chrome test:firefox" } }
在项目根目录新增Cucumber配置文件cucumber.js,支持TypeScript执行:
module.exports = { default: { requireModule: ['ts-node/register'], require: ['step_definitions/**/*.ts'], format: ['progress'] } }
执行方式
直接运行npm run test:all即可同时启动Chrome、Firefox两个测试进程,两份进程会分别向Selenium Grid请求对应浏览器节点,并行执行同一份登录测试用例。
内容的提问来源于stack exchange,提问作者JishitaJoseph
相关产品推荐
相关产品推荐

