You need to enable JavaScript to run this app. Playwright运行测试前如何检查viewport判断桌面/移动端对应元素是否存在
优惠活动
大模型
产品
解决方案
定价
更多

Playwright运行测试前如何检查viewport判断桌面/移动端对应元素是否存在

实现方案

有两种常用的方式可以实现环境区分,你可以根据自己的使用场景选择:


方法1:通过当前页面视口宽度直接判断

不需要修改原有配置,直接从page对象获取视口尺寸,自定义移动端和桌面端的分界阈值即可:

test("Test home page", async ({ page }) => {
  await page.goto(BASE_URL);
  // 获取当前视口尺寸
  const viewport = page.viewportSize();
  // 自定义阈值,比如宽度≤768px判定为移动端,可根据自己的业务适配规则调整
  const isMobile = viewport ? viewport.width <= 768 : false;

  if (isMobile) {
    await expect(page.getByText("I am mobile")).toBeVisible();
  } else {
    await expect(page.getByText("I am desktop")).toBeVisible();
  }
});

注意:不要用page.$$返回的数组做toBeTruthy判断,就算元素不存在$$也会返回空数组,空数组转布尔值为true,会导致断言失效,直接用Playwright自带的元素可见性匹配器更稳妥。


方法2:通过项目配置标记判断

适合视口阈值不统一、需要自定义分类的场景,有两种实现方式:

方式A:新增自定义配置参数

在原有配置的use字段中新增isMobile自定义标记:

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: "Desktop Safari",
      use: {
        browserName: "webkit",
        viewport: { width: 1200, height: 750 },
        headless: false,
        baseURL: BASE_URL,
        httpCredentials,
        isMobile: false // 新增自定义标记
      },
    },
    {
      name: "Mobile Chrome",
      use: { ...devices["Pixel 5"], baseURL: BASE_URL, httpCredentials, isMobile: true },
    },
    {
      name: "Mobile Safari",
      use: { ...devices["iPhone 12"], baseURL: BASE_URL, httpCredentials, isMobile: true },
    },
    {
      name: "Desktop Firefox",
      use: {
        browserName: "firefox",
        viewport: { width: 800, height: 600 },
        httpCredentials,
        isMobile: false // 新增自定义标记
      },
    },
  ],
}

用例中直接解构参数使用即可:

test("Test home page", async ({ page, isMobile }) => {
  await page.goto(BASE_URL);
  if (isMobile) {
    await expect(page.getByText("I am mobile")).toBeVisible();
  } else {
    await expect(page.getByText("I am desktop")).toBeVisible();
  }
});

方式B:直接匹配项目名称关键词

不需要修改配置,通过Playwright内置的testInfo获取当前运行的项目名称,匹配关键词判断:

test("Test home page", async ({ page, testInfo }) => {
  await page.goto(BASE_URL);
  // 判断项目名称是否包含Mobile关键词
  const isMobile = testInfo.project.name.includes("Mobile");

  if (isMobile) {
    await expect(page.getByText("I am mobile")).toBeVisible();
  } else {
    await expect(page.getByText("I am desktop")).toBeVisible();
  }
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.09 20:57:03