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

Aso*_*ool 6 jestjs puppeteer

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

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);
  });
Run Code Online (Sandbox Code Playgroud)

根据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

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

Eve*_*tss 16

您正在尝试读取ElementHandle的值,它与纯JS元素不同.

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

await (await checkbox.getProperty('checked')).jsonValue()
Run Code Online (Sandbox Code Playgroud)

这是工作示例:

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();
})();
Run Code Online (Sandbox Code Playgroud)