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

pytest-playwright执行测试报错:fixture 'page'未找到,求解决方案

pytest找不到Playwright page fixture的解决方案

问题重现

编写的Playwright测试代码如下:

import re
from playwright.sync_api import Page, expect


def test_pp(page: Page):
    page.goto("https://playwright.dev/")
    # Expect a title "to contain" a substring.
    expect(page).to_have_title(re.compile("Playwright"))
    # create a locator
    get_started = page.locator("text=Get Started")
    # Expect an attribute "to be strictly equal" to the value.
    expect(get_started).to_have_attribute("href", "/docs/intro")
    # Click the get started link.
    get_started.click()
    # Expects the URL to contain intro.
    expect(page).to_have_url(re.compile(".*intro"))

执行pytest时触发错误:

file D:\play_wright\test\test_sample.py, line 5
  def test_pp(page: Page):
E       fixture 'page' not found
>       available fixtures: cache, capfd, capfdbinary, caplog, capsys, capsysbinary, doctest_namespace, monkeypatch, pytestconfig, record_property, record_testsuite_property, record_xml_attribute, recwarn, tmp_path, tmp_path_factory, tmpdir, tmpdir_factory
>       use 'pytest --fixtures [testpath]' for help on them.

D:\play_wright\test\test_sample.py:5

已完成排查:安装pytest-playwright 0.3.0、Playwright 1.27.1,尝试过pytest 6.2.1及7.x版本,重启Windows电脑,问题仍存在。

解决方案

  • 确认pytest-playwright插件已被加载
    运行pytest --trace-config,在输出中查找pytest_playwright相关条目。若未找到,说明插件未被pytest识别,需检查安装环境。

  • 重新在正确环境中安装依赖
    若使用虚拟环境,先激活环境,再执行重装命令:

    pip uninstall pytest-playwright playwright -y
    pip install pytest-playwright
    playwright install
    
  • 强制加载插件运行测试
    直接通过命令指定加载pytest-playwright插件:

    pytest -p pytest_playwright
    
  • 检查pytest配置文件是否禁用插件
    查看项目中的pytest.ini、tox.ini或setup.cfg,确认无addopts = -p no:pytest_playwright这类禁用插件的配置,如有则删除。

  • 验证测试文件/函数命名规范
    确保测试文件以test_开头、测试函数以test_开头(当前代码已符合要求,此条为通用检查项)。

内容的提问来源于stack exchange,提问作者Naveen Kumar R B

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 17:50:44