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

Playwright中locator.evaluateAll返回Map及对象填充问题咨询

Playwright中evaluateAll的对象填充与Map返回问题

你在浏览器DevTools里能正常用Map和对象获取h2节点的id与文本,但在Playwright中编写测试时出现了headersMap.size为undefined的错误,核心原因是**evaluateAll的回调参数是节点数组,而非单个节点**,且Playwright对返回值的序列化规则会影响Map的传递。

1. 创建对象并通过forEach填充后返回

修正原代码中遍历逻辑的错误,在evaluateAll的回调里遍历传入的节点数组,填充对象后返回:

test('API Testing - H2 count greater than 2', async ({ page }) => {     
    await test.step('API Testing - get titles', async() => {
        await page.goto("https://playwright.dev/docs/api-testing");
        
        const headersObj = await page.locator('h2').evaluateAll(nodes => {
            const headers = Object.create(null);
            nodes.forEach(el => {
                headers[el.id] = el.innerText;
            });
            return headers;
        });
        
        // 验证对象的键数量大于2
        await expect(Object.keys(headersObj).length).toBeGreaterThan(2);
        console.log(headersObj);
        page.pause();
    });
});

2. 让locator.evaluateAll()返回可用的Map

Playwright在序列化从浏览器环境返回的值时,会把Map自动转换成普通对象(丢失size等Map专属属性),可以通过以下两种方式处理:

方式一:返回Map的entries数组,在Playwright环境重建Map

test('API Testing - H2 count greater than 2', async ({ page }) => {     
    await test.step('API Testing - get titles', async() => {
        await page.goto("https://playwright.dev/docs/api-testing");
        
        // 在浏览器端返回Map的entries数组
        const mapEntries = await page.locator('h2').evaluateAll(nodes => {
            const headersMap = new Map();
            nodes.forEach(el => {
                headersMap.set(el.id, el.innerText);
            });
            return Array.from(headersMap.entries());
        });
        
        // 在Playwright环境重建Map
        const headersMap = new Map(mapEntries);
        await expect(headersMap.size).toBeGreaterThan(2);
        console.table(Array.from(headersMap, ([name, value]) => ({ name, value })));
        page.pause();
    });
});

方式二:直接返回节点数据数组,自行构建Map或对象

如果不需要在浏览器端操作Map,可以直接返回结构化的数组,再在测试代码里处理:

test('API Testing - H2 count greater than 2', async ({ page }) => {     
    await test.step('API Testing - get titles', async() => {
        await page.goto("https://playwright.dev/docs/api-testing");
        
        const headersData = await page.locator('h2').evaluateAll(nodes => {
            return nodes.map(el => ({ id: el.id, text: el.innerText }));
        });
        
        // 转换为Map
        const headersMap = new Map(headersData.map(item => [item.id, item.text]));
        await expect(headersMap.size).toBeGreaterThan(2);
        console.table(headersData);
        page.pause();
    });
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.22 22:43:24