Get your setup working faster. Join our Discord for optimisation tips from elite testers.Join our Discord
Run Percy using CLI
How to run Percy via CLI and capture snapshots for visual comparisons.
Percy Snapshots are a fundamental component of Percy. These are static images of your web pages or components and provide a visual baseline of how your application should look, making it easier to detect any unexpected visual changes introduced by code modifications.
On this page, we’ll explore the available options to take Percy snapshots, the process of creating your custom configuration files, the default settings provided by Percy, the available configurations for utilizing this command, and the rules governing the precedence of configuration files.
You can run Percy using the CLI in two ways:
Use percy exec when running with a configuration file.
Use percy snapshot [options] <file|dir|sitemap> to capture snapshots directly.
This is not applicable when using BrowserStack SDK.
Choose the appropriate method and refer to the following section for details:
To run Percy via the percy exec command, you need to create a configuration file. Let’s get started!
Configuration file
Run percy config:create within your project’s main directory (or from wherever you run percy). This configuration file allows you to globally set configuration options for each build.
There are various options to customize the configuration of Percy Software Development Kits (SDKs). Run percy config:create --help to see the all options.
Running percy config:create command will generate a basic configuration file with default settings already filled in as shown:
Once the configuration file is created, run percy exec and it automatically detects the file and use the specified options for all snapshots in the build.
Config CLI command
The Percy CLI has a config CLI command, which helps managing Percy config.
```bash
$ percy config --help
manage Percy config files
USAGE
$ percy config:COMMAND
COMMANDS
config:create Create a Percy config file
config:migrate Migrate a Percy config file to the latest version
config:validate Validate a Percy config file
```
```bash
$ percy config:migrate --help
Migrate a Percy config file to the latest version
USAGE
$ percy config:migrate [FILEPATH] [OUTPUT]
ARGUMENTS
FILEPATH current config filepath, detected by default
OUTPUT new config filepath to write to, defaults to FILEPATH
OPTIONS
-d, --dry-run prints the new config rather than writing it
EXAMPLES
$ percy config:migrate
$ percy config:migrate --dry-run
$ percy config:migrate ./config/percy.yml
$ percy config:migrate .percy.yml .percy.js
```
Percy currently support for the following configuration options:
For Percy
Option
Description
token
A Percy project token can be provided here. Note: PERCY_TOKEN environment variable would override token provided in config file.
defer-uploads
Upload all snapshots post tests are complete. This is only required in a few cases, refer Capture Responsive DOM snapshots for details.
For Snapshot command
Option
Description
widths
An array of numbers, in pixels, representing the widths you’d like to capture for each snapshot. Default: [375, 1280]
min-height
A number specifying the minimum height in pixels each snapshot should be. Default: 1024.
percy-css
A string containing Percy specific CSS that will be applied to each snapshot (per-snapshot Percy CSS is concatenated to the end of this value).
enable-javascript
A boolean that enables JavaScript for all snapshots in the project. This may cause side-effects like animations or redirects making your snapshots less reliable. Default: false. Note: When you capture the DOM, JavaScript remains enabled regardless of the “enable-javascript” option. JavaScript is only disabled in our rendering environment. You can use JavaScript to set the DOM state, take a Percy snapshot, and we will render it with JavaScript enabled or disabled based on the flag.
scope
A string of a selector to scope the given screenshot to.
enableLayout
A boolean to enable layout testing while capturing the screenshot. Default:false.
scope-options
This option is specific to the scope element and works only if the scope is passed. scroll: a boolean to scroll on scope element passed. Learn more
Below options are only applicable with Percy on Automate integration.
Option
Description
freeze-animated-image
To determine whether Percy will perform stabilization on the DOM. Default: false.
freeze-animated-image-options
To freeze specific animated images that do not appear to freeze. Default: false.
freeze-image-by-selectors
To freeze specific animated images by selectors. Note: To be passed under freeze-animated-image-options option.
freeze-image-by-xpaths
To freeze specific animated images by xpaths. Note: To be passed under freeze-animated-image-options option.
ignore-regions
To ignore a particular set of elements or sections in DOM.
ignore-region-selectors
Ignore particular sections of DOM based on strings of CSS selectors array. Default: []. Note: To be passed under ignore-regions option.
ignore-region-xpaths
Ignore particular sections of DOM based on strings of Xpaths array. Default: []. Note: To be passed under ignore-regions option.
consider-regions
To counteract the effects of IntelliIgnore.
consider-region-selectors
Consider particular sections of DOM based on strings of CSS selectors array. Default: []. Note: To be passed under consider-regions option.
consider-region-xpaths
Consider particular sections of DOM based on strings of Xpaths array. Default: []. Note: To be passed under consider-regions option.
full-Page
To capture fullpage screenshots. Default: false.
Check the following configuration file to understand how to set the options when using Percy on Automate.
If your static files will be hosted in a subdirectory, instead of the web server’s root path, set that subdirectory with this flag. Default: /
files
Glob or array of globs for matching static file paths to snapshot. Default: **/*.{html,htm}
ignore
Glob or array of globs for matching static file paths to ignore.
For asset discovery
Option
Description
allowed-hostnames
An array of additional hostnames to save asset contents from. By default Percy only captures assets from the hostname that the snapshot was taken on. More Info
disallowed-hostnames
An array of hostnames to immediately abort requests from.
request-headers
An object containing HTTP headers to be sent for each request made during asset discovery.
authorization
A username/password combo to authenticate requests for Percy. More Info
Custom user-agent string used when requesting assets.
network-idle-timeout
The amount of time where the snapshotted page has had zero network requests (in milliseconds). Once this has been reached, asset discovery closes.
concurrency
The amount of parallelism asset discovery has for processing snapshots.
launch-options
Options to pass to the asset discovery that is being launched. - executable: A path to a Chromium browser executable on disk. - headless: Hide or show the asset discovery browser. Default: true - args: Browser flags/args to pass when launching the executable. - timeout: Timeout for how long the browser will try to launch. Default: 30000. More Info
A boolean flag that enables the capture of image assets found in srcset. Note: This will increase the time required for asset discovery.
retry
A boolean flag that will retry asset discovery up to 3 times. Set this to true if you encounter intermittent log lines like this: [percy] Encountered an error taking snapshot: (name of the snapshot) for the same snapshot across multiple builds.
For file upload
Option
Description
files
Glob or comma-separated string of globs for matching the file types to upload. Default: */.{png,jpg,jpeg}.
ignore
Glob or comma-separated string of globs for matching the files to ignore.
Percy SDKs can be configured through either a configuration file or by adding a “percy” entry in your package.json. Percy will search for the following configurations, in the below order, within the current working directory:
a "percy" property in package.json
a JSON or YAML, extensionless .percyrc file
a .percy.* file with the extensions .json, .yaml, .yml, or .js
a percy.config.js if you are using “CommonJS” module
a percy.config.cjs if you are using “type”: “module” in the package.json file
If a configuration is not found in the current directory, Percy will proceed to search the directory hierarchy, inspecting each directory along the way for these configurations, until it discovers a suitable configuration or reaches the home directory.
The Percy snapshot is a powerful command that allows you to capture visual snapshots of web pages, lists, sitemaps, or static directories.
In this section, we’ll explore the different usage of Percy snapshot command through CLI and respective examples for the same. You have the option to either capture a full screenshot or take a screenshot of a single element.
Percy snapshot command
Run the Percy snapshot command via the command-line interface (CLI) as shown below. You can specify a snapshots file, a static directory, or the URL of a sitemap that you wish to capture snapshots of.
Use the below options along with percy snapshot command. For details, refer the below table:
Option
Description
General
-b, –base-url : Set the base URL for the pages when taking snapshots. --include : Define one or more globs/patterns to include specific snapshots. --exclude : Specify one or more globs/patterns to exclude specific snapshots.
Static
–clean-urls: Rewrite static index and filepath URLs to be clean.
Percy
-c, –config : Specify the path to the Percy configuration file. -d, --dry-run: Print snapshot names only, useful for testing without actually taking snapshots. -h, --allowed-hostname : Set allowed hostnames to capture during asset discovery. -t, --network-idle-timeout : Define the asset discovery network idle timeout. --disable-cache: Disable asset discovery caches. --debug: Enable debug mode for asset discovery and prevent uploading snapshots.
Global
-v, –verbose: Log all activity. -q, –quiet: Log errors only. -s, –silent: Disable all logging. –help: Display command help.
Examples
Snapshot a file
When you have a file containing a list of snapshots, it must be in YAML, JSON, or a JavaScript format exporting a list of pages. Each snapshot should include at least a URL that can be navigated to using a browser.
With the snapshot command, you can interact with the page by providing an execute option. This can be any valid JavaScript you run inside of a browser.
For advanced use cases, you can specify an execute function and additionalSnapshots for each snapshot to execute JavaScript within the page execution context before taking subsequent snapshots.
All options are also accepted by other file formats. For execute however, a string containing a function body can be provided when the file format prevents normal functions.
The snapshot command also accepts a JavaScript file that exports an array of objects (with the keys name & url present). You can export sync or async functions from this file.
For example, a common use case is to build an array of pages dynamically and then iterate over that array to snapshot pages. You can export that array to the snapshot command. As a snapshots.js file:
Instead of an array of snapshots, list files can also contain an object that defines additional top-level options along with a snapshots option containing the array of snapshots. This allows dynamically filtering lists with include/exclude options, and enables utilizing features such as YAML anchors and references.
The base URL path the static site should be served under.
clean-urls
When true, rewrite index and filepath URLs to be clean.
include/exclude
A predicate or an array of predicates matching snapshots to include/exclude. A predicate can be a string glob or pattern, a regular expression, or a function that accepts a snapshot object and returns true or false if the snapshot is considered matching or not.
rewrites
An object containing source-destination pairs for rewriting URLs. Paths for resources can sometimes be expected to be in a certain format that may not be covered by the clean-urls option. For such paths, rewrites can map a short, clean, or pretty path to a specific resource. Paths are matched using path-to-regexp.
overrides
An array of per-snapshot option overrides. Just like page listing options, static snapshots may also contain per-snapshot configuration options. However, since pages are matched against the files option, so are per-snapshot configuration options via an array of overrides. If multiple overrides match a snapshot, they will be merged with previously matched overrides.
Snapshot a sitemap URL
When providing a sitemap URL, the document must be an XML document. You can use --include and --exclude flags to filter snapshots. The Percy configuration file also accepts options.
Sitemaps can contain a lot of URLs, so its best to always start with the --dry-run flag while fine tuning the include and exclude options.
Sometimes capturing a full-page screenshot isn’t necessary. For example, if there are dynamic parts of the page that you don’t need to test or are only interested in a very specific region to test.
For these cases, you can pass a scope snapshot option and Percy will only capture the scoped element on the given widths. This can be passed as a per-snapshot option.
The scope selector accepts any valid selector you would be able to pass to document querySelector.
If there are multiple matching selectors on the page, Percy will select the first matching element.
The Percy Snapshot Command is a versatile command for capturing and comparing visual snapshots, making it an indispensable part of your web development and testing workflow.
Use cases
Multiple elements with the same selector
If you would like to scope a screenshot to a specific element that has the same matching selector as other elements on the page you’ll have to get more specific with your selector. This can be done by either adding another unique selector to that element or by using standard CSS selectors to get more specific. This is the same way you would write CSS – Percy doesn’t add anything to this process.
For example, given the below DOM:
```html
<html>
<head>
<title>Example</title>
</head>
<body>
<h1 class="underline">My example</h1>
<p class="underline">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tristique convallis sem, vitae sodales risus accumsan in</p>
<p class="underline">Lorem ipsum dolor sit amet, consectetur adipiscing elit. Maecenas tristique convallis sem, vitae sodales risus accumsan in</p>
</body>
</html>
```
Instead of using just .underline to select the element, you would want to either specify the element type (h1 / p) or by using CSS tree-structural pseudo-classes like :last-of-type or :nth-child.
p.underline:last-of-type scope selects last paragraph
Selector for elements serialized by Percy
It may happen that your single-element screenshots are not working correctly with canvas/video elements.
During DOM serialization <canvas>, <video> elements are converted to <img>. Check canvas elements in Percy’s SDK Workflow. This can cause the selector to not match, and an incorrect screenshot.
To work around this, we can use CSS tree structural pseudo-classes as suggested in the previous section.
```html HTML
<!-- Skipping most of the stuff for brevity -->
<!-- Original DOM -->
<div class="selector">
<canvas> </canvas>
<canvas> </canvas>
<video> </video>
</div>
<!-- Post DOM Serialization -->
<div class="selector">
<img> </img>
<img> </img>
<img> </img>
</div>
```