webship-js 2.0.11 → 2.0.13

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.
Files changed (175) hide show
  1. package/.circleci/config.yml +10 -1
  2. package/.drone.yml +7 -7
  3. package/.github/workflows/github-actions.yml +48 -0
  4. package/.gitlab-ci.yml +9 -4
  5. package/.harness/webship-js-pipeline.yml +5 -6
  6. package/.semaphore/semaphore.yml +6 -9
  7. package/.teamcity/settings.kts +7 -6
  8. package/.travis.yml +6 -1
  9. package/AGENTS.md +1 -1
  10. package/CLAUDE.md +65 -23
  11. package/Jenkinsfile +5 -3
  12. package/azure-pipelines.yml +17 -8
  13. package/bamboo-specs/bamboo.yml +9 -15
  14. package/bin/init-webship.js +53 -10
  15. package/bitbucket-pipelines.yml +5 -1
  16. package/buildspec.yml +6 -7
  17. package/cloudbuild.yaml +28 -12
  18. package/codefresh.yml +6 -6
  19. package/cucumber.js +17 -10
  20. package/docs/00-quick-start.md +8 -0
  21. package/docs/02-bbr-smart-waits.md +15 -10
  22. package/docs/03-selector-registry.md +24 -0
  23. package/docs/04-step-reference.md +51 -25
  24. package/docs/05-web-first-assertions.md +6 -0
  25. package/docs/07-auth-state.md +1 -1
  26. package/docs/08-clock-mocking.md +21 -2
  27. package/docs/09-api-testing.md +40 -2
  28. package/docs/10-accessibility.md +2 -0
  29. package/docs/11-debugging.md +3 -1
  30. package/docs/12-ai-agent-guide.md +5 -0
  31. package/docs/13-faq.md +72 -1
  32. package/docs/14-recipes-cookbook.md +2 -0
  33. package/docs/15-tag-conventions.md +2 -1
  34. package/docs/16-ci-cd.md +140 -119
  35. package/docs/README.md +5 -5
  36. package/docs/advanced-screenshots.md +3 -1
  37. package/docs/api-step-definitions.md +16 -2
  38. package/docs/global-settings.md +69 -17
  39. package/docs/install-webship-js.md +2 -0
  40. package/docs/step-definitions/then-i-should-see.md +14 -1
  41. package/docs/step-definitions/then-item-checkbox.md +2 -0
  42. package/docs/step-definitions/when-i-fill.md +4 -0
  43. package/docs/step-definitions/when-i-select-option-select-list.md +2 -0
  44. package/examples/check-switch.html +37 -0
  45. package/examples/choice-controls.html +29 -0
  46. package/examples/click-whitespace.html +37 -0
  47. package/examples/datetime-fields.html +52 -0
  48. package/examples/element-selector-hint.html +16 -0
  49. package/examples/field-states.html +27 -0
  50. package/examples/fill-in-empty.html +26 -0
  51. package/examples/fill-unreachable.html +27 -0
  52. package/examples/follow-hidden-first.html +29 -0
  53. package/examples/iframe-inner.html +20 -0
  54. package/examples/iframe-nested.html +16 -0
  55. package/examples/iframe-outer.html +15 -0
  56. package/examples/multi-value-fields.html +54 -0
  57. package/examples/registered-names.html +15 -0
  58. package/examples/select-by-label.html +33 -0
  59. package/examples/settle-budget.html +21 -0
  60. package/examples/sorted-tables.html +38 -0
  61. package/examples/text-matching.html +48 -0
  62. package/examples/text-order.html +25 -0
  63. package/examples/touch.html +22 -0
  64. package/examples/viewport-top.html +36 -0
  65. package/package.json +17 -1
  66. package/playwright.config.ts +3 -1
  67. package/tests/check-api-launch-url.js +106 -0
  68. package/tests/check-assets.js +103 -0
  69. package/tests/check-attachments.js +105 -0
  70. package/tests/check-breakpoints.js +117 -0
  71. package/tests/check-clock.js +143 -0
  72. package/tests/check-config.js +90 -0
  73. package/tests/check-context.js +215 -0
  74. package/tests/check-dry-run.js +104 -0
  75. package/tests/check-examples.js +10 -4
  76. package/tests/check-exit-report.js +141 -0
  77. package/tests/check-javascript-errors.js +105 -0
  78. package/tests/check-must-fail.js +5 -4
  79. package/tests/check-network-changed.js +137 -0
  80. package/tests/check-scaffold.js +54 -2
  81. package/tests/check-screenshots.js +117 -0
  82. package/tests/check-settle-verbs.js +137 -0
  83. package/tests/check-time-limit.js +104 -0
  84. package/tests/check-video.js +156 -0
  85. package/tests/check-world.js +167 -0
  86. package/tests/features/api-base-url.feature +25 -0
  87. package/tests/features/api-form-data.feature +18 -0
  88. package/tests/features/api-json-paths.feature +24 -0
  89. package/tests/features/api-response-contains.feature +21 -0
  90. package/tests/features/api-response-header-presence.feature +17 -0
  91. package/tests/features/api-response-header.feature +17 -0
  92. package/tests/features/api-saved-placeholders.feature +37 -0
  93. package/tests/features/api-step-definitions-individual.feature +1 -1
  94. package/tests/features/api-tables.feature +40 -0
  95. package/tests/features/breakpoints.feature +25 -0
  96. package/tests/features/check-switch.feature +28 -0
  97. package/tests/features/choice-controls.feature +35 -0
  98. package/tests/features/click-whitespace.feature +29 -0
  99. package/tests/features/complete-api-testing-examples.feature +1 -1
  100. package/tests/features/datetime-field-lookup.feature +29 -0
  101. package/tests/features/element-selector-hint.feature +14 -0
  102. package/tests/features/field-state.feature +21 -0
  103. package/tests/features/fill-in-empty-value.feature +41 -0
  104. package/tests/features/fill-reachable.feature +13 -0
  105. package/tests/features/follow-hidden-first.feature +9 -0
  106. package/tests/features/iframe-nested.feature +43 -0
  107. package/tests/features/javascript-tolerated-errors.feature +20 -0
  108. package/tests/features/modal-open.feature +13 -0
  109. package/tests/features/multi-value-field-lookup.feature +30 -0
  110. package/tests/features/registered-names.feature +14 -0
  111. package/tests/features/select-by-label.feature +31 -0
  112. package/tests/features/selector-files.feature +14 -0
  113. package/tests/features/selectors-table-header.feature +35 -0
  114. package/tests/features/settle-budget.feature +11 -0
  115. package/tests/features/sorted-tables.feature +19 -0
  116. package/tests/features/storage-quoted-values.feature +26 -0
  117. package/tests/features/text-matching.feature +38 -0
  118. package/tests/features/text-order.feature +14 -0
  119. package/tests/features/touch.feature +21 -0
  120. package/tests/features/viewport-top.feature +13 -0
  121. package/tests/features/xml-namespaces.feature +34 -0
  122. package/tests/must-fail/api-json-paths.feature +21 -0
  123. package/tests/must-fail/api-response-contains.feature +23 -0
  124. package/tests/must-fail/api-response-header-presence.feature +17 -0
  125. package/tests/must-fail/api-response-header.feature +21 -0
  126. package/tests/must-fail/api-without-base-url.feature +11 -0
  127. package/tests/must-fail/breakpoints.feature +15 -0
  128. package/tests/must-fail/choice-controls.feature +25 -0
  129. package/tests/must-fail/clock.feature +11 -0
  130. package/tests/must-fail/datetime-field.feature +10 -0
  131. package/tests/must-fail/element-selector-hint.feature +17 -0
  132. package/tests/must-fail/field-state.feature +20 -0
  133. package/tests/must-fail/fill-field.feature +30 -0
  134. package/tests/must-fail/iframe-text.feature +17 -0
  135. package/tests/must-fail/modal-open.feature +26 -0
  136. package/tests/must-fail/multi-value-field.feature +18 -0
  137. package/tests/must-fail/registered-names.feature +25 -0
  138. package/tests/must-fail/select-list.feature +15 -0
  139. package/tests/must-fail/selector-files.feature +10 -0
  140. package/tests/must-fail/sorted-tables.feature +20 -0
  141. package/tests/must-fail/storage-before-a-page.feature +13 -0
  142. package/tests/must-fail/text-matching.feature +16 -0
  143. package/tests/must-fail/text-order.feature +15 -0
  144. package/tests/must-fail/viewport-top.feature +20 -0
  145. package/tests/must-fail/yaml-numbers.feature +48 -0
  146. package/tests/step-definitions/a11y.steps.js +24 -15
  147. package/tests/step-definitions/action.steps.js +53 -20
  148. package/tests/step-definitions/api.steps.js +349 -67
  149. package/tests/step-definitions/assertion.steps.js +100 -10
  150. package/tests/step-definitions/auth.steps.js +15 -18
  151. package/tests/step-definitions/clock.steps.js +22 -0
  152. package/tests/step-definitions/debug.steps.js +8 -0
  153. package/tests/step-definitions/dialog.steps.js +7 -0
  154. package/tests/step-definitions/element.steps.js +132 -17
  155. package/tests/step-definitions/field.steps.js +412 -96
  156. package/tests/step-definitions/form.steps.js +88 -37
  157. package/tests/step-definitions/iframe.steps.js +89 -29
  158. package/tests/step-definitions/input.steps.js +26 -7
  159. package/tests/step-definitions/javascript.steps.js +64 -22
  160. package/tests/step-definitions/modal.steps.js +79 -13
  161. package/tests/step-definitions/navigation.steps.js +14 -0
  162. package/tests/step-definitions/network.steps.js +15 -5
  163. package/tests/step-definitions/response.steps.js +6 -4
  164. package/tests/step-definitions/responsive.steps.js +26 -33
  165. package/tests/step-definitions/screenshot.steps.js +25 -8
  166. package/tests/step-definitions/scroll.steps.js +20 -0
  167. package/tests/step-definitions/selectors.steps.js +95 -48
  168. package/tests/step-definitions/storage.steps.js +38 -13
  169. package/tests/step-definitions/table.steps.js +81 -6
  170. package/tests/step-definitions/video.steps.js +52 -55
  171. package/tests/step-definitions/wait.steps.js +88 -23
  172. package/tests/step-definitions/web-first.steps.js +69 -35
  173. package/tests/step-definitions/webship.js +741 -145
  174. package/tests/step-definitions/xml.steps.js +49 -15
  175. package/tests/step-definitions/yaml.steps.js +45 -20
