testsurfer 0.1.2 → 0.3.0

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 (84) hide show
  1. package/README.md +52 -149
  2. package/dist/browser.d.ts +135 -1
  3. package/dist/browser.js +378 -2
  4. package/dist/browser.js.map +1 -1
  5. package/dist/cli.d.ts +16 -0
  6. package/dist/cli.js +140 -0
  7. package/dist/cli.js.map +1 -0
  8. package/dist/client.d.ts +12 -2
  9. package/dist/client.js +73 -4
  10. package/dist/client.js.map +1 -1
  11. package/dist/diff.d.ts +19 -0
  12. package/dist/diff.js +116 -0
  13. package/dist/diff.js.map +1 -0
  14. package/dist/events.d.ts +386 -0
  15. package/dist/events.js +1035 -0
  16. package/dist/events.js.map +1 -0
  17. package/dist/expect.d.ts +135 -26
  18. package/dist/expect.js +634 -130
  19. package/dist/expect.js.map +1 -1
  20. package/dist/frame.d.ts +88 -0
  21. package/dist/frame.js +194 -0
  22. package/dist/frame.js.map +1 -0
  23. package/dist/global.d.ts +12 -0
  24. package/dist/global.js +136 -0
  25. package/dist/global.js.map +1 -0
  26. package/dist/hooks.d.ts +28 -0
  27. package/dist/hooks.js +48 -0
  28. package/dist/hooks.js.map +1 -0
  29. package/dist/index.d.ts +22 -3
  30. package/dist/index.js +21 -3
  31. package/dist/index.js.map +1 -1
  32. package/dist/injected.d.ts +15 -0
  33. package/dist/injected.js +2025 -0
  34. package/dist/injected.js.map +1 -0
  35. package/dist/locator.d.ts +374 -86
  36. package/dist/locator.js +845 -244
  37. package/dist/locator.js.map +1 -1
  38. package/dist/media.d.ts +15 -0
  39. package/dist/media.js +83 -0
  40. package/dist/media.js.map +1 -0
  41. package/dist/net.d.ts +110 -0
  42. package/dist/net.js +498 -0
  43. package/dist/net.js.map +1 -0
  44. package/dist/page.d.ts +448 -5
  45. package/dist/page.js +1187 -31
  46. package/dist/page.js.map +1 -1
  47. package/dist/png.d.ts +28 -0
  48. package/dist/png.js +197 -0
  49. package/dist/png.js.map +1 -0
  50. package/dist/pwconfig.d.ts +66 -0
  51. package/dist/pwconfig.js +77 -0
  52. package/dist/pwconfig.js.map +1 -0
  53. package/dist/register.d.ts +6 -0
  54. package/dist/register.js +9 -0
  55. package/dist/register.js.map +1 -0
  56. package/dist/request.d.ts +29 -0
  57. package/dist/request.js +75 -0
  58. package/dist/request.js.map +1 -0
  59. package/dist/runner.d.ts +99 -15
  60. package/dist/runner.js +354 -58
  61. package/dist/runner.js.map +1 -1
  62. package/dist/screenshot.d.ts +35 -0
  63. package/dist/screenshot.js +171 -0
  64. package/dist/screenshot.js.map +1 -0
  65. package/dist/selector.d.ts +55 -0
  66. package/dist/selector.js +208 -0
  67. package/dist/selector.js.map +1 -0
  68. package/dist/selectors.d.ts +13 -0
  69. package/dist/selectors.js +16 -0
  70. package/dist/selectors.js.map +1 -0
  71. package/dist/serialize.d.ts +17 -0
  72. package/dist/serialize.js +149 -0
  73. package/dist/serialize.js.map +1 -0
  74. package/dist/shim.d.ts +15 -0
  75. package/dist/shim.js +211 -0
  76. package/dist/shim.js.map +1 -0
  77. package/dist/testinfo.d.ts +62 -0
  78. package/dist/testinfo.js +23 -0
  79. package/dist/testinfo.js.map +1 -0
  80. package/dist/values.d.ts +67 -0
  81. package/dist/values.js +293 -0
  82. package/dist/values.js.map +1 -0
  83. package/package.json +10 -3
  84. package/skills/testsurfer/SKILL.md +55 -0
package/dist/expect.js CHANGED
@@ -1,196 +1,700 @@
1
1
  /**
2
- * Web-first assertions. Every matcher polls against fresh views until
3
- * it passes or the expect timeout elapses, so tests never race the
4
- * page. Negate with `.not`.
2
+ * Web-first assertions. Every matcher polls the page until it passes
3
+ * or the expect timeout elapses, so tests never race the page. Negate
4
+ * with `.not`. Failure messages follow Playwright's layout.
5
5
  */
6
+ import { isDeepStrictEqual } from 'node:util';
7
+ import { diffValues, isStructured } from "./diff.js";
6
8
  import { matchesTemplate, parseTemplate, renderSnapshot } from "./aria.js";
7
- import { TimeoutError } from "./errors.js";
9
+ import { StrictModeError } from "./errors.js";
10
+ import { APIResponse } from "./events.js";
8
11
  import { Locator } from "./locator.js";
9
12
  import { Page } from "./page.js";
10
- const POLL_MS = 10;
13
+ import { asymmetric, pollAssertions, ValueAssertions } from "./values.js";
14
+ import { assertScreenshot } from "./screenshot.js";
15
+ import { currentTestInfo } from "./testinfo.js";
11
16
  const sleep = (ms) => new Promise((r) => setTimeout(r, ms));
