Home > Software design >  Puppeteer css selectors not working with storybook?
Puppeteer css selectors not working with storybook?

Time:03-08

const puppeteer = require('puppeteer');

async function run () {
    const browser = await puppeteer.launch();
    const page = await browser.newPage();
    await page.goto(url);
    await page.$eval('input[type=submit]', el => el.click());
    await page.screenshot({path: 'screenshot.png'});
    browser.close();
}
run();

When I run this with any site like 'node screenshot.js "https://github.com/login"' it works as expected but with storybook, it simply can't find elements even tho I can't select them from the console fine. Is there something with storybook not supporting puppeteer? Is there a different tool to hover/click on storybook components in headless browser? Thank you for your help.

CodePudding user response:

Storybook presents the components/elements inside an iframe, which means a regular document.querySelector cannot find them.

The reason it seems to work in the console is that the console switches context for document as soon as you activate the iframe, e.g. by clicking anywhere inside of it, or focussing an element inside of it.

To solve the issue, find the iframe like this (this example uses the DOM API, you need to find the puppeteer way to do this):

const iframe = document.querySelector('#storybook-preview-iframe');

Then, to find your element:

let el = iframe.contentDocument.querySelector('input[type=submit]');

Here's what it would look like in puppeteer:

const elementHandle = await page.waitForSelector('#storybook-preview-iframe');
const frame = await elementHandle.contentFrame();
await frame.waitForSelector('input[type=submit]');
const el = await frame.$('input[type=submit]');
el.click();
  • Related