@@ -1,14 +1,21 @@
1
1
  const { Given, When, Then, Before } = require('@cucumber/cucumber');
2
2
  const assert = require('assert');
3
- const { friendly, sendRequest } = require('./webship');
3
+ const { friendly, sendRequest, excerpt } = require('./webship');
4
4
 
5
5
  // The API steps talk to an API on its own terms: its own base URL, its own
6
6
  // authentication and headers. A request is sent outside the browser session
7
7
  // (no cookie of the browser goes with it), and it follows the HTTPS setting
8
8
  // of the browser context, so a self-signed or locally issued certificate is
9
9
  // accepted whenever the browser accepts it.
10
+ // Placeholders are replaced in the headers when the request is sent, so a
11
+ // header set before its value exists (in a Background, before the response
12
+ // that carries it) gets it.
10
13
  function sendApiRequest(world, method, url, headers, data) {
11
- return sendRequest(world, { method, url, headers, data, session: false });
14
+ const sent = {};
15
+ for (const [name, value] of Object.entries(headers || {})) {
16
+ sent[name] = typeof value === 'string' ? replacePlaceHolder(value) : value;
17
+ }
18
+ return sendRequest(world, { method, url, headers: sent, data, session: false });
12
19
  }
13
20
 
14
21
  // Global variables to store API response and request data
