@percy/nightwatch 2.2.0 → 2.2.1-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/README.md CHANGED
@@ -1,139 +1,209 @@
1
- # @percy/nightwatch
2
-
3
- [![Version](https://img.shields.io/npm/v/@percy/nightwatch.svg)](https://www.npmjs.com/package/@percy/nightwatch)
4
- ![Test](https://github.com/percy/percy-nightwatch/workflows/Test/badge.svg)
5
-
6
- [Percy](https://percy.io) visual testing for [Nightwatch.js](http://nightwatchjs.org).
7
-
8
- ## Installation
9
-
10
- ```sh-session
11
- $ npm install --save-dev @percy/cli @percy/nightwatch
12
- ```
13
-
14
- ### Nightwatch configuration
15
-
16
- Add the path exported by `@percy/nightwatch` to your Nightwatch configuration's
17
- `custom_commands_path` property.
18
-
19
- ```javascript
20
- const percy = require('@percy/nightwatch');
21
-
22
- module.exports = {
23
- // ...
24
- custom_commands_path: [percy.path],
25
- // ...
26
- };
27
- ```
28
-
29
- ## Usage
30
-
31
- This is an example test using the `browser.percySnapshot()` command. For other examples of how to
32
- write Nightwatch tests, check out [the official Nightwatch
33
- guides](https://nightwatchjs.org/guide/using-nightwatch/writing-tests.html).
34
-
35
- ```javascript
36
- module.exports = {
37
- 'Snapshots pages': function(browser) {
38
- browser
39
- .url('http://example.com')
40
- .assert.containsText('h1', 'Example Domain')
41
- .percySnapshot('Example snapshot');
42
- browser
43
- .url('http://google.com')
44
- .assert.elementPresent('img[alt="Google"]')
45
- .percySnapshot('Google homepage');
46
- browser.end();
47
- }
48
- };
49
- ```
50
-
51
- Running the test above directly will result in the following logs:
52
-
53
- ```sh-session
54
- $ nightwatch
55
-
56
- [Example] Test Suite
57
- ====================
58
- ...
59
-
60
- Running: Snapshots pages
61
-
62
- ✔ Testing if element <h1> contains text 'Example Domain'
63
- [percy] Percy is not running, disabling snapshots
64
- ✔ Testing if element <img[alt="Google"]> is present
65
-
66
- OK. 2 assertions passed.
67
- ```
68
-
69
- When running with [`percy
70
- exec`](https://github.com/percy/cli/tree/master/packages/cli-exec#percy-exec), and your project's
71
- `PERCY_TOKEN`, a new Percy build will be created and snapshots will be uploaded to your project.
72
-
73
- ```sh-session
74
- $ export PERCY_TOKEN=[your-project-token]
75
- $ percy exec -- nightwatch
76
- [percy] Percy has started!
77
- [percy] Created build #1: https://percy.io/[your-project]
78
- [percy] Running "nightwatch"
79
-
80
- [Example] Test Suite
81
- ====================
82
- ...
83
-
84
- Running: Snapshots pages
85
-
86
- ✔ Testing if element <h1> contains text 'Example Domain'
87
- [percy] Snapshot taken "Snapshots pages"
88
- ✔ Testing if element <img[alt="Google"]> is present
89
- [percy] Snapshot taken "Google homepage"
90
-
91
- OK. 2 assertions passed.
92
- [percy] Stopping percy...
93
- [percy] Finalized build #1: https://percy.io/[your-project]
94
- [percy] Done!
95
- ```
96
-
97
- ## Configuration
98
-
99
- `percySnapshot([name][, options])`
100
-
101
- - `name` - The snapshot name; must be unique to each snapshot
102
- - `options` - [See per-snapshot configuration options](https://docs.percy.io/docs/cli-configuration#per-snapshot-configuration)
103
-
104
- ## Upgrading
105
-
106
- ### Automatically with `@percy/migrate`
107
-
108
- We built a tool to help automate migrating to the new CLI toolchain! Migrating
109
- can be done by running the following commands and following the prompts:
110
-
111
- ``` shell
112
- $ npx @percy/migrate
113
- ? Are you currently using @percy/nightwatch? Yes
114
- ? Install @percy/cli (required to run percy)? Yes
115
- ? Migrate Percy config file? Yes
116
- ? Upgrade SDK to @percy/nightwatch@2.0.0? Yes
117
- ```
118
-
119
- This will automatically run the changes described below for you.
120
-
121
- ### Manually
122
-
123
- #### Installing `@percy/cli`
124
-
125
- If you're coming from a pre-2.0 version of this package, make sure to install `@percy/cli` after
126
- upgrading to retain any existing scripts that reference the Percy CLI command.
127
-
128
- ```sh-session
129
- $ npm install --save-dev @percy/cli
130
- ```
131
-
132
- #### Migrating Config
133
-
134
- If you have a previous Percy configuration file, migrate it to the newest version with the
135
- [`config:migrate`](https://github.com/percy/cli/tree/master/packages/cli-config#percy-configmigrate-filepath-output) command:
136
-
137
- ```sh-session
138
- $ percy config:migrate
139
- ```
1
+ # @percy/nightwatch
2
+
3
+ [![Version](https://img.shields.io/npm/v/@percy/nightwatch.svg)](https://www.npmjs.com/package/@percy/nightwatch)
4
+ ![Test](https://github.com/percy/percy-nightwatch/workflows/Test/badge.svg)
5
+
6
+ [Percy](https://percy.io) visual testing for [Nightwatch.js](http://nightwatchjs.org).
7
+
8
+ ## Installation
9
+
10
+ ```sh-session
11
+ $ npm install --save-dev @percy/cli @percy/nightwatch
12
+ ```
13
+
14
+ ### Nightwatch configuration
15
+
16
+ Add the path exported by `@percy/nightwatch` to your Nightwatch configuration's
17
+ `custom_commands_path` property.
18
+
19
+ ```javascript
20
+ const percy = require('@percy/nightwatch');
21
+
22
+ module.exports = {
23
+ // ...
24
+ custom_commands_path: [percy.path],
25
+ // ...
26
+ };
27
+ ```
28
+
29
+ ## Usage
30
+
31
+ This is an example test using the `browser.percySnapshot()` command. For other examples of how to
32
+ write Nightwatch tests, check out [the official Nightwatch
33
+ guides](https://nightwatchjs.org/guide/using-nightwatch/writing-tests.html).
34
+
35
+ ```javascript
36
+ module.exports = {
37
+ "Snapshots pages": function (browser) {
38
+ browser.url("http://example.com").assert.containsText("h1", "Example Domain").percySnapshot("Example snapshot");
39
+ browser.url("http://google.com").assert.elementPresent('img[alt="Google"]').percySnapshot("Google homepage");
40
+ browser.end();
41
+ },
42
+ };
43
+ ```
44
+
45
+ Running the test above directly will result in the following logs:
46
+
47
+ ```sh-session
48
+ $ nightwatch
49
+
50
+ [Example] Test Suite
51
+ ====================
52
+ ...
53
+
54
+ Running: Snapshots pages
55
+
56
+ ✔ Testing if element <h1> contains text 'Example Domain'
57
+ [percy] Percy is not running, disabling snapshots
58
+ ✔ Testing if element <img[alt="Google"]> is present
59
+
60
+ OK. 2 assertions passed.
61
+ ```
62
+
63
+ When running with [`percy
64
+ exec`](https://github.com/percy/cli/tree/master/packages/cli-exec#percy-exec), and your project's
65
+ `PERCY_TOKEN`, a new Percy build will be created and snapshots will be uploaded to your project.
66
+
67
+ ```sh-session
68
+ $ export PERCY_TOKEN=[your-project-token]
69
+ $ percy exec -- nightwatch
70
+ [percy] Percy has started!
71
+ [percy] Created build #1: https://percy.io/[your-project]
72
+ [percy] Running "nightwatch"
73
+
74
+ [Example] Test Suite
75
+ ====================
76
+ ...
77
+
78
+ Running: Snapshots pages
79
+
80
+ ✔ Testing if element <h1> contains text 'Example Domain'
81
+ [percy] Snapshot taken "Snapshots pages"
82
+ ✔ Testing if element <img[alt="Google"]> is present
83
+ [percy] Snapshot taken "Google homepage"
84
+
85
+ OK. 2 assertions passed.
86
+ [percy] Stopping percy...
87
+ [percy] Finalized build #1: https://percy.io/[your-project]
88
+ [percy] Done!
89
+ ```
90
+
91
+ ## Configuration
92
+
93
+ `percySnapshot([name][, options])`
94
+
95
+ - `name` - The snapshot name; must be unique to each snapshot
96
+ - `options` - [See per-snapshot configuration options](https://www.browserstack.com/docs/percy/take-percy-snapshots/overview#per-snapshot-configuration)
97
+
98
+ ### Responsive snapshots
99
+
100
+ Set `responsiveSnapshotCapture: true` (and optionally `widths`) to have the Nightwatch SDK resize the browser window and capture DOM snapshots at multiple breakpoints in a single Percy snapshot. The SDK implementation:
101
+
102
+ - Calling `PercyDOM.waitForResize()` once and waiting on `window.resizeCount` before each snapshot.
103
+ - Using Chrome DevTools Protocol resizing when available (disable with `PERCY_DISABLE_CDP_RESIZE=true`) and falling back to WebDriver window APIs.
104
+ - Honoring the environment toggles:
105
+ - `PERCY_RESPONSIVE_CAPTURE_MIN_HEIGHT` – ensure a minimum viewport height using `snapshot.minHeight`.
106
+ - `PERCY_RESPONSIVE_CAPTURE_RELOAD_PAGE` – reload the page (and re-inject Percy DOM) between widths.
107
+ - `RESPONSIVE_CAPTURE_SLEEP_TIME` – wait (in seconds) between width changes.
108
+ - `PERCY_ENABLE_LAZY_LOADING_SCROLL` – trigger the lazy-load scroll helper described below.
109
+ - Resetting the window back to its original dimensions after the final width.
110
+
111
+ ### Lazy-loading scroll helper
112
+
113
+ When `PERCY_ENABLE_LAZY_LOADING_SCROLL` is set the SDK scrolls the page in increments (up to 25,000px) to trigger lazy-loaded content before each snapshot. Additional environment variables control the behavior:
114
+
115
+ - `PERCY_LAZY_LOAD_SCROLL_TIME` – seconds to pause between scroll steps (default `0.45`).
116
+ - `BYPASS_SCROLL_TO_TOP=true` – skip scrolling back to the top of the page.
117
+ - `PERCY_SLEEP_AFTER_LAZY_LOAD_COMPLETE` – seconds to wait after finishing the scroll sequence.
118
+
119
+ ### Running tests
120
+
121
+ All unit and Nightwatch integration tests can be executed with:
122
+
123
+ ```sh
124
+ yarn test
125
+ ```
126
+
127
+ Additional scripts are available when iterating locally:
128
+
129
+ - `yarn test:unit` &mdash; runs the mocha suite under `test/unit/**`.
130
+ - `yarn test:nightwatch` &mdash; runs the Nightwatch suite (wrapped by `percy exec`) in headless Firefox.
131
+
132
+ ### E2E Visual Testing
133
+
134
+ The repository includes comprehensive end-to-end (E2E) visual regression tests that create actual Percy builds and validate all SDK features. These tests use real HTML fixtures and test scenarios to ensure the SDK works correctly.
135
+
136
+ **Running E2E tests locally:**
137
+
138
+ ```sh
139
+ # Terminal 1 - Start test server
140
+ yarn e2e:server
141
+
142
+ # Terminal 2 - Run tests with Percy
143
+ PERCY_TOKEN=your_token yarn e2e:chrome # Chrome (with CDP)
144
+ PERCY_TOKEN=your_token yarn e2e:firefox # Firefox (WebDriver)
145
+
146
+ # Or run everything in one command
147
+ PERCY_TOKEN=your_token yarn e2e:local
148
+ ```
149
+
150
+ **What's tested:**
151
+ - ✅ Responsive snapshots with multiple widths (CDP + WebDriver fallbacks)
152
+ - ✅ Lazy loading with scroll helper
153
+ - ✅ Canvas and stylesheet serialization
154
+ - ✅ Region algorithms (ignore, standard, layout, intelliignore)
155
+ - ✅ Percy CSS, scope selectors, and DOM transformation
156
+ - ✅ Cookie capture and attachment
157
+ - ✅ Shadow DOM serialization
158
+ - ✅ Complex real-world integration scenarios
159
+
160
+ **E2E test structure:**
161
+ - `test/e2e/fixtures/` - 7 comprehensive HTML test pages
162
+ - `test/e2e/e2e.test.js` - 13 optimized test scenarios covering all features
163
+ - `test/e2e/server.js` - Static file server for fixtures
164
+ - `test/e2e/nightwatch.e2e.conf.js` - E2E-specific configuration
165
+
166
+ **Snapshot count:**
167
+ - PRs: ~25-30 snapshots (Chrome only, optimized for quick review)
168
+ - Main branch: ~75-90 snapshots (Chrome + Firefox + environment tests)
169
+
170
+ See [`test/e2e/README.md`](test/e2e/README.md) for detailed documentation, environment variables, and troubleshooting.
171
+
172
+ **CI/CD:** E2E tests run automatically on pull requests (Chrome) and main branch pushes (Chrome + Firefox) via GitHub Actions (`.github/workflows/e2e-percy.yml`).
173
+
174
+ ## Upgrading
175
+
176
+ ### Automatically with `@percy/migrate`
177
+
178
+ We built a tool to help automate migrating to the new CLI toolchain! Migrating
179
+ can be done by running the following commands and following the prompts:
180
+
181
+ ```shell
182
+ $ npx @percy/migrate
183
+ ? Are you currently using @percy/nightwatch? Yes
184
+ ? Install @percy/cli (required to run percy)? Yes
185
+ ? Migrate Percy config file? Yes
186
+ ? Upgrade SDK to @percy/nightwatch@2.0.0? Yes
187
+ ```
188
+
189
+ This will automatically run the changes described below for you.
190
+
191
+ ### Manually
192
+
193
+ #### Installing `@percy/cli`
194
+
195
+ If you're coming from a pre-2.0 version of this package, make sure to install `@percy/cli` after
196
+ upgrading to retain any existing scripts that reference the Percy CLI command.
197
+
198
+ ```sh-session
199
+ $ npm install --save-dev @percy/cli
200
+ ```
201
+
202
+ #### Migrating Config
203
+
204
+ If you have a previous Percy configuration file, migrate it to the newest version with the
205
+ [`config:migrate`](https://github.com/percy/cli/tree/master/packages/cli-config#percy-configmigrate-filepath-output) command:
206
+
207
+ ```sh-session
208
+ $ percy config:migrate
209
+ ```
@@ -1,52 +1,90 @@
1
1
  // Collect client and environment information
2
2
  const sdkPkg = require('../package.json');
3
3
  const nightwatchPkg = require('nightwatch/package.json');
4
+ const { captureDOM, waitForReady } = require('../lib/snapshot');
5
+ const { createRegion } = require('../lib/regions');
4
6
  const CLIENT_INFO = `${sdkPkg.name}/${sdkPkg.version}`;
5
7
  const ENV_INFO = `${nightwatchPkg.name}/${nightwatchPkg.version}`;
8
+ const NOT_RUNNING_ERROR = 'Percy is not running, disabling snapshots.';
9
+ const AUTOMATE_ERROR = 'Invalid function call - percySnapshot(). Please use percyScreenshot() function while using Percy with Automate. For more information on usage of percyScreenshot, refer https://www.browserstack.com/docs/percy/integrate/functional-and-visual';
6
10
 
7
11
  // Take a DOM snapshot and post it to the snapshot endpoint
12
+ function injectPercyDOM(browser, domScript) {
13
+ return new Promise((resolve, reject) => {
14
+ browser.execute(domScript, [], (result) => {
15
+ if (result && result.status && result.status !== 0 && result.error) {
16
+ return reject(result.error);
17
+ }
18
+ resolve();
19
+ });
20
+ });
21
+ }
22
+
8
23
  module.exports = class PercySnapshotCommand {
9
- async command(name, options) {
24
+ async command(name, options = {}) {
10
25
  let utils = await import('@percy/sdk-utils');
11
-
12
- if (!(await utils.isPercyEnabled())) return;
13
26
  name = name || this.api.currentTest.name;
14
27
  let log = utils.logger('nightwatch');
15
28
 
29
+ if (!(await utils.isPercyEnabled())) {
30
+ if (process.env.PERCY_RAISE_ERROR === 'true') {
31
+ throw new Error(NOT_RUNNING_ERROR);
32
+ }
33
+ return;
34
+ }
35
+
36
+ if (utils.percy?.type === 'automate') {
37
+ throw new Error(AUTOMATE_ERROR);
38
+ }
39
+
16
40
  try {
41
+ let domScript = await utils.fetchPercyDOM();
42
+
17
43
  // Inject the DOM serialization script
18
- await this.api.execute(await utils.fetchPercyDOM());
19
-
20
- // Serialize and capture the DOM
21
- /* istanbul ignore next: no instrumenting injected code */
22
- let { domSnapshot, url } = await new Promise((resolve) => {
23
- this.api.execute(function(options) {
24
- return {
25
- /* eslint-disable-next-line no-undef */
26
- domSnapshot: PercyDOM.serialize(options),
27
- url: document.URL
28
- };
29
- }, [options], function(result) {
30
- // Check if we're in Nightwatch 1.x (which returns with `.value`)
31
- result.value ? resolve(result.value) : resolve(result);
32
- });
33
- });
44
+ await injectPercyDOM(this.api, domScript);
34
45
 
35
- // Post the DOM to the snapshot endpoint with snapshot options and other info
36
- await utils.postSnapshot({
37
- ...options,
46
+ // Readiness gate — runs before serialize when CLI supports it.
47
+ const readinessDiagnostics = await waitForReady(this.api, options, utils, log);
48
+
49
+ // Thread domScript + log through ctx so concurrent percySnapshot calls
50
+ // (parallel workers in the same Node process) don't race on shared
51
+ // module-level state.
52
+ let { domSnapshot, url } = await captureDOM(this.api, options, utils, domScript, log);
53
+
54
+ // Attach readiness diagnostics so the CLI can log timing and pass/fail
55
+ if (readinessDiagnostics && domSnapshot && typeof domSnapshot === 'object' && !Array.isArray(domSnapshot)) {
56
+ domSnapshot.readiness_diagnostics = readinessDiagnostics;
57
+ }
58
+
59
+ // Filter out DOM-only serialization options that shouldn't be posted to Percy
60
+ const {
61
+ ignoreCanvasSerializationErrors,
62
+ ignoreStyleSheetSerializationErrors,
63
+ ...snapshotOptions
64
+ } = options;
65
+
66
+ const postData = {
67
+ ...snapshotOptions,
68
+ domSnapshot,
38
69
  environmentInfo: ENV_INFO,
39
70
  clientInfo: CLIENT_INFO,
40
- domSnapshot,
41
71
  name,
42
72
  url
43
- });
73
+ };
74
+
75
+ // Post the DOM to the snapshot endpoint with snapshot options and other info
76
+ await utils.postSnapshot(postData);
44
77
  } catch (error) {
45
78
  // Handle errors
46
79
  log.error(`Could not take DOM snapshot "${name}"`);
47
80
  log.error(error);
81
+
82
+ if (process.env.PERCY_RAISE_ERROR === 'true') {
83
+ throw error;
84
+ }
48
85
  }
49
86
  }
50
87
  };
51
88
 
89
+ module.exports.createRegion = createRegion;
52
90
  module.exports.path = __dirname;
package/lib/regions.js ADDED
@@ -0,0 +1,59 @@
1
+ const AVAILABLE_ALGORITHMS = ['standard', 'layout', 'ignore', 'intelliignore'];
2
+
3
+ function createRegion({
4
+ boundingBox = null,
5
+ elementXpath = null,
6
+ elementCSS = null,
7
+ padding = null,
8
+ algorithm = 'ignore',
9
+ diffSensitivity = null,
10
+ imageIgnoreThreshold = null,
11
+ carouselsEnabled = null,
12
+ bannersEnabled = null,
13
+ adsEnabled = null,
14
+ diffIgnoreThreshold = null
15
+ } = {}) {
16
+ if (!AVAILABLE_ALGORITHMS.includes(algorithm)) {
17
+ throw new Error(`Invalid algorithm "${algorithm}". Expected one of: ${AVAILABLE_ALGORITHMS.join(', ')}`);
18
+ }
19
+
20
+ const elementSelector = {};
21
+ if (boundingBox) elementSelector.boundingBox = boundingBox;
22
+ if (elementXpath) elementSelector.elementXpath = elementXpath;
23
+ if (elementCSS) elementSelector.elementCSS = elementCSS;
24
+
25
+ const region = { algorithm };
26
+ if (Object.keys(elementSelector).length > 0) {
27
+ region.elementSelector = elementSelector;
28
+ }
29
+
30
+ if (padding) {
31
+ region.padding = padding;
32
+ }
33
+
34
+ const configuration = {};
35
+ if (['standard', 'intelliignore'].includes(algorithm)) {
36
+ if (diffSensitivity !== null) configuration.diffSensitivity = diffSensitivity;
37
+ if (imageIgnoreThreshold !== null) configuration.imageIgnoreThreshold = imageIgnoreThreshold;
38
+ if (carouselsEnabled !== null) configuration.carouselsEnabled = carouselsEnabled;
39
+ if (bannersEnabled !== null) configuration.bannersEnabled = bannersEnabled;
40
+ if (adsEnabled !== null) configuration.adsEnabled = adsEnabled;
41
+ }
42
+
43
+ if (Object.keys(configuration).length > 0) {
44
+ region.configuration = configuration;
45
+ }
46
+
47
+ const assertion = {};
48
+ if (diffIgnoreThreshold !== null) assertion.diffIgnoreThreshold = diffIgnoreThreshold;
49
+
50
+ if (Object.keys(assertion).length > 0) {
51
+ region.assertion = assertion;
52
+ }
53
+
54
+ return region;
55
+ }
56
+
57
+ module.exports = {
58
+ createRegion
59
+ };