E2E Testing Material-UI Select with Puppeteer

Viewed 1267

I'm unable to access dropdown values (<MenuItem>) in dropdown on Material-UI Select component.

Basically, what I'm trying to accomplish is following, click on input with id='x', wait for the dropdown to show up (div with ul and li, where each li has id='y' prop), select specific one and then click on it.

The dropdown is related to filter...

Note: Using native select is not an option.

2 Answers

You need to trigger first mousedown and then click events on the Material Select element. You can use the following function in your Puppeteer code.

const MaterialSelect = async (page, newSelectedValue, cssSelector) => {
    await page.evaluate((newSelectedValue, cssSelector) => {
        var clickEvent = document.createEvent('MouseEvents');
        clickEvent.initEvent("mousedown", true, true);
        var selectNode = document.querySelector(cssSelector);
        selectNode.dispatchEvent(clickEvent);
        [...document.querySelectorAll('li')].filter(el => el.innerText == newSelectedValue)[0].click();
    }, newSelectedValue, cssSelector);
}

Example usage: "demo-simple-select" is the id I assigned to material-ui Select

(async () => {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto('https://my-app-site/page');
    await MaterialSelect(page, 'new selected value', '#demo-simple-select');
})();

A simple one.

Use expect-puppeteer npm package to get onClick method.

Then Declare:

export const MaterialSelect = async (page, cssSelector, newSelectedValue) => {
    await expect(page).toClick(cssSelector);
    await expect(page).toClick(`li[data-value="${newSelectedValue}"]`);
}

And use it like:

 await MaterialSelect(page, '#demo-simple-select', 'new selected value');
Related