12
- const normalize = (s) => s.replace(/\s+/g, ' ').trim();
13
- function textMatches(actual, expected, substring) {
14
- const norm = normalize(actual);
15
- if (expected instanceof RegExp)
16
- return expected.test(norm);
17
- const want = normalize(expected);
18
- return substring ? norm.includes(want) : norm === want;
17
+ const BACKOFF = [0, 20, 50, 100, 100, 250];
18
+ const normalize = (s) => s.replace(/[\u200b\u00ad]/g, '').trim().replace(/\s+/g, ' ');
19
+ const show = (v) => v instanceof RegExp ? String(v) : typeof v === 'string' ? JSON.stringify(v) : v === undefined ? 'undefined' : JSON.stringify(v);
20
+ /** Playwright's text match: strings compare whitespace-normalized, RegExps test the raw text. */
21
+ function textMatch(actual, expected, o) {
22
+ if (expected instanceof RegExp) {
23
+ // ignoreCase overrides the RegExp's own i flag either way.
24
+ const flags = o.ignoreCase === true ? expected.flags.replace('i', '') + 'i' : o.ignoreCase === false ? expected.flags.replace('i', '') : expected.flags;
25
+ return new RegExp(expected.source, flags).test(actual);
26
+ }
27
+ let a = o.normalize === false ? actual : normalize(actual);
28
+ let e = o.normalize === false ? expected : normalize(expected);
29
+ if (o.ignoreCase) {
30
+ a = a.toLowerCase();
31
+ e = e.toLowerCase();
32
+ }
33
+ return o.substring ? a.includes(e) : a === e;
34
+ }
35
+ /** The first stack frame outside testsurfer and Node internals: the test's own call. */
36
+ function callerFrame() {
37
+ const own = import.meta.url.replace(/\/[^/]*$/, '/').replace(/^file:\/\//, '');
38
+ return (new Error().stack ?? '')
39
+ .split('\n')
40
+ .slice(1)
41
+ .find((l) => l.trim().startsWith('at ') && !l.includes(own) && !l.includes('node:'));
42
+ }
43
+ /** An assertion failure, carrying Playwright's matcherResult. Its stack points at the test line only. */
44
+ export class ExpectError extends Error {
45
+ matcherResult;
46
+ constructor(message, name, pass, log, timeout, frame) {
47
+ super(message);
48
+ this.name = 'Error';
49
+ this.matcherResult = { message, name, pass, log, timeout };
50
+ if (frame)
51
+ this.stack = `Error: ${message}\n${frame}`;
52
+ }
53
+ }
54
+ function render(subject, rawLocator, spec, negated, timeout, last, error, custom) {
55
+ // A selector the CSS parser rejects prints as written, as Playwright
56
+ // cannot turn it back into locator code either.
57
+ const bad = error ? /while parsing css selector "([^"]*)"/.exec(error) : null;
58
+ const locator = rawLocator && bad ? rawLocator.replace(`locator('${bad[1]}')`, bad[1]) : rawLocator;
59
+ const not = negated ? 'not.' : '';
60
+ const out = [];
61
+ if (custom)
62
+ out.push(custom, '');
63
+ out.push(`expect(${subject}).${not}${spec.name}(${spec.arg}) failed`, '');
64
+ const expected = `${negated && !spec.expected.startsWith('predicate to') ? 'not ' : ''}${spec.expected}`;
65
+ const loc = locator ? [['Locator', locator]] : [];
66
+ if (error) {
67
+ for (const [k, v] of loc)
68
+ out.push(`${k}: ${v}`);
69
+ out.push(`Expected: ${expected}`, error);
70
+ }
71
+ else if (!last || !last.found) {
72
+ for (const [k, v] of loc)
73
+ out.push(`${k}: ${v}`);
74
+ out.push(`Expected: ${expected}`, `Timeout: ${timeout}ms`, 'Error: element(s) not found');
75
+ }
76
+ else if (last.diff !== undefined) {
77
+ for (const [k, v] of loc)
78
+ out.push(`${k}: ${v}`);
79
+ out.push(`Timeout: ${timeout}ms`, last.diff);
80
+ }
81
+ else {
82
+ const el = spec.expectedLabel ?? 'Expected';
83
+ const rl = spec.receivedLabel ?? 'Received';
84
+ if (el === 'Expected' && rl === 'Received') {
85
+ for (const [k, v] of loc)
86
+ out.push(`${k}: ${v}`);
87
+ out.push(`Expected: ${expected}`, `Received: ${last.received ?? ''}`, `Timeout: ${timeout}ms`);
88
+ }
89
+ else {
90
+ // Playwright aligns the two values, except in a negated message.
91
+ const w = negated ? 0 : Math.max(el.length, rl.length) + 2;
92
+ for (const [k, v] of loc)
93
+ out.push(`${k}: ${v}`);
94
+ const label = (l) => (w ? `${l}:`.padEnd(w) : `${l}: `);
95
+ out.push(`${label(el)}${expected}`, `${label(rl)}${last.received ?? ''}`, `Timeout: ${timeout}ms`);
96
+ }
97
+ }
98
+ const log = [`Expect "${negated ? 'not ' : ''}${spec.name}" with timeout ${timeout}ms`];
99
+ if (locator)
100
+ log.push(`waiting for ${locator}`);
101
+ for (const l of last?.log ?? [])
102
+ log.push(l);
103
+ if (last?.found && last.received !== undefined && last.diff === undefined && !error) {
104
+ const v = /^["\[{]/.test(last.received) ? last.received : JSON.stringify(last.received);
105
+ log.push(` - unexpected value ${v}`);
106
+ }
107
+ out.push('', 'Call log:', ...log.map((l) => (l.startsWith(' ') ? ` ${l}` : ` - ${l}`)), '');
108
+ return { message: out.join('\n'), log };
19
109
  }
20
110
  /**
21
- * Poll `check` until it returns true or the budget elapses. `describe`
22
- * renders the failure message with the last observed state.
111
+ * Poll `sample` until its pass flag differs from `negated`. A strict
112
+ * mode violation, or an engine error about the element's type, fails
113
+ * at once; other errors are retried until the timeout.
23
114
  */
24
- async function poll(budget, negated, check, describe) {
25
- const deadline = Date.now() + budget;
26
- let lastActual = '<no observation>';
27
- let lastError = null;
28
- for (;;) {
115
+ async function poll(subject, locator, spec, negated, timeout, custom, sample) {
116
+ const frame = callerFrame();
117
+ const deadline = Date.now() + timeout;
118
+ let last = null;
119
+ let error = null;
120
+ for (let i = 0;; i++) {
29
121
  try {
30
- const { pass, actual } = await check();
31
- lastActual = actual;
32
- lastError = null;
33
- if (pass !== negated)
122
+ last = await sample();
123
+ error = null;
124
+ if (last.pass !== negated && (last.found || last.missingOk))
34
125
  return;
35
126
  }
36
127
  catch (e) {
37
- lastError = e;
128
+ const msg = e instanceof Error ? e.message : String(e);
129
+ const fatal = e instanceof StrictModeError || /^Error: /.test(msg);
130
+ // "locator.x: Error: ..." and "Error: ..." both print as one "Error: ..." line.
131
+ const bare = msg.replace(/^[\w.]+: (?=Error: )/, '').replace(/\n+$/, '');
132
+ error = /^Error: /.test(bare) ? bare : `Error: ${bare.replace(/^[\w.]+: /, '')}`;
133
+ if (fatal) {
134
+ const { message, log } = render(subject, locator, spec, negated, timeout, last, error, custom);
135
+ throw new ExpectError(message, spec.name, !negated, log, timeout, frame);
136
+ }
38
137
  }
39
138
  if (Date.now() >= deadline)
40
139
  break;
41
- await sleep(POLL_MS);
140
+ await sleep(BACKOFF[Math.min(i, BACKOFF.length - 1)]);
42
141
  }
43
- if (lastError)
44
- throw lastError;
45
- throw new TimeoutError(`${describe(lastActual)} (waited ${budget}ms)`);
142
+ const { message, log } = render(subject, locator, spec, negated, timeout, last, error, custom);
143
+ throw new ExpectError(message, spec.name, !negated, log, timeout, frame);
46
144
  }
145
+ /** jest-style diff of two string lists, as Playwright prints array mismatches. */
146
+ function arrayDiff(expected, received, negated) {
147
+ // Negated, Playwright prints plain Expected/Received lines.
148
+ if (negated)
149
+ return undefined;
150
+ const lines = [];
151
+ let minus = 0;
152
+ let plus = 0;
153
+ const n = Math.max(expected.length, received.length);
154
+ for (let i = 0; i < n; i++) {
155
+ const e = expected[i];
156
+ const r = received[i];
157
+ const es = e === undefined ? undefined : show(e);
158
+ const rs = r === undefined ? undefined : show(r);
159
+ if (e !== undefined && r !== undefined && textMatch(r, e, { normalize: true })) {
160
+ lines.push(` ${rs},`);
161
+ continue;
162
+ }
163
+ if (es !== undefined) {
164
+ lines.push(`- ${es},`);
165
+ minus++;
166
+ }
167
+ if (rs !== undefined) {
168
+ lines.push(`+ ${rs},`);
169
+ plus++;
170
+ }
171
+ }
172
+ return [`- Expected - ${minus}`, `+ Received + ${plus}`, '', ' Array [', ...lines, ' ]'].join('\n');
173
+ }
174
+ /** Options in a matcher header, as Playwright prints them: `{ checked: false }`, timeout left out. */
175
+ function optArg(o) {
176
+ const parts = Object.entries(o ?? {})
177
+ .filter(([k, v]) => k !== 'timeout' && v !== undefined)
178
+ .map(([k, v]) => `${k}: ${typeof v === 'string' ? `'${v}'` : String(v)}`);
179
+ return parts.length ? `{ ${parts.join(', ')} }` : '';
180
+ }
181
+ /** An array matcher's printed result: a diff, or plain lines when negated. */
182
+ function arrayOut(expected, received, negated) {
183
+ const diff = arrayDiff(expected, received, negated);
184
+ return diff === undefined ? { received: JSON.stringify(received) } : { diff };
185
+ }
186
+ const resolvedLog = (n) => [`locator resolved to ${n} element${n === 1 ? '' : 's'}`];
47
187
  export class LocatorAssertions {
48
188
  locator;
49
189
  negated;
50
190
  defaultTimeout;
51
- constructor(locator, negated = false, defaultTimeout = 5_000) {
191
+ custom;
192
+ constructor(locator, negated = false, defaultTimeout = 5_000, custom) {
52
193
  this.locator = locator;
53
194
  this.negated = negated;
54
195
  this.defaultTimeout = defaultTimeout;
196
+ this.custom = custom;
55
197
  }
56
198
  get not() {
57
- return new LocatorAssertions(this.locator, !this.negated, this.defaultTimeout);
199
+ return new LocatorAssertions(this.locator, !this.negated, this.defaultTimeout, this.custom);
58
200
  }
59
- budget(options) {
60
- return options?.timeout ?? this.defaultTimeout;
201
+ lastPreview;
202
+ /** locator.peek, remembering the element for the call log. */
203
+ async peekEl(apiName, op, args) {
204
+ const r = await this.locator.peek(apiName, op, args);
205
+ this.lastPreview = r.preview;
206
+ return r;
61
207
  }
62
- msg(condition, actual) {
63
- const wanted = this.negated ? `not to ${condition}` : `to ${condition}`;
64
- return `expected ${this.locator.toString()} ${wanted}, but ${actual}`;
208
+ /** When the running assertion gives up; locator handlers wait no longer than this. */
209
+ deadline = 0;
210
+ run(spec, options, sample) {
211
+ const timeout = options?.timeout ?? this.defaultTimeout;
212
+ this.deadline = Date.now() + timeout;
213
+ return poll('locator', this.locator.toString(), spec, this.negated, timeout, this.custom, async () => {
214
+ this.lastPreview = undefined;
215
+ const page = this.locator.page();
216
+ if (!(await page.runLocatorHandlers(this.deadline))) {
217
+ return { pass: false, found: true, received: '""', log: [...page.handlerLog] };
218
+ }
219
+ const s = await sample();
220
+ if (!s.log && this.lastPreview)
221
+ s.log = [`locator resolved to ${this.lastPreview}`];
222
+ return s;
223
+ });
65
224
  }
66
- /** At least one visible match. */
67
- async toBeVisible(options) {
68
- await poll(this.budget(options), this.negated, async () => {
69
- const visible = await this.locator.resolveVisible();
70
- return {
71
- pass: visible.length > 0,
72
- actual: visible.length > 0 ? `found ${visible.length} visible` : 'found none visible',
73
- };
74
- }, (actual) => this.msg('be visible', actual));
225
+ /** A boolean element state: pass when `read` returns true. */
226
+ state(name, yes, no, op, want, options, args) {
227
+ const expected = want ? yes : no;
228
+ return this.run({ name, arg: optArg(options), expected }, options, async () => {
229
+ const r = await this.peekEl(`expect.${name}`, op, args);
230
+ if (!r.found)
231
+ return { pass: false, found: false };
232
+ return { pass: r.v === want, found: true, received: r.v ? yes : no };
233
+ });
75
234
  }
76
- /** No visible match. */
77
- async toBeHidden(options) {
78
- await poll(this.budget(options), this.negated, async () => {
79
- const visible = await this.locator.resolveVisible();
80
- return {
81
- pass: visible.length === 0,
82
- actual: visible.length === 0 ? 'found none visible' : `found ${visible.length} visible`,
83
- };
84
- }, (actual) => this.msg('be hidden', actual));
85
- }
86
- /** The element's full text equals the expected string (or matches the RegExp). */
87
- async toHaveText(expected, options) {
88
- await this.textAssertion(expected, false, 'have text', options);
89
- }
90
- /** The element's full text contains the expected substring (or matches the RegExp). */
91
- async toContainText(expected, options) {
92
- await this.textAssertion(expected, true, 'contain text', options);
93
- }
94
- async textAssertion(expected, substring, condition, options) {
95
- await poll(this.budget(options), this.negated, async () => {
96
- const matches = await this.locator.resolveAll();
97
- const node = matches[0];
98
- if (!node)
99
- return { pass: false, actual: 'no matching element' };
100
- const text = await this.locator.textContent({ timeout: 1_000 }).catch(() => node.label);
235
+ async toBeVisible(options = {}) {
236
+ const want = options.visible ?? true;
237
+ await this.run({ name: 'toBeVisible', arg: optArg(options), expected: want ? 'visible' : 'hidden' }, options, async () => {
238
+ const r = await this.peekEl('expect.toBeVisible', 'visible');
239
+ const visible = r.found && r.v === true;
240
+ return { pass: visible === want, found: r.found, missingOk: !want !== this.negated, received: visible ? 'visible' : 'hidden' };
241
+ });
242
+ }
243
+ async toBeHidden(options = {}) {
244
+ await this.run({ name: 'toBeHidden', arg: '', expected: 'hidden' }, options, async () => {
245
+ const r = await this.peekEl('expect.toBeHidden', 'visible');
246
+ const visible = r.found && r.v === true;
247
+ return { pass: !visible, found: r.found, missingOk: !this.negated, received: visible ? 'visible' : 'hidden' };
248
+ });
249
+ }
250
+ async toBeAttached(options = {}) {
251
+ const want = options.attached ?? true;
252
+ await this.run({ name: 'toBeAttached', arg: optArg(options), expected: want ? 'attached' : 'detached' }, options, async () => {
253
+ const list = await this.locator.many('describe');
254
+ const n = list.length;
255
+ const log = n === 1 ? [`locator resolved to ${list[0]}`] : undefined;
256
+ return { pass: n > 0 === want, found: true, received: n > 0 ? 'attached' : 'detached', ...(log ? { log } : {}) };
257
+ });
258
+ }
259
+ async toBeChecked(options = {}) {
260
+ if (options.indeterminate && options.checked !== undefined) {
261
+ throw new Error("Can't assert indeterminate and checked at the same time");
262
+ }
263
+ const want = options.indeterminate ? 'mixed' : (options.checked ?? true);
264
+ const word = (v) => (v === 'mixed' ? 'indeterminate' : v ? 'checked' : 'unchecked');
265
+ await this.run({ name: 'toBeChecked', arg: optArg(options), expected: word(want) }, options, async () => {
266
+ const r = await this.peekEl('expect.toBeChecked', 'checkedMixed');
267
+ if (!r.found || !r.v)
268
+ return { pass: false, found: false };
269
+ const state = want === 'mixed' ? (r.v.m ? 'mixed' : r.v.c) : r.v.c;
270
+ return { pass: state === want, found: true, received: word(state) };
271
+ });
272
+ }
273
+ async toBeDisabled(options = {}) {
274
+ await this.state('toBeDisabled', 'disabled', 'enabled', 'disabled', true, options);
275
+ }
276
+ async toBeEnabled(options = {}) {
277
+ await this.state('toBeEnabled', 'disabled', 'enabled', 'disabled', !(options.enabled ?? true), options);
278
+ }
279
+ async toBeEditable(options = {}) {
280
+ await this.state('toBeEditable', 'editable', 'readOnly', 'editable', options.editable ?? true, options);
281
+ }
282
+ async toBeFocused(options = {}) {
283
+ await this.state('toBeFocused', 'focused', 'inactive', 'focused', true, options);
284
+ }
285
+ async toBeEmpty(options = {}) {
286
+ await this.state('toBeEmpty', 'empty', 'notEmpty', 'empty', true, options);
287
+ }
288
+ async toBeInViewport(options = {}) {
289
+ await this.run({ name: 'toBeInViewport', arg: optArg(options), expected: 'in viewport' }, options, async () => {
290
+ const r = await this.peekEl('expect.toBeInViewport', 'inViewport');
291
+ if (!r.found)
292
+ return { pass: false, found: false };
293
+ const ratio = r.v ?? 0;
294
+ const pass = options.ratio !== undefined ? ratio >= options.ratio && ratio > 0 : ratio > 0;
295
+ return { pass, found: true, received: `viewport ratio ${ratio}` };
296
+ });
297
+ }
298
+ /** The element's text equals the string (whitespace-normalized) or matches the RegExp; an array checks each match. */
299
+ async toHaveText(expected, options = {}) {
300
+ await this.text('toHaveText', expected, false, options);
301
+ }
302
+ /** The element's text contains the string or matches the RegExp; an array checks matches in order. */
303
+ async toContainText(expected, options = {}) {
304
+ await this.text('toContainText', expected, true, options);
305
+ }
306
+ async text(name, expected, substring, options) {
307
+ const op = options.useInnerText ? 'innerText' : 'elText';
308
+ if (Array.isArray(expected)) {
309
+ await this.run({ name, arg: 'expected', expected: JSON.stringify(expected.map(String)) }, options, async () => {
310
+ const texts = await this.locator.many(op === 'elText' ? 'elTexts' : 'innerTexts');
311
+ const ok = (t, e) => textMatch(t, e, { substring, ignoreCase: options.ignoreCase });
312
+ let pass;
313
+ if (substring) {
314
+ let j = 0;
315
+ for (const t of texts)
316
+ if (j < expected.length && ok(t, expected[j]))
317
+ j++;
318
+ pass = j === expected.length;
319
+ }
320
+ else {
321
+ pass = texts.length === expected.length && texts.every((t, i) => ok(t, expected[i]));
322
+ }
323
+ return { pass, found: true, ...arrayOut(expected, texts, this.negated), log: resolvedLog(texts.length) };
324
+ });
325
+ return;
326
+ }
327
+ const labels = expected instanceof RegExp
328
+ ? { expectedLabel: 'Expected pattern', receivedLabel: 'Received string' }
329
+ : substring
330
+ ? { expectedLabel: 'Expected substring', receivedLabel: 'Received string' }
331
+ : {};
332
+ await this.run({ name, arg: 'expected', expected: show(expected), ...labels }, options, async () => {
333
+ const r = await this.peekEl(`expect.${name}`, op);
334
+ if (!r.found)
335
+ return { pass: false, found: false };
336
+ const t = r.v ?? '';
101
337
  return {
102
- pass: textMatches(text, expected, substring),
103
- actual: `text was ${JSON.stringify(normalize(text)).slice(0, 200)}`,
338
+ pass: textMatch(t, expected, { substring, ignoreCase: options.ignoreCase }),
339
+ found: true,
340
+ received: show(expected instanceof RegExp ? t : normalize(t)),
104
341
  };
105
- }, (actual) => this.msg(`${condition} ${String(expected)}`, actual));
106
- }
107
- /** A checked checkbox or radio (vibesurfer 0.2.12+). */
108
- async toBeChecked(options) {
109
- await poll(this.budget(options), this.negated, async () => {
110
- const checked = await this.locator.isChecked({ timeout: 1_000 });
111
- return { pass: checked, actual: checked ? 'it was checked' : 'it was not checked' };
112
- }, (actual) => this.msg('be checked', actual));
113
- }
114
- /** A text field or select whose current value equals the string (or matches the RegExp). */
115
- async toHaveValue(expected, options) {
116
- await poll(this.budget(options), this.negated, async () => {
117
- const value = await this.locator.inputValue({ timeout: 1_000 });
118
- return {
119
- pass: textMatches(value, expected, false),
120
- actual: `value was ${JSON.stringify(value)}`,
342
+ });
343
+ }
344
+ /** The field's current value equals the string (exactly) or matches the RegExp. */
345
+ async toHaveValue(expected, options = {}) {
346
+ await this.run({ name: 'toHaveValue', arg: 'expected', expected: show(expected) }, options, async () => {
347
+ const r = await this.peekEl('expect.toHaveValue', 'value');
348
+ if (!r.found)
349
+ return { pass: false, found: false };
350
+ return { pass: textMatch(r.v ?? '', expected, { normalize: false }), found: true, received: show(r.v) };
351
+ });
352
+ }
353
+ /** A multi-select's selected values. */
354
+ async toHaveValues(expected, options = {}) {
355
+ await this.run({ name: 'toHaveValues', arg: 'expected', expected: JSON.stringify(expected.map(String)) }, options, async () => {
356
+ const r = await this.peekEl('expect.toHaveValues', 'values');
357
+ if (!r.found)
358
+ return { pass: false, found: false };
359
+ const v = r.v ?? [];
360
+ const pass = v.length === expected.length && v.every((x, i) => textMatch(x, expected[i], { normalize: false }));
361
+ return { pass, found: true, ...arrayOut(expected, v, this.negated) };
362
+ });
363
+ }
364
+ /** The attribute is present, and with `value`, equals it (or matches the RegExp). */
365
+ async toHaveAttribute(name, value, options = {}) {
366
+ if (typeof value === 'object' && !(value instanceof RegExp)) {
367
+ options = value;
368
+ value = undefined;
369
+ }
370
+ const want = value;
371
+ const spec = want === undefined
372
+ ? { name: 'toHaveAttribute', arg: 'expected', expected: 'have attribute' }
373
+ : {
374
+ name: 'toHaveAttribute',
375
+ arg: 'expected',
376
+ expected: show(want),
377
+ ...(want instanceof RegExp ? { expectedLabel: 'Expected pattern', receivedLabel: 'Received string' } : {}),
121
378
  };
122
- }, (actual) => this.msg(`have value ${String(expected)}`, actual));
379
+ await this.run(spec, options, async () => {
380
+ const r = await this.peekEl('expect.toHaveAttribute', 'attr', { name });
381
+ if (!r.found)
382
+ return { pass: false, found: false };
383
+ const v = r.v ?? null;
384
+ if (want === undefined)
385
+ return { pass: v !== null, found: true, received: v !== null ? 'have attribute' : 'not have attribute' };
386
+ // null and "" print alike, so say that instead of a confusing "null".
387
+ if (v === null) {
388
+ if (want instanceof RegExp)
389
+ return { pass: false, found: true, received: '""' };
390
+ return { pass: false, found: true, received: want === '' ? 'serializes to the same string' : 'null' };
391
+ }
392
+ return { pass: textMatch(v, want, { normalize: false, ignoreCase: options.ignoreCase }), found: true, received: show(v) };
393
+ });
394
+ }
395
+ /** The class attribute equals the string (whitespace-normalized) or matches the RegExp; an array checks each match. */
396
+ async toHaveClass(expected, options = {}) {
397
+ if (Array.isArray(expected)) {
398
+ await this.run({ name: 'toHaveClass', arg: 'expected', expected: JSON.stringify(expected.map(String)) }, options, async () => {
399
+ const list = await this.locator.evaluateAll((els) => els.map((e) => e.getAttribute('class') ?? ''));
400
+ const pass = list.length === expected.length && list.every((c, i) => textMatch(c, expected[i], {}));
401
+ return { pass, found: true, ...arrayOut(expected, list, this.negated), log: resolvedLog(list.length) };
402
+ });
403
+ return;
404
+ }
405
+ await this.run({ name: 'toHaveClass', arg: 'expected', expected: show(expected), ...(expected instanceof RegExp ? { expectedLabel: 'Expected pattern', receivedLabel: 'Received string' } : {}) }, options, async () => {
406
+ const r = await this.peekEl('expect.toHaveClass', 'attr', { name: 'class' });
407
+ if (!r.found)
408
+ return { pass: false, found: false };
409
+ const v = r.v ?? '';
410
+ return { pass: textMatch(v, expected, {}), found: true, received: show(v) };
411
+ });
412
+ }
413
+ /** Every class in the expected string is present; an array checks each match. */
414
+ toContainClass(expected, options = {}) {
415
+ if (expected instanceof RegExp)
416
+ throw new Error('"expected" argument in toContainClass cannot be a RegExp value');
417
+ if (Array.isArray(expected) && expected.some((e) => e instanceof RegExp)) {
418
+ throw new Error('"expected" argument in toContainClass cannot contain RegExp values');
419
+ }
420
+ return this.containClass(expected, options);
421
+ }
422
+ async containClass(expected, options) {
423
+ const has = (actual, want) => {
424
+ const set = new Set(actual.split(/\s+/).filter(Boolean));
425
+ return want.split(/\s+/).filter(Boolean).every((c) => set.has(c));
426
+ };
427
+ if (Array.isArray(expected)) {
428
+ await this.run({ name: 'toContainClass', arg: 'expected', expected: JSON.stringify(expected) }, options, async () => {
429
+ const list = await this.locator.evaluateAll((els) => els.map((e) => e.getAttribute('class') ?? ''));
430
+ const pass = list.length === expected.length && list.every((c, i) => has(c, expected[i]));
431
+ return { pass, found: true, ...arrayOut(expected, list, this.negated), log: resolvedLog(list.length) };
432
+ });
433
+ return;
434
+ }
435
+ await this.run({ name: 'toContainClass', arg: 'expected', expected: show(expected), expectedLabel: 'Expected', receivedLabel: 'Received' }, options, async () => {
436
+ const r = await this.peekEl('expect.toContainClass', 'attr', { name: 'class' });
437
+ if (!r.found)
438
+ return { pass: false, found: false };
439
+ return { pass: has(r.v ?? '', expected), found: true, received: show(r.v ?? '') };
440
+ });
441
+ }
442
+ async toHaveId(expected, options = {}) {
443
+ await this.run({ name: 'toHaveId', arg: 'expected', expected: show(expected) }, options, async () => {
444
+ const r = await this.peekEl('expect.toHaveId', 'attr', { name: 'id' });
445
+ if (!r.found)
446
+ return { pass: false, found: false };
447
+ return { pass: textMatch(r.v ?? '', expected, { normalize: false }), found: true, received: show(r.v ?? '') };
448
+ });
449
+ }
450
+ async toHaveCSS(name, value, options = {}) {
451
+ await this.run({ name: 'toHaveCSS', arg: 'expected', expected: show(value) }, options, async () => {
452
+ const r = await this.peekEl('expect.toHaveCSS', 'css', { name });
453
+ if (!r.found)
454
+ return { pass: false, found: false };
455
+ return { pass: textMatch(r.v ?? '', value, { normalize: false }), found: true, received: show(r.v) };
456
+ });
457
+ }
458
+ async toHaveJSProperty(name, value, options = {}) {
459
+ await this.run({ name: 'toHaveJSProperty', arg: 'expected', expected: show(value) }, options, async () => {
460
+ const r = await this.peekEl('expect.toHaveJSProperty', 'prop', { name });
461
+ if (!r.found)
462
+ return { pass: false, found: false };
463
+ const pass = isDeepStrictEqual(r.v, value);
464
+ // Objects and arrays fail with a line diff, as in Playwright.
465
+ if (!pass && !this.negated && isStructured(value) && isStructured(r.v)) {
466
+ return { pass, found: true, diff: diffValues(value, r.v) };
467
+ }
468
+ return { pass, found: true, received: show(r.v) };
469
+ });
470
+ }
471
+ async toHaveRole(role, options = {}) {
472
+ await this.run({ name: 'toHaveRole', arg: 'expected', expected: show(role) }, options, async () => {
473
+ const r = await this.peekEl('expect.toHaveRole', 'role');
474
+ if (!r.found)
475
+ return { pass: false, found: false };
476
+ return { pass: r.v === role, found: true, received: show(r.v) };
477
+ });
478
+ }
479
+ async toHaveAccessibleName(name, options = {}) {
480
+ await this.run({ name: 'toHaveAccessibleName', arg: 'expected', expected: show(name) }, options, async () => {
481
+ const r = await this.peekEl('expect.toHaveAccessibleName', 'name');
482
+ if (!r.found)
483
+ return { pass: false, found: false };
484
+ return { pass: textMatch(r.v ?? '', name, { ignoreCase: options.ignoreCase }), found: true, received: show(r.v) };
485
+ });
486
+ }
487
+ async toHaveAccessibleDescription(description, options = {}) {
488
+ await this.run({ name: 'toHaveAccessibleDescription', arg: 'expected', expected: show(description) }, options, async () => {
489
+ const r = await this.peekEl('expect.toHaveAccessibleDescription', 'description');
490
+ if (!r.found)
491
+ return { pass: false, found: false };
492
+ return { pass: textMatch(r.v ?? '', description, { ignoreCase: options.ignoreCase }), found: true, received: show(r.v) };
493
+ });
494
+ }
495
+ async toHaveCount(count, options = {}) {
496
+ await this.run({ name: 'toHaveCount', arg: 'expected', expected: String(count) }, options, async () => {
497
+ const n = await this.locator.count();
498
+ return { pass: n === count, found: true, received: String(n), log: resolvedLog(n) };
499
+ });
123
500
  }
124
501
  /**
125
502
  * The element's accessibility subtree matches a template. See
126
503
  * src/aria.ts for the format; `locator.ariaSnapshot()` prints the
127
504
  * current tree in it, ready to paste and trim.
128
505
  */
129
- async toMatchAriaSnapshot(template, options) {
506
+ async toMatchAriaSnapshot(template, options = {}) {
130
507
  const parsed = parseTemplate(template);
131
- await poll(this.budget(options), this.negated, async () => {
132
- const { snap, refs } = await this.locator.resolveScope();
508
+ await this.run({ name: 'toMatchAriaSnapshot', arg: 'expected', expected: `\n${template.trim()}\n` }, options, async () => {
509
+ const { snap, refs } = await this.locator.resolveScope(1_000);
133
510
  if (refs.length === 0)
134
- return { pass: false, actual: 'no matching element' };
135
- return {
136
- pass: matchesTemplate(snap, refs, parsed),
137
- actual: `the tree was:\n${renderSnapshot(snap, refs)}`,
138
- };
139
- }, (actual) => this.msg(`match the aria snapshot\n${template.trim()}\n`, actual));
511
+ return { pass: false, found: false };
512
+ return { pass: matchesTemplate(snap, refs, parsed), found: true, received: `\n${renderSnapshot(snap, refs)}` };
513
+ });
140
514
  }
141
- /** Exactly `count` matches. */
142
- async toHaveCount(count, options) {
143
- await poll(this.budget(options), this.negated, async () => {
144
- const n = await this.locator.count();
145
- return { pass: n === count, actual: `found ${n}` };
146
- }, (actual) => this.msg(`have count ${count}`, actual));
515
+ /**
516
+ * The element looks like its stored baseline. See src/screenshot.ts
517
+ * for where baselines live and how they are created.
518
+ */
519
+ async toHaveScreenshot(nameOrOptions, options = {}) {
520
+ if (this.negated)
521
+ throw new Error('toHaveScreenshot cannot be negated');
522
+ const name = typeof nameOrOptions === 'string' ? nameOrOptions : undefined;
523
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : options;
524
+ await assertScreenshot(() => this.locator.screenshot({ timeout: 2_000 }), name, opts, opts.timeout ?? this.defaultTimeout, this.locator.toString());
147
525
  }
148
526
  }
527
+ const notAResponse = async () => {
528
+ throw new Error('toBeOK can be only used with APIResponse object');
529
+ };
149
530
  export class PageAssertions {
531
+ /** Only APIResponse has toBeOK; Playwright says so for anything else. */
532
+ toBeOK = notAResponse;
150
533
  page;
151
534
  negated;
152
535
  defaultTimeout;
153
- constructor(page, negated = false, defaultTimeout = 5_000) {
536
+ custom;
537
+ constructor(page, negated = false, defaultTimeout = 5_000, custom) {
154
538
  this.page = page;
155
539
  this.negated = negated;
156
540
  this.defaultTimeout = defaultTimeout;
541
+ this.custom = custom;
157
542
  }
158
543
  get not() {
159
- return new PageAssertions(this.page, !this.negated, this.defaultTimeout);
544
+ return new PageAssertions(this.page, !this.negated, this.defaultTimeout, this.custom);
160
545
  }
161
- /** The page URL equals the string (or matches the RegExp). */
162
- async toHaveURL(expected, options) {
163
- await poll(options?.timeout ?? this.defaultTimeout, this.negated, async () => {
546
+ run(spec, options, sample) {
547
+ return poll('page', null, spec, this.negated, options?.timeout ?? this.defaultTimeout, this.custom, sample);
548
+ }
549
+ /** The page URL equals the string (resolved against baseURL), matches the RegExp, or satisfies the predicate. */
550
+ async toHaveURL(expected, options = {}) {
551
+ const pattern = typeof expected === 'object' && !(expected instanceof RegExp) && typeof expected.test === 'function';
552
+ if (typeof expected !== 'string' && typeof expected !== 'function' && !(expected instanceof RegExp) && !pattern) {
553
+ const not = this.negated ? 'not.' : '';
554
+ throw new ExpectError(`expect(page).${not}toHaveURL(expected) failed\n\nError: expected value must be a string or regular expression\nExpected has type: ${typeof expected}\nExpected has value: ${JSON.stringify(expected)}\n`, 'toHaveURL', !this.negated, [], 0);
555
+ }
556
+ const want = typeof expected === 'string' && this.page.baseURL ? new URL(expected, this.page.baseURL).href : expected;
557
+ const label = typeof want === 'function' ? (this.negated ? 'predicate to fail' : 'predicate to succeed') : pattern ? 'URLPattern' : show(want);
558
+ const spec = { name: 'toHaveURL', arg: 'expected', expected: label };
559
+ await this.run(spec, options, async () => {
164
560
  const url = await this.page.url();
165
- return { pass: textMatches(url, expected, false), actual: `URL was ${JSON.stringify(url)}` };
166
- }, (actual) => `expected page ${this.negated ? 'not ' : ''}to have URL ${String(expected)}, but ${actual}`);
561
+ const pass = typeof want === 'function'
562
+ ? !!(await want(new URL(url)))
563
+ : pattern
564
+ ? want.test(url)
565
+ : textMatch(url, want, { normalize: false, ignoreCase: options.ignoreCase });
566
+ return { pass, found: true, received: show(url) };
567
+ });
568
+ }
569
+ /** The document title equals the string (whitespace-normalized) or matches the RegExp. */
570
+ async toHaveTitle(expected, options = {}) {
571
+ await this.run({ name: 'toHaveTitle', arg: 'expected', expected: show(expected) }, options, async () => {
572
+ const title = await this.page.title();
573
+ return { pass: textMatch(title, expected, {}), found: true, received: show(title) };
574
+ });
167
575
  }
168
576
  /** The whole page's accessibility tree matches a template (see LocatorAssertions.toMatchAriaSnapshot). */
169
- async toMatchAriaSnapshot(template, options) {
577
+ async toMatchAriaSnapshot(template, options = {}) {
170
578
  const parsed = parseTemplate(template);
171
- await poll(options?.timeout ?? this.defaultTimeout, this.negated, async () => {
579
+ await this.run({ name: 'toMatchAriaSnapshot', arg: 'expected', expected: `\n${template.trim()}\n` }, options, async () => {
172
580
  const snap = await this.page.view();
173
- return {
174
- pass: matchesTemplate(snap, snap.roots, parsed),
175
- actual: `the tree was:\n${renderSnapshot(snap, snap.roots)}`,
176
- };
177
- }, (actual) => `expected page ${this.negated ? 'not ' : ''}to match the aria snapshot\n${template.trim()}\nbut ${actual}`);
581
+ return { pass: matchesTemplate(snap, snap.roots, parsed), found: true, received: `\n${renderSnapshot(snap, snap.roots)}` };
582
+ });
178
583
  }
179
- /** The document title equals the string (or matches the RegExp). */
180
- async toHaveTitle(expected, options) {
181
- await poll(options?.timeout ?? this.defaultTimeout, this.negated, async () => {
182
- const title = await this.page.title();
183
- return {
184
- pass: textMatches(title, expected, false),
185
- actual: `title was ${JSON.stringify(title)}`,
186
- };
187
- }, (actual) => `expected page ${this.negated ? 'not ' : ''}to have title ${String(expected)}, but ${actual}`);
584
+ /** The page looks like its stored baseline (see LocatorAssertions.toHaveScreenshot). */
585
+ async toHaveScreenshot(nameOrOptions, options = {}) {
586
+ if (this.negated)
587
+ throw new Error('toHaveScreenshot cannot be negated');
588
+ const name = typeof nameOrOptions === 'string' ? nameOrOptions : undefined;
589
+ const opts = typeof nameOrOptions === 'object' ? nameOrOptions : options;
590
+ await assertScreenshot(() => this.page.screenshot(opts.fullPage ? { fullPage: true } : {}), name, opts, opts.timeout ?? this.defaultTimeout, 'page');
188
591
  }
189
592
  }
190
- export function expect(target) {
191
- if (target instanceof Locator) {
192
- return new LocatorAssertions(target, false, target.expectTimeout);
593
+ export class ResponseAssertions {
594
+ response;
595
+ negated;
596
+ constructor(response, negated = false) {
597
+ this.response = response;
598
+ this.negated = negated;
599
+ }
600
+ get not() {
601
+ return new ResponseAssertions(this.response, !this.negated);
193
602
  }
194
- return new PageAssertions(target, false, target.timeouts.expect);
603
+ /** Status in the 2xx range. */
604
+ async toBeOK() {
605
+ const ok = this.response.ok();
606
+ if (ok !== this.negated)
607
+ return;
608
+ const not = this.negated ? 'not.' : '';
609
+ let text = '';
610
+ if (!ok) {
611
+ const type = this.response.headers()['content-type'] ?? '';
612
+ if (/text|json|xml|javascript/.test(type))
613
+ text = await this.response.text().catch(() => '');
614
+ }
615
+ const lines = [
616
+ `expect(response).${not}toBeOK() failed`,
617
+ '',
618
+ `→ GET ${this.response.url()}`,
619
+ `← ${this.response.status()} ${this.response.statusText()}`,
620
+ ];
621
+ if (text)
622
+ lines.push('', `Response text:\n${text.slice(0, 1000)}`);
623
+ throw new ExpectError(lines.join('\n'), 'toBeOK', ok, [], 0);
624
+ }
625
+ }
626
+ /** Record a soft failure on the running test, or throw when there is none. */
627
+ function softly(target) {
628
+ return new Proxy(target, {
629
+ get(obj, prop, recv) {
630
+ const v = Reflect.get(obj, prop, recv);
631
+ if (prop === 'not')
632
+ return softly(v);
633
+ if (typeof v !== 'function')
634
+ return v;
635
+ return (...args) => {
636
+ const record = (e) => {
637
+ const info = currentTestInfo();
638
+ if (!info)
639
+ throw e;
640
+ info.softErrors.push(e);
641
+ };
642
+ try {
643
+ const r = v.apply(obj, args);
644
+ return r instanceof Promise ? r.catch(record) : r;
645
+ }
646
+ catch (e) {
647
+ record(e);
648
+ return undefined;
649
+ }
650
+ };
651
+ },
652
+ });
653
+ }
654
+ /** Web-first assertions that also answer the generic matchers (toBe, toEqual, ...) for the same target. */
655
+ function withValueMatchers(a, values) {
656
+ return new Proxy(a, {
657
+ get(obj, prop, recv) {
658
+ if (prop === 'not') {
659
+ return withValueMatchers(Reflect.get(obj, prop, recv), values.not);
660
+ }
661
+ if (prop in obj)
662
+ return Reflect.get(obj, prop, recv);
663
+ const v = Reflect.get(values, prop);
664
+ return typeof v === 'function' ? v.bind(values) : v;
665
+ },
666
+ });
667
+ }
668
+ function makeExpect(config) {
669
+ const fn = ((target, message) => {
670
+ const custom = (typeof message === 'string' ? message : message?.message) ?? config.message;
671
+ let a;
672
+ if (target instanceof Locator) {
673
+ a = new LocatorAssertions(target, false, config.timeout ?? target.expectTimeout, custom);
674
+ }
675
+ else if (target instanceof Page) {
676
+ a = new PageAssertions(target, false, config.timeout ?? target.timeouts.expect, custom);
677
+ }
678
+ else if (target instanceof APIResponse) {
679
+ a = new ResponseAssertions(target);
680
+ }
681
+ else {
682
+ a = new ValueAssertions(target);
683
+ }
684
+ if (!(a instanceof ValueAssertions))
685
+ a = withValueMatchers(a, new ValueAssertions(target));
686
+ return config.soft ? softly(a) : a;
687
+ });
688
+ fn.poll = (pollFn, options = {}) => pollAssertions(pollFn, options.timeout ?? config.timeout ?? 5_000, options.intervals ?? [100, 250, 500, 1000]);
689
+ Object.defineProperty(fn, 'soft', { get: () => makeExpect({ ...config, soft: true }) });
690
+ fn.configure = (more) => makeExpect({ ...config, ...more });
691
+ fn.any = asymmetric.any;
692
+ fn.anything = asymmetric.anything;
693
+ fn.stringContaining = asymmetric.stringContaining;
694
+ fn.stringMatching = asymmetric.stringMatching;
695
+ fn.objectContaining = asymmetric.objectContaining;
696
+ fn.arrayContaining = asymmetric.arrayContaining;
697
+ return fn;
195
698
  }
699
+ export const expect = makeExpect({});
196
700
  //# sourceMappingURL=expect.js.map