@@ -20,22 +27,82 @@ let authorization = '';
20
27
  let placeHolders = {};
21
28
 
22
29
  Before(async function () {
23
- // Reset API state before each scenario
30
+ // Reset API state before each scenario: the base URL too, so a scenario
31
+ // sends its requests where it says, alone or after another one.
24
32
  apiResponse = null;
25
33
  apiRequestData = null;
26
34
  apiHeaders = {};
35
+ baseURL = '';
27
36
  authorization = '';
28
37
  placeHolders = {};
29
38
  });
30
39
 
31
40
  /**
32
- * Helper function to replace placeholders in text
41
+ * Replace the placeholders of the scenario in a text, as plain text: no
42
+ * character of a name or a value has a special meaning ("$1.50", "[id]").
33
43
  */
34
44
  function replacePlaceHolder(string) {
45
+ let text = String(string);
35
46
  for (const [key, value] of Object.entries(placeHolders)) {
36
- string = string.replace(new RegExp(key, 'g'), value);
47
+ if (key) text = text.split(key).join(String(value));
37
48
  }
38
- return string;
49
+ return text;
50
+ }
51
+
52
+ /**
53
+ * The body of an API response as text: the JSON written out when the body is
54
+ * JSON, the text of the body otherwise.
55
+ */
56
+ function responseText(response) {
57
+ return typeof response.data === 'string' ? response.data : JSON.stringify(response.data);
58
+ }
59
+
60
+ /**
61
+ * Find a text in another one, letter case ignored. Returns the match (with
62
+ * its index) or null.
63
+ */
64
+ function findText(haystack, needle) {
65
+ return new RegExp(needle.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i').exec(haystack);
66
+ }
67
+
68
+ /**
69
+ * A short excerpt of a text around a position, white space collapsed.
70
+ */
71
+ function excerptAround(text, index, length) {
72
+ const start = Math.max(0, index - 60);
73
+ const end = Math.min(text.length, index + length + 60);
74
+ return (start > 0 ? '…' : '') + text.slice(start, end).replace(/\s+/g, ' ') + (end < text.length ? '…' : '');
75
+ }
76
+
77
+ /**
78
+ * Build the failure of an API assertion for a tester: what was expected and
79
+ * did not hold, what was found, the request the response answers and a hint.
80
+ * No stack.
81
+ */
82
+ function apiFailure(message, details) {
83
+ const info = details || {};
84
+ const lines = [message];
85
+ if (info.found !== undefined && info.found !== null) lines.push(` Found: ${info.found}`);
86
+ if (apiResponse && apiResponse.config) {
87
+ lines.push(` Request: ${String(apiResponse.config.method || '').toUpperCase()} ${apiResponse.config.url} (answered ${apiResponse.status})`);
88
+ }
89
+ if (info.hint) lines.push(` Hint: ${info.hint}`);
90
+ return friendly(lines.join('\n'));
91
+ }
92
+
93
+ /**
94
+ * The rows of a two-column table of names and values (headers, body fields).
95
+ * Every row is data, as the examples write the table; a first row that names
96
+ * the columns (| name | value |, | header | value |, | field | value |,
97
+ * | key | value |) is a header row and is left out.
98
+ */
99
+ function nameValueRows(table) {
100
+ const rows = table.raw();
101
+ if (rows.length === 0) return rows;
102
+ const [name, value] = rows[0].map((cell) => String(cell || '').trim().toLowerCase());
103
+ const header = /^(?:name|header|header name|field|field name|key)$/.test(name || '')
104
+ && /^(?:value|header value|field value)$/.test(value || '');
105
+ return header ? rows.slice(1) : rows;
39
106
  }
40
107
 
41
108
  /**
@@ -46,12 +113,73 @@ function prepareUrl(url) {
46
113
  }
47
114
 
48
115
  /**
49
- * Helper function to get nested property from object using dot notation.
116
+ * The address a request step sends to: a whole `http(s)://` URL as written,
117
+ * else the path joined to the base URL of the scenario. Without a base URL a
118
+ * path has no address, and the step fails before sending anything.
119
+ */
120
+ function apiUrl(endpoint, method) {
121
+ const target = replacePlaceHolder(endpoint);
122
+ if (/^https?:\/\//i.test(target)) return target;
123
+ if (!baseURL) {
124
+ throw friendly([
125
+ `No API base URL is set, so "${target}" has no address.`,
126
+ ` Request: ${method} ${target} (not sent)`,
127
+ ` Hint: set one in the scenario or its Background before the request: Given the API base URL is "https://api.example.com" ("/" for the launch URL of the run), or give the request a whole URL.`,
128
+ ].join('\n'));
129
+ }
130
+ return baseURL + '/' + prepareUrl(endpoint);
131
+ }
132
+
133
+ /**
134
+ * Find a property of a JSON value by its path: a dot path (`data.0.id`,
135
+ * `data[0].id`) or a JSON Pointer (`/data/0/id`, with ~1 for "/" and ~0 for
136
+ * "~"), the form the YAML steps take. Returns where it stopped when a part of
137
+ * the path is missing, written the way the path was written.
138
+ *
139
+ * @param {*} obj
140
+ * @param {string} path
141
+ * @returns {{found: boolean, value: *, missing: string, at: string}}
142
+ */
143
+ function resolveJsonPath(obj, path) {
144
+ const pointer = path.startsWith('/');
145
+ const parts = pointer
146
+ ? path.slice(1).split('/').map((part) => part.replace(/~1/g, '/').replace(/~0/g, '~'))
147
+ : path.replace(/\[(\d+)\]/g, '.$1').split('.').filter((part) => part !== '');
148
+ const label = (count) => (pointer ? '/' + parts.slice(0, count).join('/') : parts.slice(0, count).join('.'));
149
+ let current = obj;
150
+ for (let i = 0; i < parts.length; i += 1) {
151
+ const part = parts[i];
152
+ const has = current !== null && typeof current === 'object' && Object.prototype.hasOwnProperty.call(current, part);
153
+ if (!has) return { found: false, value: undefined, missing: part, at: i ? label(i) : '' };
154
+ current = current[part];
155
+ }
156
+ return { found: true, value: current, missing: '', at: '' };
157
+ }
158
+
159
+ /**
160
+ * The value at a path of a JSON value, or undefined when a part is missing.
50
161
  */
51
162
  function getNestedProperty(obj, path) {
52
- return path.split('.').reduce((current, prop) => {
53
- return current && current[prop] !== undefined ? current[prop] : undefined;
54
- }, obj);
163
+ return resolveJsonPath(obj, path).value;
164
+ }
165
+
166
+ /**
167
+ * The words that say where a path stopped: the part that is missing and the
168
+ * property that does not have it.
169
+ */
170
+ function missingPart(result) {
171
+ return result.at
172
+ ? `"${result.at}" has no "${result.missing}"`
173
+ : `the response has no "${result.missing}" at its top level`;
174
+ }
175
+
176
+ const PATH_HINT = 'name a property with a dot path ("data.0.id", "data[0].id") or a JSON Pointer ("/data/0/id").';
177
+
178
+ /**
179
+ * A value of a JSON response, written for a failure message.
180
+ */
181
+ function shownValue(value) {
182
+ return typeof value === 'string' ? `"${value}"` : excerpt(JSON.stringify(value));
55
183
  }
56
184
 
57
185
  /**
@@ -61,6 +189,7 @@ function getNestedProperty(obj, path) {
61
189
  * Example #2: Given we are authenticating as "user@example.com" with "secret" password
62
190
  * Example #3: Given I am authenticating as "api-user" with "pass!word" password
63
191
  * Example #4: Given we are authenticating as "reader" with "readonly" password
192
+ * Example #5: Given I am authenticating as "editor@example.com" with "s3cret" password
64
193
  *
65
194
  */
66
195
  Given(/^(?:I am|we are) authenticating as "([^"]*)" with "([^"]*)" password$/, function (username, password) {
@@ -87,7 +216,10 @@ Given(/^(?:I |we )?set header "([^"]*)" with value "([^"]*)"$/, function (name,
87
216
  });
88
217
 
89
218
  /**
90
- * Set the base URL for API calls. Accepts full URLs or paths relative to LAUNCH_URL.
219
+ * Set the base URL of the API requests of this scenario. A full URL is used as
220
+ * written; a path is joined to the launch URL of the run (worldParameters
221
+ * launchUrl, which LAUNCH_URL sets). The base URL is reset before every
222
+ * scenario: set it in each scenario, or in a Background.
91
223
  *
92
224
  * Example #1: Given the API base URL is "https://jsonplaceholder.typicode.com"
93
225
  * Example #2: Given I set the API base URL to "https://api.example.com/v1"
@@ -103,8 +235,8 @@ Given(/^(?:the API base URL is|I set the API base URL to|the base URL is) "([^"]
103
235
  if (url.match(/^https?:\/\//)) {
104
236
  baseURL = url.replace(/\/$/, ''); // Remove trailing slash
105
237
  } else {
106
- // If not a full URL, combine with the LAUNCH_URL env variable or default
107
- const launchUrl = (process.env.LAUNCH_URL || 'http://localhost:8080').replace(/\/$/, '');
238
+ // A path: joined to the launch URL of the run, as "I am on" joins one.
239
+ const launchUrl = String(this.launchUrl || (this.parameters && this.parameters.launchUrl) || process.env.LAUNCH_URL || 'http://localhost:8080').replace(/\/$/, '');
108
240
  baseURL = (launchUrl + '/' + url).replace(/\/+/g, '/').replace(/\/$/, '');
109
241
  baseURL = baseURL.replace(':/', '://');
110
242
  }
@@ -128,7 +260,8 @@ Given(/^(?:I set the header|we set the header|the header) "([^"]*)" (?:to|is) "(
128
260
  });
129
261
 
130
262
  /**
131
- * Set multiple headers using a table.
263
+ * Set multiple headers using a table: one `| name | value |` row per header,
264
+ * every row sent (a first row that names the columns is left out).
132
265
  *
133
266
  * Example #1: Given I set the following headers:
134
267
  * | Content-Type | application/json |
@@ -149,9 +282,12 @@ Given(/^(?:I set the header|we set the header|the header) "([^"]*)" (?:to|is) "(
149
282
  * | Authorization | Bearer {{token}} |
150
283
  * | Accept | application/json |
151
284
  * | X-Request-ID | req-001 |
285
+ * Example #5: Given I set the following headers:
286
+ * | Accept | application/json |
287
+ * | X-Request-Id | test-runner-42 |
152
288
  */
153
289
  Given(/^(?:I|we) set the following headers:$/, function (table) {
154
- table.rows().forEach(row => {
290
+ nameValueRows(table).forEach(row => {
155
291
  apiHeaders[row[0]] = replacePlaceHolder(row[1]);
156
292
  });
157
293
  });
@@ -177,7 +313,9 @@ Given(/^(?:I set the request body to|we set the request body to|the request body
177
313
  });
178
314
 
179
315
  /**
180
- * Set request body using a table.
316
+ * Set request body using a table: one `| field | value |` row per field,
317
+ * every row sent (a first row that names the columns is left out). "true",
318
+ * "false" and numbers are sent as JSON booleans and numbers.
181
319
  *
182
320
  * Example #1: Given I set the request body with:
183
321
  * | name | John Doe |
@@ -198,10 +336,13 @@ Given(/^(?:I set the request body to|we set the request body to|the request body
198
336
  * | status | published |
199
337
  * | priority | 5 |
200
338
  * | featured | false |
339
+ * Example #5: Given I set the request body with:
340
+ * | title | Release notes |
341
+ * | status | draft |
201
342
  */
202
343
  Given(/^(?:I|we) set the request body with:$/, function (table) {
203
344
  apiRequestData = {};
204
- table.rows().forEach(row => {
345
+ nameValueRows(table).forEach(row => {
205
346
  let value = replacePlaceHolder(row[1]);
206
347
 
207
348
  // Try to parse as number or boolean, otherwise keep as string
@@ -228,7 +369,7 @@ Given(/^(?:I|we) set the request body with:$/, function (table) {
228
369
  * Example #10: When we send a GET request to "/posts/{{postId}}"
229
370
  */
230
371
  When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)"$/, async function (method, endpoint) {
231
- const url = baseURL + '/' + prepareUrl(endpoint);
372
+ const url = apiUrl(endpoint, method);
232
373
 
233
374
  try {
234
375
  apiResponse = await sendApiRequest(this, method, url, apiHeaders, apiRequestData);
@@ -258,9 +399,11 @@ When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)"$/, async function (method
258
399
  * | title | Welcome |
259
400
  * | body | Hello Webship.co|
260
401
  * | userId | 1 |
402
+ * Example #5: When I send a PATCH request to "/users/42" with values:
403
+ * | status | active |
261
404
  */
262
405
  When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with values:$/, async function (method, endpoint, table) {
263
- const url = baseURL + '/' + prepareUrl(endpoint);
406
+ const url = apiUrl(endpoint, method);
264
407
  const fields = {};
265
408
 
266
409
  const rowsHash = table.rowsHash();
@@ -310,9 +453,15 @@ When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with values:$/, async fun
310
453
  * "subscribe": true
311
454
  * }
312
455
  * """
456
+ * Example #5: When I send a PATCH request to "/posts/1" with body:
457
+ * """
458
+ * {
459
+ * "status": "published"
460
+ * }
461
+ * """
313
462
  */
314
463
  When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with body:$/, async function (method, endpoint, docString) {
315
- const url = baseURL + '/' + prepareUrl(endpoint);
464
+ const url = apiUrl(endpoint, method);
316
465
  const body = replacePlaceHolder(docString.trim());
317
466
 
318
467
  // Parse JSON if the body looks like JSON, otherwise send as string
@@ -341,7 +490,9 @@ When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with body:$/, async funct
341
490
  });
342
491
 
343
492
  /**
344
- * Sends HTTP request to specific URL with form data.
493
+ * Sends HTTP request to specific URL with form data: one `name=value` field
494
+ * per line, split on the first "=" only, so a value keeps every "=" after it
495
+ * (a query string, a base64 token). Blank lines are skipped.
345
496
  *
346
497
  * Example #1: When I send a POST request to "/login" with form data:
347
498
  * """
@@ -368,18 +519,23 @@ When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with body:$/, async funct
368
519
  * name=Updated
369
520
  * country=UN
370
521
  * """
522
+ * Example #5: When I send a POST request to "/search" with form data:
523
+ * """
524
+ * q=webship
525
+ * page=2
526
+ * """
371
527
  */
372
528
  When(/^(?:I |we )?send a ([A-Z]+) request to "([^"]+)" with form data:$/, async function (method, endpoint, docString) {
373
- const url = baseURL + '/' + prepareUrl(endpoint);
529
+ const url = apiUrl(endpoint, method);
374
530
  const body = replacePlaceHolder(docString.trim());
375
531
 
376
- // Parse form data
532
+ // Parse form data: one field per line, split on its first "=".
377
533
  const fields = {};
378
534
  body.split('\n').forEach(line => {
379
- const [key, value] = line.split('=');
380
- if (key && value !== undefined) {
381
- fields[key.trim()] = value.trim();
382
- }
535
+ const at = line.indexOf('=');
536
+ if (at <= 0) return;
537
+ const key = line.slice(0, at).trim();
538
+ if (key) fields[key] = line.slice(at + 1).trim();
383
539
  });
384
540
 
385
541
  // Convert to URL encoded format
@@ -420,7 +576,9 @@ Then(/^(?:the )?API response code should be (\d+)$/, function (expectedCode) {
420
576
  });
421
577
 
422
578
  /**
423
- * Checks that API response body contains specific text.
579
+ * Checks that the body of the last API response contains a text. Letter case
580
+ * does not matter, and placeholders set with `I set placeholder` are replaced
581
+ * in the text first. The negative step reads the body the same way.
424
582
  *
425
583
  * Example #1: Then the API response should contain "success"
426
584
  * Example #2: Then API response should contain "John Doe"
@@ -430,22 +588,26 @@ Then(/^(?:the )?API response code should be (\d+)$/, function (expectedCode) {
430
588
  * Example #6: Then API response should contain "id"
431
589
  * Example #7: Then the API response should contain "email"
432
590
  * Example #8: Then API response should contain "hello@un.org"
591
+ * Example #9: Then the API response should contain "{{userId}}"
433
592
  */
434
593
  Then(/^(?:the )?API response should contain "([^"]*)"$/, function (expectedText) {
435
594
  if (!apiResponse) {
436
595
  throw friendly('No API response available. Make sure to send a request first.');
437
596
  }
438
-
439
- const responseBody = typeof apiResponse.data === 'string' ?
440
- apiResponse.data : JSON.stringify(apiResponse.data);
441
-
442
- const expectedRegexp = new RegExp(expectedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'), 'i');
443
- assert(expectedRegexp.test(responseBody),
444
- `Response should contain "${expectedText}", but got: ${responseBody}`);
597
+ const body = responseText(apiResponse);
598
+ const text = replacePlaceHolder(expectedText);
599
+ if (!findText(body, text)) {
600
+ throw apiFailure(`The API response does not contain "${text}".`, {
601
+ found: `"${excerpt(body)}"`,
602
+ hint: 'the step looks for the text anywhere in the body of the response, letter case ignored, after replacing the placeholders. For a JSON property, use: the JSON response should have "<path>" equal to "<value>"',
603
+ });
604
+ }
445
605
  });
446
606
 
447
607
  /**
448
- * Checks that API response body doesn't contain specific text.
608
+ * Checks that the body of the last API response does not contain a text.
609
+ * Letter case does not matter, and placeholders are replaced first, exactly
610
+ * as in the positive step: a text that one finds, the other refuses.
449
611
  *
450
612
  * Example #1: Then the API response should not contain "error"
451
613
  * Example #2: Then API response should not contain "failed"
@@ -455,18 +617,21 @@ Then(/^(?:the )?API response should contain "([^"]*)"$/, function (expectedText)
455
617
  * Example #6: Then API response should not contain "secret"
456
618
  * Example #7: Then the API response should not contain "exception"
457
619
  * Example #8: Then API response should not contain "stack trace"
620
+ * Example #9: Then the API response should not contain "{{apiKey}}"
458
621
  */
459
622
  Then(/^(?:the )?API response should not contain "([^"]*)"$/, function (unexpectedText) {
460
623
  if (!apiResponse) {
461
624
  throw friendly('No API response available. Make sure to send a request first.');
462
625
  }
463
-
464
- const responseBody = typeof apiResponse.data === 'string' ?
465
- apiResponse.data : JSON.stringify(apiResponse.data);
466
-
467
- const expectedRegexp = new RegExp(unexpectedText.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'));
468
- assert(!expectedRegexp.test(responseBody),
469
- `Response should not contain "${unexpectedText}", but it does. Response: ${responseBody}`);
626
+ const body = responseText(apiResponse);
627
+ const text = replacePlaceHolder(unexpectedText);
628
+ const match = findText(body, text);
629
+ if (match) {
630
+ throw apiFailure(`The API response contains "${text}", but it should not.`, {
631
+ found: `"${excerptAround(body, match.index, match[0].length)}"`,
632
+ hint: 'the step looks for the text anywhere in the body of the response, letter case ignored, after replacing the placeholders.',
633
+ });
634
+ }
470
635
  });
471
636
 
472
637
  /**
@@ -502,6 +667,12 @@ Then(/^(?:the )?API response should not contain "([^"]*)"$/, function (unexpecte
502
667
  * "email": "hello@un.org"
503
668
  * }
504
669
  * """
670
+ * Example #5: Then the API response should contain json:
671
+ * """
672
+ * {
673
+ * "status": "published"
674
+ * }
675
+ * """
505
676
  */
506
677
  Then(/^(?:the )?API response should contain json:$/, function (docString) {
507
678
  if (!apiResponse) {
@@ -534,7 +705,8 @@ Then(/^(?:the )?API response should contain json:$/, function (docString) {
534
705
  });
535
706
 
536
707
  /**
537
- * Alternative syntax for JSON property verification.
708
+ * Alternative syntax for JSON property verification. The property is named by
709
+ * a dot path (`user.role`, `data[0].id`) or a JSON Pointer (`/user/role`).
538
710
  *
539
711
  * Example #1: Then the JSON response should have "name" equal to "John Doe"
540
712
  * Example #2: Then the API response should have "id" equal to 1
@@ -544,6 +716,7 @@ Then(/^(?:the )?API response should contain json:$/, function (docString) {
544
716
  * Example #6: Then the JSON property "count" should be 42
545
717
  * Example #7: Then the JSON response should have "user.role" equal to "admin"
546
718
  * Example #8: Then the JSON property "published" should be false
719
+ * Example #9: Then the JSON response should have "/data/0/type" equal to "articles"
547
720
  */
548
721
  Then(/^(?:the JSON response should have|the API response should have|the JSON property) "([^"]*)" (?:equal to|should be) (.+)$/, function (propertyPath, expectedValue) {
549
722
  if (!apiResponse) {
@@ -566,14 +739,21 @@ Then(/^(?:the JSON response should have|the API response should have|the JSON pr
566
739
  }
567
740
 
568
741
  // Get the actual value from response
569
- const actualValue = getNestedProperty(apiResponse.data, propertyPath);
570
-
571
- assert.strictEqual(actualValue, parsedExpectedValue,
572
- `Expected "${propertyPath}" to be ${parsedExpectedValue}, but got ${actualValue}`);
742
+ const result = resolveJsonPath(apiResponse.data, propertyPath);
743
+ if (!result.found) {
744
+ throw apiFailure(`The JSON response has no "${propertyPath}": ${missingPart(result)}.`, {
745
+ hint: PATH_HINT,
746
+ });
747
+ }
748
+ if (result.value !== parsedExpectedValue) {
749
+ throw apiFailure(`The JSON response has "${propertyPath}" equal to ${shownValue(result.value)}, not ${shownValue(parsedExpectedValue)}.`, {
750
+ hint: 'a value in quotes is compared as text; true, false and a number without quotes as JSON booleans and numbers.',
751
+ });
752
+ }
573
753
  });
574
754
 
575
755
  /**
576
- * Verify a JSON property exists.
756
+ * Verify a JSON property exists, named by a dot path or a JSON Pointer.
577
757
  *
578
758
  * Example #1: Then the JSON response should have property "id"
579
759
  * Example #2: Then the API response should contain property "user.email"
@@ -583,20 +763,24 @@ Then(/^(?:the JSON response should have|the API response should have|the JSON pr
583
763
  * Example #6: Then the API response should contain property "meta.total"
584
764
  * Example #7: Then the JSON response should have property "createdAt"
585
765
  * Example #8: Then the API response should contain property "links.self"
766
+ * Example #9: Then the JSON response should have property "/links/self"
586
767
  */
587
768
  Then(/^(?:the JSON response should have property|the API response should contain property) "([^"]*)"$/, function (propertyPath) {
588
769
  if (!apiResponse) {
589
770
  throw friendly('No API response available. Make sure to send a request first.');
590
771
  }
591
772
 
592
- const actualValue = getNestedProperty(apiResponse.data, propertyPath);
593
-
594
- assert(actualValue !== undefined,
595
- `Expected property "${propertyPath}" to exist in response, but it doesn't`);
773
+ const result = resolveJsonPath(apiResponse.data, propertyPath);
774
+ if (!result.found) {
775
+ throw apiFailure(`The JSON response has no "${propertyPath}": ${missingPart(result)}.`, {
776
+ hint: PATH_HINT,
777
+ });
778
+ }
596
779
  });
597
780
 
598
781
  /**
599
- * Verify a JSON property does not exist.
782
+ * Verify a JSON property does not exist, named by a dot path or a JSON
783
+ * Pointer.
600
784
  *
601
785
  * Example #1: Then the JSON response should not have property "password"
602
786
  * Example #2: Then the API response should not contain property "secret"
@@ -606,16 +790,20 @@ Then(/^(?:the JSON response should have property|the API response should contain
606
790
  * Example #6: Then the API response should not contain property "internal"
607
791
  * Example #7: Then the JSON response should not have property "debug"
608
792
  * Example #8: Then the API response should not contain property "stack"
793
+ * Example #9: Then the JSON response should not have property "/user/password"
609
794
  */
610
795
  Then(/^(?:the JSON response should not have property|the API response should not contain property) "([^"]*)"$/, function (propertyPath) {
611
796
  if (!apiResponse) {
612
797
  throw friendly('No API response available. Make sure to send a request first.');
613
798
  }
614
799
 
615
- const actualValue = getNestedProperty(apiResponse.data, propertyPath);
616
-
617
- assert(actualValue === undefined,
618
- `Expected property "${propertyPath}" not to exist in response, but it does`);
800
+ const result = resolveJsonPath(apiResponse.data, propertyPath);
801
+ if (result.found) {
802
+ throw apiFailure(`The JSON response has "${propertyPath}", but it should not.`, {
803
+ found: shownValue(result.value),
804
+ hint: PATH_HINT,
805
+ });
806
+ }
619
807
  });
620
808
 
621
809
  /**
@@ -641,26 +829,46 @@ Then(/^(?:the response should be valid JSON|the API response should be valid JSO
641
829
  });
642
830
 
643
831
  /**
644
- * Verify response header value.
832
+ * Verify a header of the last API response. "should be" compares the whole
833
+ * value (white space around it trimmed); "should contain" looks for a part of
834
+ * it. The header name is matched in any letter case.
645
835
  *
646
- * Example #1: Then the response header "Content-Type" should be "application/json"
836
+ * Example #1: Then the response header "Content-Type" should be "application/json; charset=utf-8"
647
837
  * Example #2: Then the header "Cache-Control" should contain "no-cache"
648
838
  * Example #3: Then the response header "Content-Type" should contain "charset=utf-8"
649
839
  * Example #4: Then the header "X-Powered-By" should be "Webship.co"
650
840
  * Example #5: Then the response header "ETag" should contain "etag"
651
841
  * Example #6: Then the header "Location" should contain "/users/1"
652
842
  * Example #7: Then the response header "Access-Control-Allow-Origin" should be "*"
653
- * Example #8: Then the header "Content-Length" should contain "0"
843
+ * Example #8: Then the header "Content-Length" should be "0"
654
844
  */
655
- Then(/^(?:the response header|the header) "([^"]*)" should (?:be|contain) "([^"]*)"$/, function (headerName, expectedValue) {
845
+ Then(/^(?:the response header|the header) "([^"]*)" should (be|contain) "([^"]*)"$/, function (headerName, verb, expectedValue) {
656
846
  if (!apiResponse) {
657
847
  throw friendly('No API response available. Make sure to send a request first.');
658
848
  }
659
-
849
+
660
850
  const actualValue = apiResponse.headers[headerName.toLowerCase()];
661
-
662
- assert(actualValue && actualValue.includes(expectedValue),
663
- `Expected header "${headerName}" to contain "${expectedValue}", but got "${actualValue}"`);
851
+ if (actualValue === undefined || actualValue === null) {
852
+ throw apiFailure(`The API response has no "${headerName}" header.`, {
853
+ found: `the headers ${Object.keys(apiResponse.headers).join(', ') || 'none'}`,
854
+ hint: 'check the name of the header; the step reads the headers of the last API response.',
855
+ });
856
+ }
857
+ const actual = String(actualValue).trim();
858
+ const expected = replacePlaceHolder(expectedValue).trim();
859
+ if (verb === 'be' && actual !== expected) {
860
+ throw apiFailure(`The response header "${headerName}" is "${actual}", not "${expected}".`, {
861
+ hint: actual.includes(expected)
862
+ ? `"should be" compares the whole value. For a part of it, use: the response header "${headerName}" should contain "${expected}"`
863
+ : '"should be" compares the whole value, letter case included.',
864
+ });
865
+ }
866
+ if (verb === 'contain' && !actual.includes(expected)) {
867
+ throw apiFailure(`The response header "${headerName}" does not contain "${expected}".`, {
868
+ found: `"${actual}"`,
869
+ hint: '"should contain" looks for a part of the value, letter case included.',
870
+ });
871
+ }
664
872
  });
665
873
 
666
874
  /**
@@ -688,6 +896,39 @@ Then(/^print API response$/, function () {
688
896
  console.log(typeof apiResponse.data === 'string' ? apiResponse.data : JSON.stringify(apiResponse.data, null, 2));
689
897
  });
690
898
 
899
+ /**
900
+ * Verify the last API response has, or has not, a header, whatever its value.
901
+ * The name is matched in any letter case. To check the value, use
902
+ * `the response header "X" should be "Y"` or `should contain "Y"`.
903
+ *
904
+ * Example #1: Then the API response should contain the header "ETag"
905
+ * Example #2: Then the API response should contain the header "Location"
906
+ * Example #3: Then API response should contain the header "Content-Type"
907
+ * Example #4: Then the API response should not contain the header "X-Powered-By"
908
+ * Example #5: Then the API response should not contain the header "Server"
909
+ * Example #6: And API response should not contain the header "Set-Cookie"
910
+ */
911
+ Then(/^(?:the )?API response should( not)? contain the header "([^"]*)"$/, function (notCase, headerName) {
912
+ if (!apiResponse) {
913
+ throw friendly('No API response available. Make sure to send a request first.');
914
+ }
915
+ const wanted = headerName.trim().toLowerCase();
916
+ const names = Object.keys(apiResponse.headers || {});
917
+ const present = names.some((name) => name.toLowerCase() === wanted);
918
+ if (!notCase && !present) {
919
+ throw apiFailure(`The API response has no "${headerName}" header.`, {
920
+ found: `the headers ${names.join(', ') || 'none'}`,
921
+ hint: 'check the name of the header; the step reads the headers of the last API response, in any letter case.',
922
+ });
923
+ }
924
+ if (notCase && present) {
925
+ throw apiFailure(`The API response has the header "${headerName}", but it should not.`, {
926
+ found: `"${headerName}: ${apiResponse.headers[wanted]}"`,
927
+ hint: 'the step reads the headers of the last API response, in any letter case, whatever their value.',
928
+ });
929
+ }
930
+ });
931
+
691
932
  /**
692
933
  * Sets placeholder for replacement in URLs, requests, and responses.
693
934
  *
@@ -702,4 +943,45 @@ Then(/^print API response$/, function () {
702
943
  */
703
944
  Given(/^(?:I|we) set placeholder "([^"]*)" to "([^"]*)"$/, function (placeholder, value) {
704
945
  placeHolders[placeholder] = value;
705
- });
946
+ });
947
+
948
+ /**
949
+ * Save a JSON property of the last API response as a placeholder, to carry a
950
+ * value the API returned (a token, the id of a new record) into the URLs,
951
+ * headers and bodies of the next requests and into the checks. The property
952
+ * is named the way the other JSON property steps name it.
953
+ *
954
+ * Example #1: When I save the JSON property "token" as placeholder "{{token}}"
955
+ * Example #2: When we save the JSON property "id" as placeholder "{{postId}}"
956
+ * Example #3: And I save the JSON property "data.0.id" as placeholder "{{articleId}}"
957
+ * Example #4: When I save the JSON property "user.email" as placeholder "{{email}}"
958
+ * Example #5: Then I save the JSON property "meta.total" as placeholder "{{total}}"
959
+ * And I send a GET request to "/items?count={{total}}"
960
+ */
961
+ When(/^(I |we )*save the JSON property "([^"]*)" as placeholder "([^"]*)"$/, function (pronoun, propertyPath, placeholder) {
962
+ if (!apiResponse) {
963
+ throw friendly({
964
+ action: `save the JSON property "${propertyPath}" as placeholder "${placeholder}"`,
965
+ cause: 'no API response yet',
966
+ hint: 'send a request first: When I send a GET request to "/path"',
967
+ });
968
+ }
969
+ const value = getNestedProperty(apiResponse.data, propertyPath);
970
+ if (value === undefined) {
971
+ throw apiFailure(`The JSON response has no "${propertyPath}" to save as placeholder "${placeholder}".`, {
972
+ found: `"${excerpt(responseText(apiResponse))}"`,
973
+ hint: 'name the property the way the JSON property steps do: "token", "data.0.id".',
974
+ });
975
+ }
976
+ placeHolders[placeholder] = typeof value === 'string' ? value : JSON.stringify(value);
977
+ });
978
+
979
+ // The state of the API steps for a custom step: the last response and the
980
+ // placeholders of the scenario.
981
+ module.exports = {
982
+ getApiResponse: () => apiResponse,
983
+ setPlaceholder: (name, value) => { placeHolders[name] = String(value); },
984
+ getPlaceholder: (name) => placeHolders[name],
985
+ replacePlaceHolder,
986
+ getNestedProperty,
987
+ };