如何在 运行 测试前检查视口

How to check viewport before running the test

我在 playwright 中有这个配置 运行 不同的浏览器进行相同的测试

const config: PlaywrightTestConfig = {
  projects: [
    {
      name: "Desktop Safari",
      use: {
        browserName: "webkit",
        viewport: { width: 1200, height: 750 },
        headless: false,
        baseURL: BASE_URL,
        httpCredentials,
      },
    },
    // Test against mobile viewports.
    {
      name: "Mobile Chrome",
      use: { ...devices["Pixel 5"], baseURL: BASE_URL, httpCredentials },
    },
    {
      name: "Mobile Safari",
      use: { ...devices["iPhone 12"], baseURL: BASE_URL, httpCredentials },
    },
    {
      name: "Desktop Firefox",
      use: {
        browserName: "firefox",
        viewport: { width: 800, height: 600 },
        httpCredentials,
      },
    },
  ],

现在,我知道如果我在桌面上应该存在一个元素,但如果我在移动设备上则不会。在期望元素出现在其中之前,我如何检查视口?

像这样:

test("Test home page", async ({ page }) => {
  await page.goto(BASE_URL);
  const inMobile =await page.$$("text='I am mobile'");;
  const inDesktop = await page.$$("I am desktop");
if (testing mobile)
  expect(inMobile).toBeTruthy()
else expect(inDesktop).toBeTruthy()
});

您可以使用 isMobile fixture 来检测它是否是移动设备。当您像在项目配置中那样使用设备时,它会在内部设置。请参阅以下示例:

test("Test home page", async ({ page, isMobile }) => {
  console.log(isMobile);
});

参考这里:https://playwright.dev/docs/api/class-fixtures#fixtures-is-mobile