Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Puppeteer - checkbox.checked is undefined - why?

I'm using puppeteer and jest to test some stuff on the front end, and I'm having a small issue - I think there is some concept I'm missing.

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

According to the puppeteer docs, page.$ runs document.querySelector. When I run the following on the browser, I get what I want:

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

but the code in jest results in CHECKED: undefined

Why is this the case --> what concept am I missing?

like image 692
Asool Avatar asked Mar 22 '18 13:03

Asool


People also ask

How do you check checkbox is checked or not in puppeteer?

To avoid that we have to check whether a checkbox is already checked or not, if checked then we should ignore it, but if not checked then we can click it and make the check box checked. Create another module and create the logic of clicking a button as a function, then call it in your framework for code reusability.

How do you find the value of selector in puppeteer?

page. $eval() function is used to get the value for an element in puppeteer. $eval will stage two-parameter as an argument first parameter will be the selector and the second parameter will be element= element.


1 Answers

You are trying to read a value of ElementHandle, it is not the same as pure JS Element.

You have to use this syntax to get checked value:

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

Here is working example:

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();
})();
like image 89
Everettss Avatar answered Oct 12 '22 18:10

Everettss