You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在WDIO中检测测试运行于BrowserStack还是本地Appium服务器

检测测试运行环境(BrowserStack vs 本地)的几种方案

方案1:通过环境变量判断

启动测试时,根据运行环境手动设置环境变量:

  • 本地运行:npm run test
  • BrowserStack运行:BROWSERSTACK=true npm run test

在beforeScenario钩子中读取环境变量判断:

import { Before } from '@cucumber/cucumber';

Before(async function () {
  const isBrowserStack = process.env.BROWSERSTACK === 'true';
  if (isBrowserStack) {
    console.log('Running on BrowserStack');
    // 执行BrowserStack专属逻辑
  } else {
    console.log('Running locally');
    // 执行本地专属逻辑
  }
});

方案2:通过Driver Capabilities判断

BrowserStack会在driver的capabilities中注入专属标识字段(如bstack:options),可通过获取capabilities判断:

import { Before } from '@cucumber/cucumber';

Before(async function () {
  const capabilities = await this.driver.getCapabilities();
  // 检查是否存在BrowserStack专属capability字段
  const isBrowserStack = !!capabilities.getCapability('bstack:options');
  // 也可通过`browserstack.user`等字段判断
  // const isBrowserStack = !!capabilities.getCapability('browserstack.user');

  if (isBrowserStack) {
    console.log('Running on BrowserStack');
  } else {
    console.log('Running locally');
  }
});

方案3:在WDIO配置中注入全局标识

在wdio.conf.ts中,根据服务配置判断并设置全局变量:

// wdio.conf.ts
export const config: WebdriverIO.Config = {
  // 其他配置项...
  onPrepare: function () {
    // 检查services中是否包含BrowserStack服务
    const isBrowserStack = config.services?.some(service => 
      typeof service === 'string' 
        ? service.includes('browserstack') 
        : service.name.includes('browserstack')
    );
    global.isBrowserStack = isBrowserStack;
  },
  // 其他配置项...
};

在beforeScenario钩子中直接使用全局变量:

import { Before } from '@cucumber/cucumber';

// TypeScript需在globals.d.ts中声明全局变量类型
// declare global {
//   namespace NodeJS {
//     interface Global {
//       isBrowserStack: boolean;
//     }
//   }
// }

Before(async function () {
  const isBrowserStack = global.isBrowserStack;
  if (isBrowserStack) {
    console.log('Running on BrowserStack');
  } else {
    console.log('Running locally');
  }
});

内容的提问来源于stack exchange,提问作者Greener

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.23 10:44:53