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

Playwright使用POM模式时context未定义的解决方法咨询

解决Playwright POM中context未定义的问题

问题核心是CommonOperations类的openSecondPage方法中没有可访问的context实例,以下是两种直接可行的修改方案:

方案1:通过已传入的page获取context

Playwright的Page对象自带context()方法,可直接获取其所属的BrowserContext,无需额外传入context。修改commonOperations.ts的代码如下:

class CommonOperations {
    private page: Page;

    constructor(page: Page) {
        this.page = page;
    }

    // 其他已有方法(login、startQuiz等)...

    async openSecondPage(urlText: any) {
        // 从当前page实例获取对应的context
        const context = this.page.context();
        const secondPage = await context.newPage();
        await secondPage.goto(urlText);
        // 可选:若需在测试用例中操作新页面,可返回该实例
        return secondPage;
    }
}

方案2:构造函数中传入context并保存

如果后续有更多直接操作context的需求,可在初始化类时同时传入context并保存为实例属性:

1. 修改测试用例中的初始化代码(first.test.ts)

test.beforeEach(async ({ context }) => {
    page = await context.newPage();
    // 同时传入page和context
    const comOperations = new commonOperations.CommonOperations(page, context);
    await comOperations.login()
    await comOperations.startQuiz(quizSamples.getQuizData(2, 4, 100, 200));
    urlText = await comOperations.copyUrl();
    // 接收返回的新页面实例(若需要)
    secondPage = await comOperations.openSecondPage(urlText)
})

2. 修改CommonOperations类(commonOperations.ts)

import { Page, BrowserContext } from '@playwright/test';

class CommonOperations {
    private page: Page;
    private context: BrowserContext;

    constructor(page: Page, context: BrowserContext) {
        this.page = page;
        this.context = context;
    }

    // 其他已有方法...

    async openSecondPage(urlText: any) {
        const secondPage = await this.context.newPage();
        await secondPage.goto(urlText);
        return secondPage;
    }
}

两种方案选择建议:方案1更简洁,适合仅通过page关联context的场景;方案2适合需要频繁直接操作context的复杂场景。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.07 22:00:23