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

标签 jestjs puppeteer

我正在使用 puppeteer 和 jest 来测试前端的一些东西,但我遇到了一个小问题 - 我认为我缺少一些概念。

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 文档,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

为什么会这样 --> 我缺少什么概念?

最佳答案

您正在尝试读取值 ElementHandle ,和纯JS Element不一样.

您必须使用此语法才能获得 checked值(value):

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();
})();

关于jestjs - Puppeteer - checkbox.checked 未定义 - 为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49430346/

相关文章:

javascript - puppeteer API 未触发点击事件

puppeteer - 使用 Puppeteer 时如何获取 ElementHandle 的类名?

javascript - 在 puppeteer 的所有页面上渲染标题

google-chrome - 如何从控制台调用 Chrome 节点截图

reactjs - React 和 Jest - 使用 PropTypes.instanceOf 测试组件

node.js - 用 Create React App 开 Jest : Test suite failed to run - Unexpected token

javascript - 如何使用配置选项测试 axios

node.js - Nodejs/Puppeteer - 如何使用 page.evaluate

javascript - Puppeteer page.evaluate 未正确返回

javascript - 使用 Jest、AudioContext 进行测试和模拟