CodeWithMMAK
Test AutomationIntermediate

Test Automation using Jest, Puppeteer, and Javascript

Learn how to set up and run your first test using Jest and Puppeteer for reliable web automation.

CodeWithMMAK
June 18, 2022
4 min

Introduction

🎯 Quick Answer

Jest and Puppeteer combined provide a powerful, zero-configuration testing environment for modern web applications. Jest serves as the test runner and assertion library, while Puppeteer provides a high-level API to control Chrome or Chromium. This combination is ideal for developers and QA engineers who need fast, reliable UI automation with minimal setup overhead.

If you are searching the web to set up your Jest and Puppeteer test then you are in the right place. In this blog, you will be reading about how to set up your Jest and Puppeteer test and run them.

đź“– Key Definitions

Jest

A delightful JavaScript Testing Framework with a focus on simplicity, developed by Meta (Facebook).

Puppeteer

A Node.js library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol.

Headless Browser

A web browser without a graphical user interface, used for automated testing and web scraping.

networkidle0

A Puppeteer navigation option that considers navigation to be finished when there are no more than 0 network connections for at least 500 ms.

What is Jest?

Jest is used by Facebook to test all JavaScript code including React applications. One of Jest’s philosophies is to provide an integrated “zero-configuration” experience.

What is Puppeteer?

Puppeteer is a Node library which provides a high-level API to control Chrome or Chromium over the DevTools Protocol. Puppeteer runs headless by default, but can be configured to run full (non-headless) Chrome or Chromium.

Key Capabilities:

  • Generate screenshots and PDFs of pages.
  • Automate form submission, UI testing, keyboard input, etc.
  • Create an up-to-date, automated testing environment.
  • Capture a timeline trace of your site to help diagnose performance issues.
  • Test Chrome Extensions.
  • Widely used in Web Scraping.

🚀 Step-by-Step Implementation

1

Prerequisites

Ensure you have Node.js and Visual Studio Code installed on your machine.

2

Initialize Project

Create a folder named jest-puppeteer-javascript and initialize it with a .gitignore file to exclude node_modules and other temporary files.

3

Configure package.json

Create a package.json file with the necessary dependencies (jest, puppeteer) and a test script that points to your spec files.

4

Install Dependencies

Run npm install --save jest puppeteer and npm install --save-dev @types/node node-notifier in your terminal.

5

Write Your First Test

Create a specs folder and add a .test.js file using Puppeteer's launch() and goto() methods within a Jest describe block.

6

Execute Tests

Run npm test in your terminal to see Jest execute your Puppeteer scripts and report the results.

Building the Framework

Let’s go through the step-by-step process of creating an automation framework using Jest, Puppeteer, and JavaScript.

  1. Install Node.JS
  2. Install Visual Studio Code
  3. Create a folder named jest-puppeteer-javascript.
  4. Create a .gitignore file:
Code Snippet
node_modules/
temp/
test-results/
downloads/*
log/*
  1. Create a package.json file:
Code Snippet
{
  "name": "jest-puppeteer-javascript",
  "version": "1.0.0",
  "description": "This is Test Automation framework designed using Jest, Puppeteer, and Javascript.",
  "homepage": "https://github.com/codewithmmak/jest-puppeteer-javascript",
  "main": "index.js",
  "dependencies": {
    "jest": "^24.9.0",
    "puppeteer": "^1.20.0"
  },
  "devDependencies": {
    "@types/node": "^10.17.60",
    "node-notifier": "^10.0.1"
  },
  "jest": {
    "testMatch": [
      "**/specs/*.test.js"
    ]
  },
  "scripts": {
    "test": "jest"
  }
}
  1. Install dependencies:
Code Snippet
npm install --save jest puppeteer
  1. Install dev dependencies:
Code Snippet
npm install --save-dev @types/node node-notifier

Creating Your First Test

Create a folder named specs. Inside it, create getGitHubRepoDetails.test.js:

Code Snippet
const puppeteer = require('puppeteer');

describe('GitHub', () => {
    it('page title should be "qaloop · GitHub"', async () => {
        const browser = await puppeteer.launch();
        const page = await browser.newPage();
        await page.goto('https://github.com/codewithmmak', { waitUntil: 'networkidle0' });

        const title = await page.title();
        expect(title).toBe('qaloop · GitHub');

        await browser.close();
    });
});

⚠️ Common Errors & Pitfalls

  • Timeout Errors

    Puppeteer has a default timeout of 30 seconds. If a page takes longer to load, use page.setDefaultNavigationTimeout(0) or increase the timeout in goto().

  • Headless vs Headful

    Tests might pass in headful mode but fail in headless mode due to different rendering behaviors or bot detection. Always verify in both if possible.

  • Async/Await Mismatch

    Forgetting to await a Puppeteer command like page.click() will lead to race conditions and unpredictable test failures.

âś… Best Practices

  • âś”
    Use networkidle0 or networkidle2 to ensure the page has fully loaded before performing assertions.
  • âś”
    Always close the browser instance in an afterAll or afterEach block to prevent memory leaks.
  • âś”
    Leverage Jest's snapshot testing for UI components to detect unexpected visual changes.
  • âś”
    Keep your tests independent; avoid sharing state between different test files.

Frequently Asked Questions

Can I run Puppeteer tests in parallel with Jest?

Yes, Jest runs tests in parallel by default. However, ensure your machine has enough resources as each worker spawns a browser instance.

How do I debug Puppeteer tests?

Launch the browser with headless: false and slowMo: 250 to watch the execution in real-time.

Does Jest-Puppeteer exist as a separate package?

Yes, jest-puppeteer is a popular preset that simplifies the integration even further by providing global browser and page objects.

Running the Test

To run the test, open the terminal and type:

Code Snippet
npm test

Code Repository

The sample framework is hosted on GitHub: jest-puppeteer-javascript

Have a suggestion or found a bug? Fork this project to help make this even better.

Conclusion

Combining Jest and Puppeteer creates a robust environment for web automation. By following this guide, you've set up a framework that is easy to maintain, fast to execute, and highly scalable for complex testing scenarios.

📝 Summary & Key Takeaways

This guide detailed the setup of a test automation framework using Jest and Puppeteer. We covered the core definitions, provided a step-by-step installation and configuration roadmap, and shared a practical example of a GitHub page title test. By adhering to best practices like proper async handling and utilizing network idle states, and avoiding common pitfalls like missing awaits, teams can build reliable UI automation suites that integrate seamlessly into modern JavaScript development workflows.

Share it with your network and help others learn too!

Follow me on social media for more developer tips, tricks, and tutorials. Let's connect and build something great together!