Lattes

Latte recipes, espresso drinks and coffee how-to

In this article
  1. What You'll Need
  2. Step-by-Step
  3. Common Mistakes
  4. Tips
  5. Troubleshooting
  6. Frequently Asked Questions

How to Capture Page Screenshots in Mocha and PhantomJS Tests

· 5 min read · Espresso Drinks

Capturing page screenshots during automated tests provides immediate visual verification of your application’s state, making it easier to debug UI issues and perform visual regression testing. By integrating screenshot capabilities into Mocha test suites running on PhantomJS (or similar headless browsers), you can automatically generate evidence of failures or successful renders without manual intervention. This process requires a basic understanding of asynchronous JavaScript testing and file system operations.

What You'll Need

  • A Node.js environment installed on your machine.
  • Mocha as your test runner.
  • PhantomJS or a compatible headless browser driver (such as SlimerJS or a modern alternative like Puppeteer if PhantomJS is deprecated in your context).
  • A local development server or a static HTML file to serve as the target for screenshots.
  • A directory structure within your project to store generated images.

Step-by-Step

  1. Initialize Your Project: Ensure you have a valid package.json file. Install Mocha and PhantomJS as dev dependencies using npm: npm install --save-dev mocha phantomjs-prebuilt. Note that PhantomJS is largely unmaintained; for new projects, consider using Puppeteer with Chrome, but this guide focuses on the PhantomJS architecture requested.
  2. Create a Test File: Create a new file, for example, screenshot.test.js, inside a test directory. Import the necessary modules. You will need phantomjs-prebuilt to spawn the browser instance and fs (File System) from Node.js to write the image data to disk.
  3. Configure PhantomJS Options: Before navigating to any page, configure the PhantomJS instance. Set the viewport size to ensure consistent screenshot dimensions. For example, set the width to 1024px and height to 768px. This prevents responsive design variations from affecting your visual comparisons.
  4. Navigate to the Target URL: Use the page.open() method provided by PhantomJS to load the webpage you wish to capture. Ensure you wait for the page to fully load. In PhantomJS, this often involves checking the page.status or waiting for specific DOM elements to appear before proceeding.
  5. Render the Screenshot: Once the page is loaded, invoke the page.render('path/to/screenshot.png') method. This command captures the current viewport and saves it as a PNG file. The path should be relative to where the test script is executed.
  6. Handle Asynchronous Operations: Mocha relies on callbacks or Promises to handle asynchronous tasks. Ensure your test function returns a Promise or calls the done() callback only after the screenshot has been successfully written to the disk. Failing to do so may result in the test passing before the file is saved.
  7. Clean Up Resources: After the screenshot is captured, close the PhantomJS page and exit the browser instance to free up memory. This should be done in an afterEach hook in Mocha to ensure cleanup happens regardless of whether the test passed or failed.
  8. Run the Test: Execute your test suite using the command npx mocha test/screenshot.test.js. Check the specified directory for the generated PNG files. If the test fails, inspect the image to see what went wrong visually.

Common Mistakes

One frequent error is attempting to take a screenshot before the page resources (images, CSS, fonts) have finished loading. PhantomJS does not always wait for all assets by default, leading to blank or partially rendered images. Another mistake is ignoring the asynchronous nature of Mocha; if you do not properly chain promises or use async/await patterns, the test runner may finish before the file I/O operation completes. Additionally, hardcoding absolute paths for screenshots can cause portability issues when moving tests between different machines or CI environments.

Tips

To improve reliability, always define a fixed viewport size at the start of your session. This ensures that visual diffs are meaningful and not skewed by window resizing. Consider adding a small delay after navigation to allow for any client-side animations or lazy-loaded content to render. Using descriptive filenames that include the test name and timestamp helps in organizing artifacts, especially when running large suites. Finally, implement error handling around the page.render call to catch cases where the browser crashes or the path is invalid, providing clearer failure messages in your test logs.

Troubleshooting

If screenshots are not being generated, first verify that the output directory exists and is writable. PhantomJS cannot create nested directories automatically; you must ensure the parent folder is present. If the images appear blank, check if the website requires JavaScript execution that might be failing silently. Review the PhantomJS console logs by enabling verbose mode. If you encounter permission errors, ensure your user account has write access to the test output folder. For CI/CD pipelines, remember that headless environments may lack certain font libraries or display drivers required by complex web pages, which can result in missing text or layout shifts.

Frequently Asked Questions

Can I capture full-page screenshots instead of just the viewport?

Yes, PhantomJS supports full-page rendering. By setting the clipRect property in the page settings to match the document's total height and width, you can capture the entire scrollable area rather than just the visible screen portion.

Why are my screenshots blurry or low resolution?

This usually occurs because the default viewport resolution is too low. Increase the viewport width and height in your PhantomJS configuration. Additionally, ensure you are saving the image in PNG format, which is lossless, rather than JPEG, which introduces compression artifacts.

Is PhantomJS still recommended for new projects?

While this guide addresses PhantomJS specifically, it is important to note that PhantomJS has reached end-of-life. Modern alternatives like Puppeteer (for Chrome) or Playwright are generally recommended for new automation projects due to better performance, active maintenance, and support for newer web standards.

How do I compare two screenshots automatically?

Mocha itself does not compare images. You need to integrate a visual regression library such as pixelmatch or resemble.js. These tools compare the new screenshot against a baseline image and report the difference percentage, allowing you to fail the test if changes exceed a defined threshold.

Can I take screenshots only when a test fails?

Absolutely. This is a common strategy to save storage space. You can place the screenshot logic inside the afterEach hook and check the status of the previous test. If the test status indicates failure, trigger the screenshot capture; otherwise, skip it.

Do I need a display server to run PhantomJS in Docker?

Not necessarily. PhantomJS runs in headless mode, meaning it does not require a graphical user interface. However, some Linux distributions may require virtual framebuffer utilities like Xvfb if specific fonts or rendering libraries expect a display environment, though many modern containers handle this natively.