Puppeteer - checkbox.checked未定义 - 为什么?

问题描述 投票:4回答:1

我正在使用木偶戏和开玩笑来测试前端的一些东西,而我有一个小问题 - 我认为有一些我缺少的概念。

test("Assert that when checkbox isn't checked, dropdown menu is visible", async () => {
    let checkbox = await page.$('input[ng-model="user.managed.timezone"]');
    console.log("Checking if checkbox checked");
    console.log("CHECKED: ", checkbox.checked);
  });

根据puppeteer docs,page。$运行document.querySelector。当我在浏览器上运行以下内容时,我得到了我想要的内容:

let m = document.querySelector('input[ng-model="user.managed.timezone"]') console.log(m.checked) // results in true or false

但是jest中的代码导致CHECKED:undefined

为什么会这样 - >我错过了什么概念?

jestjs puppeteer
1个回答
10
投票

你试图读取ElementHandle的值,它与纯JS Element不同。

您必须使用此语法来获取checked值:

await (await checkbox.getProperty('checked')).jsonValue()

这是工作示例:

const puppeteer = require('puppeteer');

const html = `
    <html>
        <body>
            <input ng-model="user.managed.timezone" type="checkbox" />
        </body>
    </html>`;

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(`data:text/html,${html}`);

    const checkbox = await page.$('input[ng-model="user.managed.timezone"]');

    console.log(await (await checkbox.getProperty('checked')).jsonValue());
    await checkbox.click();
    console.log(await (await checkbox.getProperty('checked')).jsonValue());

    await browser.close();
})();
© www.soinside.com 2019 - 2024. All rights reserved.