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

使用Playwright点击关闭Mantine Modal对话框的推荐方法

如何在Playwright中优雅地点击Mantine Modal遮罩层以关闭对话框?

我正在开发一个使用Mantine的<Modal>组件的Web应用,模态框打开时会显示背景遮罩层,点击遮罩层可以关闭对话框。我需要编写Playwright测试来实现点击遮罩层关闭对话框的操作,目前的实现方式是点击<body>元素的视口角落,但觉得不够优雅,希望找到Playwright中点击元素外部的推荐实现方式。

示例代码:

import { Button, MantineProvider, Modal } from "@mantine/core";
import { useState } from "react";

export default function App() {
  const [opened, setOpened] = useState(true);
  return (
    <MantineProvider>
      <Button onClick={() => setOpened(true)}>Open modal</Button>
      <Modal opened={opened} onClose={() => setOpened(false)}>
        This is a modal!
      </Modal>
    </MantineProvider>
  );
}

我当前的实现代码:

await page.locator("body").click({ position: { x: 0, y: 0 } });

推荐实现方式

1. 直接定位Mantine Modal的遮罩层元素

Mantine的Modal组件会生成带特定类名的遮罩层DOM元素(通常是mantine-Modal-overlay),直接定位这个元素点击是最精准的方式,完全贴合业务逻辑:

await page.locator(".mantine-Modal-overlay").click();

2. 基于模态框位置动态计算外部点击坐标

如果不想依赖组件类名,可以先获取模态框的边界信息,再计算外部点击位置,适配不同尺寸的模态框:

// 获取模态框的位置与尺寸
const modalBounds = await page.locator(".mantine-Modal-modal").boundingBox();
// 点击模态框左侧外部的垂直居中位置
await page.click({ 
  position: { 
    x: (modalBounds?.x || 0) - 10, 
    y: (modalBounds?.y || 0) + (modalBounds?.height || 0) / 2 
  } 
});

3. 模拟ESC键关闭(补充方案)

若测试场景不强制要求点击遮罩,也可以用Mantine Modal默认支持的ESC键关闭,代码更简洁:

await page.keyboard.press("Escape");

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.21 22:55:19