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

Playwright:如何在PageObject中按设备选定位器并获取browserName

在PageObject中区分移动端/桌面端定位器并获取browserName

1. 从testConfig获取browserName

在PageObject中,你可以在初始化实例时将testConfig作为参数传入,之后就能直接访问其中的browserName字段:

  • 测试文件中传递testConfig:
// test.spec.js
const { test } = require('@playwright/test');
const LoginPage = require('./pages/LoginPage');

test('登录流程验证', async ({ page, testConfig }) => {
  const loginPage = new LoginPage(page, testConfig);
  await loginPage.login('13800138000', '123456');
});
  • PageObject中接收并存储testConfig:
// LoginPage.js
class LoginPage {
  constructor(page, testConfig) {
    this.page = page;
    this.testConfig = testConfig;
  }
}

完成上述步骤后,就能通过this.testConfig.browserName获取当前浏览器名称,比如chrome、mobile chrome等。

2. 区分端类型的login方法实现

在login方法内,根据browserName判断是否为移动端,选择对应的登录按钮定位器,再执行后续的填写和提交操作:

// LoginPage.js 完整实现
class LoginPage {
  constructor(page, testConfig) {
    this.page = page;
    this.testConfig = testConfig;
    // 通用定位器定义
    this.phoneInput = this.page.locator('#phone-input');
    this.verifyCodeInput = this.page.locator('#verify-code-input');
  }

  async login(phone, verifyCode) {
    // 判断是否为移动端环境
    const isMobile = this.testConfig.browserName.includes('mobile');
    
    // 选择对应登录按钮
    const loginBtn = isMobile 
      ? this.page.locator('#buttonLoginNavModal2') 
      : this.page.locator('#buttonLoginNavModal');
    
    // 执行登录操作
    await loginBtn.click();
    await this.phoneInput.fill(phone);
    await this.verifyCodeInput.fill(verifyCode);
    await this.verifyCodeInput.press('Enter');
  }
}

module.exports = LoginPage;

补充优化方案

如果browserName未标记移动端,也可以通过视口宽度判断:

const isMobile = this.testConfig.viewport.width < 768;

还可以将按钮选择封装为getter方法,让代码更简洁:

get loginButton() {
  const isMobile = this.testConfig.browserName.includes('mobile');
  return isMobile 
    ? this.page.locator('#buttonLoginNavModal2') 
    : this.page.locator('#buttonLoginNavModal');
}

之后在login方法中直接调用await this.loginButton.click()即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 14:35:01