A heap snapshot represents how the memory is distributed among your page's JavaScript objects and related DOM nodes at the point of time the snapshot was taken. This helps you find and fix memory issues that affect page performance, including memory leaks, memory bloat, and frequent garbage collections.

With Chrome DevTools Protocol support now available in Selenium 4, Nightwatch now allows you to take heap snapshot of your browser's current execution context anytime during the test run and save it as a .heapsnapshot file. This file can then be loaded into the Chrome DevTools (Memory > select "Heap Snapshot" > click on "Load" button at the bottom) to analyze memory graphs, compare snapshots, and find memory leaks.

This command only works with Chromium based browsers such as Google Chrome and Microsoft Edge.

Take heap snapshot

This command allows you to take a snapshot of how your heap memory is distributed among your page's JavaScript objects and related DOM nodes, which then can be loaded into Chrome DevTools to analyze and find any memory leaks.

You can also take multiple snapshots of the heap memory at different points of time and then compare what has changed in the memory between the time those snapshots were taken.

Call the browser.takeHeapSnapshot() command with the required parameters anytime you want to take the snapshot.

takeHeapSnapshot() accepts the location where the snapshot is to be saved as the first argument. An optional callback function can be passed as the second argument, which will run once the process of taking the heap snapshot is complete, with the contents of the snapshot as its argument.



describe('Take heap snapshot', function() {

When used with async/await syntax, takeHeapSnapshot command returns the contents of the heap snapshot, which then can be saved manually to a .heapsnapshot file.


const fs = require('fs');

describe('Take heap snapshot with async/await', async function() {
  await browser.navigateTo('https://www.google.com');

  const heapSnapshot = await browser.takeHeapSnapshot();

  fs.writeFileSync('snap.heapsnapshot', heapSnapshot);
Improve this article