Headless browser testing generally refers to an object or thing without a head, and in the context of a browser, it refers to a browser simulation without a UI. Headless browser automation uses a web browser for end-to-end testing without loading the browser's UI.
Some of the main features of Puppeteer include:
Puppeteer is a Node.js library for controlling Chrome or Chromium browsers, primarily for tasks such as automated testing, web scraping, and generating PDFs. The "headless" in Puppeteer refers to a browser instance that can run without a user interface.
In other words, the browser runs in the background and does not display a window with which you can interact visually. Instead, it performs tasks programmatically and can be controlled by scripts or code.
Puppeteer allows you to control a regular browser instance with a visible GUI and a headless browser instance. Headless mode is particularly useful for tasks such as web scraping, automated testing, and generating screenshots or PDFs, as it allows these tasks to be performed efficiently without the browser window being displayed.
Some benefits of using Puppeteer headless mode:
Headless browsers are particularly powerful for tasks that require automated interaction with websites, data extraction, testing, and other operations that do not require visual rendering.
Do you have any wonderful ideas or doubts about web scraping and Browserless?
Let's see what other developers are sharing on Discord and Telegram!
How to do headless browser testing with Puppeteer and Browserless?
Let's figure it out in the following content!
Before testing, we need to have a Browserless service. Browserless can help us solve complex web crawling and large-scale automation tasks. With cloud deployment of fully managed achievement, Browserless has a more powerful function.
Browserless adopts a browser-centric strategy, provides powerful headless deployment capabilities, and offers higher performance and reliability. Please click here to learn more about the configuration of the Browserless service.
After completing the environment initialization, we need to further determine the target of our test.
We will just learn an example of how to use Puppeteer with Browserless without specific web pages. Please specify the sample to your target websites and requirements.
Here, let's use Puppeteer
to get the title of the page and create a screenshot. After that, we will combine it with Jest to write test cases.
The following are our main test contents:
Next, please follow the steps below to install Puppeteer
and run the test script:
Step 1: Create a new folder in Vs code
Step 2: Open the Vs code terminal and run the following commands to install related dependencies
npm init -y
pnpm add jest jest-html-reporter puppeteer-core
Step 3: Finish related files
jest.config.js
configuration file to perform the related configuration:module.exports = {
testTimeout: 10000, // 10 seconds
reporters: [
'default',
[
'jest-html-reporter',
{
pageTitle: 'Test Report',
outputPath: './test-report.html',
includeFailureMsg: true,
includeConsoleLog: true,
},
],
],
};
__tests__/puppeteer.spec.js
test scriptTo launch the browser, you need to pass in the relevant configuration (for complete configuration, refer to LaunchNewBrowser
const puppeteer = require('puppeteer-core');
describe('My First Puppeteer Test', () => {
it('should load the page and check the title', async () => {
const browserWSEndpoint = await launchAndConnectToBrowser();
const browser = await puppeteer.connect({
browserWSEndpoint: browserWSEndpoint,
defaultViewport: null,
});
const page = await browser.newPage();
await page.goto('https://example.com');
const title = await page.title();
expect(title).toBe('Example Domain');
await browser.close();
});
// take a screenshot of the page
it('should take a screenshot of the page', async () => {
const browserWSEndpoint = await launchAndConnectToBrowser();
const browser = await puppeteer.connect({
browserWSEndpoint: browserWSEndpoint,
defaultViewport: null,
});
const page = await browser.newPage();
await page.goto('https://example.com');
await page.screenshot({ path: 'example.png' });
await browser.close();
});
});
async function launchAndConnectToBrowser() {
const token = ''; // your api token from nstbrowser
const config = {
proxy:
'', // required; input format: schema://user:password@host:port eg: http://user:password@localhost:8080
// platform: 'windows', // support: windows, mac, linux
// kernel: 'chromium', // only support: chromium
// kernelMilestone: '128', // support: 128
// args: {
// "--proxy-bypass-list": "detect.nstbrowser.io"
// }, // browser args
// fingerprint: {
// userAgent: 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/128.0.6613.85 Safari/537.36', // userAgent supportted since v0.15.0
// },
};
const query = new URLSearchParams({
token: token, // required
config: JSON.stringify(config),
});
const browserWSEndpoint = `ws://less.nstbrowser.io/connect?${query.toString()}`;
return browserWSEndpoint;
}
Now we just need to open the console and run the following script command:
npx jest --detectOpenHandles
The commands here can be mainly broken down into:
npx
command to execute the jest command.jest.config.js
configuration file of the current project and obtain basic configuration information.After executing the above command, we will see the following output. Here, each important result of the test execution process will be output, and it shows us that our test case has passed.
At the same time, we can open the test-report.html
file to view the specific report generated:
The file structure of the project is as follows. We can also see the output screenshot file content, which means that our test case has been completely passed.
page.waitForTimeout
), prefer waiting for specific events or elements (page.waitForSelector
), which makes your automation more efficient and resilient to varying load times.browser.createIncognitoBrowserContext
). This prevents cached data, cookies, or local storage from affecting subsequent sessions.navigator.webdriver
removal) can help bypass headless detection.Puppeteer headless browser makes everything easy. In this blog, we aim to share with you:
The Browserless of Nstbrowser simplifies the configuration and operation of Puppeteer. Just like before, it's time to reach out: how Browserless works with Playwright and Puppeteer!