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

Playwright中storageState与globalSetup结合POM使用异常排查

问题:Playwright改用globalSetup后测试报错TypeError: Cannot read properties of undefined (reading 'addElementToDocument')

我用Playwright编写端到端(E2E)测试,原本采用beforeEach钩子,现改为使用globalSetup,但测试无法正常运行。已在playwright.config.ts中配置globalSetup路径及storageState存储路径,global-setup.ts可正常执行,成功生成storageState.json文件,步骤执行无异常。但运行测试时,终端报错TypeError: Cannot read properties of undefined (reading 'addElementToDocument'),即测试中声明的builderPage未完成初始化。


playwright.config.ts

import { defineConfig } from '@playwright/test';

export default defineConfig({
  globalSetup: "./global-setup.ts",
  testDir: './tests',
  retries: 2, // Set the number of retries here
  reporter: [['html'], ['list']],
  use: {
    baseURL: 'http://localhost:8080/velocity_builder',
    headless: true,
    screenshot: 'only-on-failure',
    storageState: './storageState.json'
  },
  workers: 4,
  timeout: 30000,
});

global-setup.ts

import { expect, Browser, chromium, Page } from '@playwright/test';
import { BuilderPage } from './tests/BuilderPage';

async function globalSetup() {
const browser: Browser = await chromium.launch({ headless: false })
const context = await browser.newContext()
const page: Page = await context.newPage()
const builderPage = new BuilderPage(page); // initialize a new builder page object
await page.goto('http://localhost:8080'); // go to the builder
await builderPage.initializeBuilder(); // initialize the builder by clicking a blank applet

    // Ensure panels are visible
    await expect(builderPage.panels.document).toBeVisible();
    await expect(builderPage.panels.quickView).toBeVisible();
    await expect(builderPage.panels.properties).toBeVisible();
    
    // Ensure buttons are visible
    await expect(builderPage.saveButton).toBeVisible();
    await expect(builderPage.previewButton).toBeVisible();
    await expect(builderPage.automationButton).toBeVisible();
    await expect(builderPage.globalizationButton).toBeVisible();
    await expect(builderPage.addButton).toBeVisible();
    
    // Click on the add button and ensure toolbox panel is visible
    await builderPage.addButton.click();
    await expect(builderPage.panels.toolbox).toBeVisible();
    
    // Store session state (e.g., cookies) for further use in tests
    const storageState = await page.context().storageState({ path: 'storageState.json' });
    console.log(storageState)
    
    await browser.close()

}

export default globalSetup

测试代码

import { test, expect, Page } from '@playwright/test';
import { BuilderPage } from './BuilderPage';

test.describe.configure({ mode: 'parallel', retries: 4 }); // Runs the test in the file in parallel mode and retries them 4 times if they fail
test.describe('Element Style Tests', () => {
// let page: Page;
let builderPage: BuilderPage;
test('Check Header Style', async () => {
await builderPage.addElementToDocument('Header');
const isElementInQuickView = await builderPage.verifyElementInQuickView();
expect(isElementInQuickView).toBe(true);

        const types = [
            'Header (Branded)',
            'Header (Decorative)',
            'Section',
            'Header'
        ];
    
        for (let i = 0; i < types.length; i++) {
            await new Promise((resolve) => setTimeout(resolve, 500)); // You might want to replace this with a better synchronization method
            await builderPage.checkHeaderStyleChange(types[i]);
        }
    });

});

storageState.json内容

{
"cookies": [],
"origins": [
{
"origin": "http://localhost:8080",
"localStorage": [
{
"name": "flowplayerTestStorage",
"value": "test"
}
]
}
]
}

报错信息

Running global setup if any…
{
cookies: [],
origins: [ { origin: 'http://localhost:8080', localStorage: [Array] } ]
}

Running 1 test using 1 worker

x  1 testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style (11ms)
x  2 testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style (retry #1) (11ms)
x  3 testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style (retry #2) (12ms)
x  4 testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style (retry #3) (11ms)
x  5 testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style (retry #4) (11ms)

1) testStyles.spec.ts:9:9 › Element Style Tests › Check Header Style ─────────────────────────────

    TypeError: Cannot read properties of undefined (reading 'addElementToDocument')
    
       8 |     let builderPage: BuilderPage;
       9 |     test('Check Header Style', async () => {
    > 10 |         await builderPage.addElementToDocument('Header');
         |                           ^
      11 |         const isElementInQuickView = await builderPage.verifyElementInQuickView();
      12 |         expect(isElementInQuickView).toBe(true);
      13 |    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.18 20:15:54