2

I am currently trying to figure out how to render my React app within the puppeteer browser so that I could take a screenshot and perform visual regression testing in the future. Most of the ways I've seen this achieved was by starting up an express server and serving up the html page when a certain endpoint is requested. However, I'd like to avoid starting up a server if possible and would like to perhaps use something like ReactDOM.render within the puppeteer browser to render it like how React would.

So far, I've tried creating a build of the React app and then using puppeteer's page.setContent api to render out the build's index.html to the puppeteer browser directly. However, when I do this, the browser doesn't render anything on screen and does not make network requests for the static files.

This is what it looks like in puppeteer: puppeteer browser

This is the method with page.setContent:

const buildHTML = await fs.readFileSync('build/index.html', 'utf8');

// create a new browser tab
const page = await browser.newPage();
await page.setViewport({ width: 1920, height: 1080 });

// set page's html content with build's index.html
await page.setContent(buildHTML);

// take a screenshot
const contentLoadingPageScreenshot = await page.screenshot({fullPage: true});

Also, if anyone knows of a better way to run an image snapshot test without having to start up a server, please let me know. Thank you.

user11885987
  • 21
  • 1
  • 3
  • Maybe the document.write used by setContent is not triggering the event (document load?) your app is using to render the HTML? – hardkoded Aug 05 '19 at 18:40
  • It doesn't make sense to `await` a sync function, so `await fs.readFileSync('build/index.html', 'utf8');` should probably be `await fs.readFile('build/index.html', 'utf8');` with the import as `import fs from "node:fs/promises";`. Also, without the HTML, it's not clear that there are images in the app. This would benefit from a [mcve]. Thanks. – ggorlen Mar 17 '23 at 14:04

1 Answers1

2

With ref: puppeteer doc, you can put options for setContent to wait for the network request

await page.setContent(reuslt, {
    waitUntil: ["load","networkidle0"]
});
Vengleab SO
  • 716
  • 4
  • 11