nativeproof 0.5.0 → 0.6.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.
package/CHANGELOG.md CHANGED
@@ -4,6 +4,34 @@ All notable changes to NativeProof are documented here. The format follows
4
4
  [Keep a Changelog](https://keepachangelog.com/) and the project adheres to
5
5
  [Semantic Versioning](https://semver.org/).
6
6
 
7
+ ## 0.6.0
8
+
9
+ Playwright-parity additions to locators, assertions, fixtures, and evidence.
10
+
11
+ **Added**
12
+
13
+ - **Checkbox/switch state** — `Locator.isChecked()`, `Locator.check()` / `uncheck()` (tap to the
14
+ desired state, a no-op if already there), and auto-waiting `expect(locator).toBeChecked()` (+ `.not`),
15
+ reading `checked="true"` on the matched node.
16
+ - **Multi-match locators** — `Locator.nth(i)` / `first()` / `last()` (negative `i` counts from the end),
17
+ `Locator.count()`, and auto-waiting `expect(locator).toHaveCount(n)`. An unindexed locator still
18
+ resolves to the first match. New `nodesForAttribute` source helper backs it.
19
+ - **Scenario `beforeEach` / `afterEach`** — `test.beforeEach(fn)` / `test.afterEach(fn)` (and the
20
+ `describeScenario` registrar's `.beforeEach` / `.afterEach`) register per-behaviour hooks that
21
+ receive the provisioned fixture context — a repeatable reset between behaviours without leaving the
22
+ harness. `BddHooks` gained optional `beforeEach` / `afterEach` (present on Mocha and node:test).
23
+ - **`onFailure` evidence hook** — `ScenarioFixture.onFailure` and `defineApp({ onFailure })` run when a
24
+ behaviour throws, before the failure propagates, so on-failure evidence (e.g. `captureState(...)`)
25
+ lives in one place instead of every behaviour. The hook receives the context + `{ title, error }`;
26
+ its own errors are swallowed (logged) so they never mask the real failure.
27
+ - **`by.*` and every `page().getBy*` accept a `RegExp`** as well as a string —
28
+ `getByText(/Save( draft)?/)`, `getByLabel(/^Remove /)`, `getByRole("checkbox", { name: /terms/i })`.
29
+ A string matches the element's value exactly; a RegExp is tested against the element's **decoded**
30
+ value, so a human pattern matches the entity-escaped source and tolerant labels
31
+ (`/complete(d)? phrases/`) no longer need source-scraping. Matching, `bounds`, `textContent`,
32
+ `tap`/`fill`, and `expect(locator)` all honour it. New `nodeForAttribute` / `attributeMatches`
33
+ source helpers back it (`boundsForAttribute` now takes `string | RegExp`).
34
+
7
35
  ## 0.5.0
8
36
 
9
37
  Two additive, backward-compatible seams so an app can drive more of its lifecycle and
package/README.md CHANGED
@@ -60,7 +60,8 @@ nativeproof --platform android
60
60
  - **Locators** — `by.text/testId/label/desc/id` and `page(driver).getByText/getByTestId/
61
61
  getByLabel/getById/getByRole`, each mapped to the right native attribute per platform (so you
62
62
  never guess `content-desc` vs `accessibilityIdentifier`), with built-in auto-waiting and
63
- `tap()` / `fill()` for interaction.
63
+ `tap()` / `fill()` for interaction. Each takes a string (exact) or a **`RegExp`**
64
+ (`getByText(/Save( draft)?/)`), tested against the element's decoded value.
64
65
  - **Auto-waiting `expect`** — `expect(locator).toBeVisible()/toShow()/toHaveText()` and
65
66
  `.not`, each polling until the condition holds (default 10s); plus synchronous `expect(value)`
66
67
  matchers (`toBe`/`toEqual`/`toContain`/…) so non-UI checks need no second assertion library.
package/dist/app.d.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  import type { Driver } from "./driver.js";
2
- import type { ScenarioFixture } from "./fixtures.js";
2
+ import type { FailureInfo, ScenarioFixture } from "./fixtures.js";
3
3
  import type { MockBackend } from "./mock.js";
4
4
  /**
5
5
  * `defineApp` — the single seam script.
@@ -44,6 +44,12 @@ export interface AppDefinition<S extends ScreenFactories> {
44
44
  * even if this throws.
45
45
  */
46
46
  teardown?: (context: SessionContext<S>) => Promise<void> | void;
47
+ /**
48
+ * Invoked when a behaviour throws, before the failure propagates — wire on-failure
49
+ * evidence here (e.g. `captureState(...)`) so capture lives in one place, not in every
50
+ * behaviour. Its own errors are swallowed so they never mask the real failure.
51
+ */
52
+ onFailure?: (context: SessionContext<S>, info: FailureInfo) => Promise<void> | void;
47
53
  }
48
54
  /** The fixture context a session injects: the device handles plus each app screen. */
49
55
  export type SessionContext<S extends ScreenFactories> = DeviceContext & {
package/dist/app.js CHANGED
@@ -34,6 +34,7 @@ export function defineApp(definition) {
34
34
  await context.mock.stop();
35
35
  }
36
36
  },
37
+ ...(definition.onFailure ? { onFailure: definition.onFailure } : {}),
37
38
  };
38
39
  },
39
40
  };
package/dist/expect.d.ts CHANGED
@@ -14,6 +14,10 @@ export interface LocatorAssertions {
14
14
  toShow(text: string | RegExp, options?: WaitOptions): Promise<void>;
15
15
  /** The matched node's own text equals/contains/matches `text`. */
16
16
  toHaveText(text: string | RegExp, options?: WaitOptions): Promise<void>;
17
+ /** The matched checkbox/switch is checked (`checked="true"`). */
18
+ toBeChecked(options?: WaitOptions): Promise<void>;
19
+ /** Exactly `count` elements match the selector. */
20
+ toHaveCount(count: number, options?: WaitOptions): Promise<void>;
17
21
  }
18
22
  export interface MockAssertions {
19
23
  readonly not: MockAssertions;
package/dist/expect.js CHANGED
@@ -25,6 +25,12 @@ class LocatorExpectation {
25
25
  return typeof text === "string" ? content.includes(text) : text.test(content);
26
26
  }, `have text ${JSON.stringify(String(text))}`, options);
27
27
  }
28
+ toBeChecked(options = {}) {
29
+ return this.check(() => this.locator.isChecked(), "be checked", options);
30
+ }
31
+ toHaveCount(count, options = {}) {
32
+ return this.check(async () => (await this.locator.count()) === count, `have count ${count}`, options);
33
+ }
28
34
  async check(predicate, description, options) {
29
35
  const want = !this.negated;
30
36
  const opts = { ...options, sleep: (ms) => this.locator.driver.pause(ms) };
@@ -36,13 +36,32 @@ export interface ScenarioFixture<Ctx> {
36
36
  * produced and must be safe to call in that state.
37
37
  */
38
38
  teardown(context: Ctx | undefined): Promise<void>;
39
+ /**
40
+ * Invoked when a behaviour throws, before the failure propagates — the seam for
41
+ * on-failure evidence (e.g. `captureState(...)`), so capture lives here instead of in
42
+ * every behaviour. Receives the provisioned context and the failing behaviour's title +
43
+ * error. Its own errors are swallowed (logged) so they never mask the real failure.
44
+ */
45
+ onFailure?(context: Ctx, info: FailureInfo): void | Promise<void>;
46
+ }
47
+ /** The failing behaviour's title and the error it threw. */
48
+ export interface FailureInfo {
49
+ title: string;
50
+ error: unknown;
39
51
  }
40
52
  /**
41
53
  * Registers one behaviour. The provisioned context is injected, so the body is pure
42
54
  * behaviour — no `before`/`after`, no threading a backend handle through assertions.
43
55
  * Read it Playwright-style: destructure the fixtures the behaviour needs.
44
56
  */
45
- export type BehaviourRegistrar<Ctx> = (title: string, body: (context: Ctx) => void | Promise<void>) => void;
57
+ export interface BehaviourRegistrar<Ctx> {
58
+ /** Register one behaviour; the provisioned context is injected into its body. */
59
+ (title: string, body: (context: Ctx) => void | Promise<void>): void;
60
+ /** Run before each behaviour in the scenario, with the provisioned context. */
61
+ beforeEach(body: (context: Ctx) => void | Promise<void>): void;
62
+ /** Run after each behaviour in the scenario, with the provisioned context. */
63
+ afterEach(body: (context: Ctx) => void | Promise<void>): void;
64
+ }
46
65
  /**
47
66
  * Define a behaviour scenario: a Mocha `describe` whose fixture context is
48
67
  * provisioned once, injected into every behaviour, and torn down once.
package/dist/fixtures.js CHANGED
@@ -31,7 +31,8 @@ import { runner } from "./runner.js";
31
31
  * });
32
32
  */
33
33
  export function describeScenario(title, fixture, define) {
34
- const { describe, before, after, it } = runner();
34
+ const hooks = runner();
35
+ const { describe, before, after, it } = hooks;
35
36
  describe(title, () => {
36
37
  let context;
37
38
  before(async () => {
@@ -40,14 +41,41 @@ export function describeScenario(title, fixture, define) {
40
41
  after(async () => {
41
42
  await fixture.teardown(context);
42
43
  });
43
- const test = (behaviourTitle, body) => {
44
+ const requireContext = () => {
45
+ if (context === undefined) {
46
+ throw new Error(`Scenario "${title}" ran a behaviour before its fixture context was provisioned`);
47
+ }
48
+ return context;
49
+ };
50
+ const registerHook = (hook, name, body) => {
51
+ if (!hook) {
52
+ throw new Error(`The active runner has no ${name} hook; scenario ${name} is unavailable`);
53
+ }
54
+ hook(async () => {
55
+ await body(requireContext());
56
+ });
57
+ };
58
+ const test = ((behaviourTitle, body) => {
44
59
  it(behaviourTitle, async () => {
45
- if (context === undefined) {
46
- throw new Error(`Scenario "${title}" ran a behaviour before its fixture context was provisioned`);
60
+ const context = requireContext();
61
+ try {
62
+ await body(context);
63
+ }
64
+ catch (error) {
65
+ if (fixture.onFailure) {
66
+ try {
67
+ await fixture.onFailure(context, { title: behaviourTitle, error });
68
+ }
69
+ catch (hookError) {
70
+ console.warn(`[nativeproof] onFailure hook threw (ignored): ${hookError}`);
71
+ }
72
+ }
73
+ throw error;
47
74
  }
48
- await body(context);
49
75
  });
50
- };
76
+ });
77
+ test.beforeEach = (body) => registerHook(hooks.beforeEach, "beforeEach", body);
78
+ test.afterEach = (body) => registerHook(hooks.afterEach, "afterEach", body);
51
79
  define(test);
52
80
  });
53
81
  }
package/dist/harness.d.ts CHANGED
@@ -24,6 +24,10 @@ export interface HarnessTest<S extends ScreenFactories> {
24
24
  describe(title: string, body: () => void): void;
25
25
  /** Open a scenario block for a specific role (e.g. "member" / "guest"). */
26
26
  describe(title: string, role: string, body: () => void): void;
27
+ /** Run before each behaviour in the open scenario, with the session context injected. */
28
+ beforeEach(body: (context: SessionContext<S>) => void | Promise<void>): void;
29
+ /** Run after each behaviour in the open scenario, with the session context injected. */
30
+ afterEach(body: (context: SessionContext<S>) => void | Promise<void>): void;
27
31
  }
28
32
  export interface Harness<S extends ScreenFactories> {
29
33
  test: HarnessTest<S>;
package/dist/harness.js CHANGED
@@ -25,5 +25,13 @@ export function createHarness(app) {
25
25
  }
26
26
  });
27
27
  });
28
+ const requireActive = (hook) => {
29
+ if (!active) {
30
+ throw new Error(`test.${hook}(...) must be called inside test.describe(...)`);
31
+ }
32
+ return active;
33
+ };
34
+ test.beforeEach = (body) => requireActive("beforeEach").beforeEach(body);
35
+ test.afterEach = (body) => requireActive("afterEach").afterEach(body);
28
36
  return { test, expect };
29
37
  }
package/dist/locator.d.ts CHANGED
@@ -11,34 +11,35 @@ import { type Bounds } from "./source.js";
11
11
  /** A cross-platform element selector. */
12
12
  export type Selector = {
13
13
  readonly by: "text";
14
- readonly value: string;
14
+ readonly value: string | RegExp;
15
15
  } | {
16
16
  readonly by: "desc";
17
- readonly value: string;
17
+ readonly value: string | RegExp;
18
18
  } | {
19
19
  readonly by: "id";
20
- readonly value: string;
20
+ readonly value: string | RegExp;
21
21
  } | {
22
22
  readonly by: "testId";
23
- readonly value: string;
23
+ readonly value: string | RegExp;
24
24
  } | {
25
25
  readonly by: "label";
26
- readonly value: string;
26
+ readonly value: string | RegExp;
27
27
  };
28
28
  /**
29
29
  * Build selectors Playwright-style. The cross-platform attribute each maps to is resolved
30
30
  * per platform (see {@link attributeFor}), so you never have to know whether it's a
31
31
  * `content-desc` or a `name`: `by.text("Submit")`, `by.testId("login-button")`,
32
- * `by.label("Sign out")`, `by.id("message-list")`.
32
+ * `by.label("Sign out")`, `by.id("message-list")`. Each accepts a string (exact match) or
33
+ * a RegExp (`by.text(/Save( draft)?/)`), tested against the element's decoded value.
33
34
  */
34
35
  export declare const by: {
35
- readonly text: (value: string) => Selector;
36
- readonly desc: (value: string) => Selector;
37
- readonly id: (value: string) => Selector;
36
+ readonly text: (value: string | RegExp) => Selector;
37
+ readonly desc: (value: string | RegExp) => Selector;
38
+ readonly id: (value: string | RegExp) => Selector;
38
39
  /** The app's test id (Android `resource-id` / Compose testTag, iOS accessibilityIdentifier). */
39
- readonly testId: (value: string) => Selector;
40
+ readonly testId: (value: string | RegExp) => Selector;
40
41
  /** The accessibility label (Android `content-desc`, iOS `label`). */
41
- readonly label: (value: string) => Selector;
42
+ readonly label: (value: string | RegExp) => Selector;
42
43
  };
43
44
  export declare function describeSelector(selector: Selector): string;
44
45
  export interface WaitOptions {
@@ -66,9 +67,24 @@ export declare class Locator {
66
67
  readonly driver: Driver;
67
68
  readonly selector: Selector;
68
69
  private readonly options;
69
- constructor(driver: Driver, selector: Selector, options?: WaitOptions);
70
+ /** When set, the locator resolves to the nth match (negative counts from the end). */
71
+ private readonly index?;
72
+ constructor(driver: Driver, selector: Selector, options?: WaitOptions,
73
+ /** When set, the locator resolves to the nth match (negative counts from the end). */
74
+ index?: number | undefined);
70
75
  private attribute;
71
- private presencePattern;
76
+ /** All node tags this selector matches in the current source, in document order. */
77
+ private matchedNodes;
78
+ /** The single node this locator resolves to (the nth match, or the first when unindexed). */
79
+ private pick;
80
+ /** A locator scoped to the nth match (0-based; negative counts from the end). */
81
+ nth(index: number): Locator;
82
+ /** A locator scoped to the first match. */
83
+ first(): Locator;
84
+ /** A locator scoped to the last match. */
85
+ last(): Locator;
86
+ /** How many elements currently match the selector. */
87
+ count(): Promise<number>;
72
88
  /** True if the selector matches a node in the current source. */
73
89
  isVisible(): Promise<boolean>;
74
90
  /** Bounds of the matched node in the current source, or null if absent. */
@@ -87,6 +103,13 @@ export declare class Locator {
87
103
  * field — it does not clear existing content first.
88
104
  */
89
105
  fill(text: string, options?: WaitOptions): Promise<void>;
106
+ /** True if the matched node is a checked checkbox/switch (`checked="true"`). */
107
+ isChecked(): Promise<boolean>;
108
+ /** Tap to bring a checkbox/switch to checked; a no-op if it already is. */
109
+ check(options?: WaitOptions): Promise<void>;
110
+ /** Tap to bring a checkbox/switch to unchecked; a no-op if it already is. */
111
+ uncheck(options?: WaitOptions): Promise<void>;
112
+ private setChecked;
90
113
  }
91
114
  /** Convenience factory: `locator(driver, by.text("Submit"))`. */
92
115
  export declare function locator(driver: Driver, selector: Selector, options?: WaitOptions): Locator;
package/dist/locator.js CHANGED
@@ -1,9 +1,10 @@
1
- import { boundsForAttribute, decodeXmlEntities, encodeXmlEntities, escapeRegExp, smallestClickableAncestorBounds, } from "./source.js";
1
+ import { decodeXmlEntities, encodeXmlEntities, escapeRegExp, nodesForAttribute, parseBounds, smallestClickableAncestorBounds, } from "./source.js";
2
2
  /**
3
3
  * Build selectors Playwright-style. The cross-platform attribute each maps to is resolved
4
4
  * per platform (see {@link attributeFor}), so you never have to know whether it's a
5
5
  * `content-desc` or a `name`: `by.text("Submit")`, `by.testId("login-button")`,
6
- * `by.label("Sign out")`, `by.id("message-list")`.
6
+ * `by.label("Sign out")`, `by.id("message-list")`. Each accepts a string (exact match) or
7
+ * a RegExp (`by.text(/Save( draft)?/)`), tested against the element's decoded value.
7
8
  */
8
9
  export const by = {
9
10
  text: (value) => ({ by: "text", value }),
@@ -15,7 +16,8 @@ export const by = {
15
16
  label: (value) => ({ by: "label", value }),
16
17
  };
17
18
  export function describeSelector(selector) {
18
- return `by.${selector.by}(${JSON.stringify(selector.value)})`;
19
+ const value = selector.value instanceof RegExp ? String(selector.value) : JSON.stringify(selector.value);
20
+ return `by.${selector.by}(${value})`;
19
21
  }
20
22
  /**
21
23
  * The page-source attribute a selector resolves to on each platform. `text` is an
@@ -58,30 +60,57 @@ export class Locator {
58
60
  driver;
59
61
  selector;
60
62
  options;
61
- constructor(driver, selector, options = {}) {
63
+ index;
64
+ constructor(driver, selector, options = {},
65
+ /** When set, the locator resolves to the nth match (negative counts from the end). */
66
+ index) {
62
67
  this.driver = driver;
63
68
  this.selector = selector;
64
69
  this.options = options;
70
+ this.index = index;
65
71
  }
66
72
  attribute() {
67
73
  return attributeFor(this.selector, this.driver.platform);
68
74
  }
69
- presencePattern() {
70
- return new RegExp(`${this.attribute()}="${escapeRegExp(encodeXmlEntities(this.selector.value))}"`);
75
+ /** All node tags this selector matches in the current source, in document order. */
76
+ async matchedNodes() {
77
+ return nodesForAttribute(await this.driver.source(), this.attribute(), this.selector.value);
78
+ }
79
+ /** The single node this locator resolves to (the nth match, or the first when unindexed). */
80
+ pick(nodes) {
81
+ if (this.index === undefined)
82
+ return nodes[0] ?? null;
83
+ const at = this.index < 0 ? nodes.length + this.index : this.index;
84
+ return nodes[at] ?? null;
85
+ }
86
+ /** A locator scoped to the nth match (0-based; negative counts from the end). */
87
+ nth(index) {
88
+ return new Locator(this.driver, this.selector, this.options, index);
89
+ }
90
+ /** A locator scoped to the first match. */
91
+ first() {
92
+ return this.nth(0);
93
+ }
94
+ /** A locator scoped to the last match. */
95
+ last() {
96
+ return this.nth(-1);
97
+ }
98
+ /** How many elements currently match the selector. */
99
+ async count() {
100
+ return (await this.matchedNodes()).length;
71
101
  }
72
102
  /** True if the selector matches a node in the current source. */
73
103
  async isVisible() {
74
- return this.presencePattern().test(await this.driver.source());
104
+ return this.pick(await this.matchedNodes()) !== null;
75
105
  }
76
106
  /** Bounds of the matched node in the current source, or null if absent. */
77
107
  async bounds() {
78
- return boundsForAttribute(await this.driver.source(), this.attribute(), this.selector.value);
108
+ const node = this.pick(await this.matchedNodes());
109
+ return node ? parseBounds(/bounds="([^"]+)"/.exec(node)?.[1]) : null;
79
110
  }
80
111
  /** The matched node's own visible text, or null if the node is absent. */
81
112
  async textContent() {
82
- const source = await this.driver.source();
83
- const selectorPattern = escapeRegExp(encodeXmlEntities(this.selector.value));
84
- const node = new RegExp(`<[^>]*${this.attribute()}="${selectorPattern}"[^>]*>`).exec(source)?.[0];
113
+ const node = this.pick(await this.matchedNodes());
85
114
  if (!node)
86
115
  return null;
87
116
  // A visible label can live in either of two attributes per platform, in the same
@@ -98,7 +127,7 @@ export class Locator {
98
127
  /** True if the selector is present AND `text` appears in the source. */
99
128
  async shows(text) {
100
129
  const source = await this.driver.source();
101
- if (!this.presencePattern().test(source))
130
+ if (this.pick(nodesForAttribute(source, this.attribute(), this.selector.value)) === null)
102
131
  return false;
103
132
  const pattern = typeof text === "string" ? new RegExp(escapeRegExp(encodeXmlEntities(text))) : text;
104
133
  return pattern.test(source);
@@ -135,6 +164,30 @@ export class Locator {
135
164
  await this.tap(options);
136
165
  await this.driver.typeText(text);
137
166
  }
167
+ /** True if the matched node is a checked checkbox/switch (`checked="true"`). */
168
+ async isChecked() {
169
+ const node = this.pick(await this.matchedNodes());
170
+ return node !== null && /\bchecked="true"/.test(node);
171
+ }
172
+ /** Tap to bring a checkbox/switch to checked; a no-op if it already is. */
173
+ async check(options = {}) {
174
+ await this.setChecked(true, options);
175
+ }
176
+ /** Tap to bring a checkbox/switch to unchecked; a no-op if it already is. */
177
+ async uncheck(options = {}) {
178
+ await this.setChecked(false, options);
179
+ }
180
+ async setChecked(desired, options) {
181
+ if ((await this.isChecked()) === desired)
182
+ return;
183
+ await this.tap(options);
184
+ const opts = { ...this.options, ...options, sleep: (ms) => this.driver.pause(ms) };
185
+ const settled = await waitUntil(() => this.isChecked(), (value) => value === desired, opts);
186
+ if (settled !== desired) {
187
+ const state = desired ? "checked" : "unchecked";
188
+ throw new Error(`${describeSelector(this.selector)} did not become ${state} within ${opts.timeout ?? DEFAULTS.timeout}ms`);
189
+ }
190
+ }
138
191
  }
139
192
  /** Convenience factory: `locator(driver, by.text("Submit"))`. */
140
193
  export function locator(driver, selector, options = {}) {
package/dist/page.d.ts CHANGED
@@ -3,22 +3,23 @@ import { type Locator, type Selector, type WaitOptions } from "./locator.js";
3
3
  /**
4
4
  * Playwright-style `getBy*` ergonomics over a {@link Driver}, so selectors are
5
5
  * discovered, not inferred. `page(driver).getByText("Submit")` returns a {@link Locator}
6
- * and you never spell out which native attribute backs it.
6
+ * and you never spell out which native attribute backs it. Every `getBy*` takes a string
7
+ * (exact match) or a RegExp (`getByText(/Save( draft)?/)`).
7
8
  */
8
9
  export interface Page {
9
10
  /** Escape hatch: a locator from a raw selector. */
10
11
  locator(selector: Selector, options?: WaitOptions): Locator;
11
- getByText(text: string, options?: WaitOptions): Locator;
12
- getByTestId(testId: string, options?: WaitOptions): Locator;
13
- getByLabel(label: string, options?: WaitOptions): Locator;
14
- getById(id: string, options?: WaitOptions): Locator;
12
+ getByText(text: string | RegExp, options?: WaitOptions): Locator;
13
+ getByTestId(testId: string | RegExp, options?: WaitOptions): Locator;
14
+ getByLabel(label: string | RegExp, options?: WaitOptions): Locator;
15
+ getById(id: string | RegExp, options?: WaitOptions): Locator;
15
16
  /**
16
17
  * Match by accessible name. Native accessibility trees don't expose web-style roles
17
18
  * reliably, so `role` is advisory and the dependable signal is the name (the element's
18
- * accessibility label). Pass `{ name }`.
19
+ * accessibility label). Pass `{ name }` — a string for exact match, or a RegExp.
19
20
  */
20
21
  getByRole(role: string, options: {
21
- name: string;
22
+ name: string | RegExp;
22
23
  } & WaitOptions): Locator;
23
24
  }
24
25
  export declare function page(driver: Driver): Page;
package/dist/runner.d.ts CHANGED
@@ -1,16 +1,10 @@
1
- /**
2
- * BDD-runner seam.
3
- *
4
- * The fixtures and the `test` facade register suites through whatever BDD runner
5
- * hosts them: Mocha by default (its `describe` / `before` / `after` / `it` globals, as
6
- * WebdriverIO uses), or any other runner wired explicitly with {@link useRunner}
7
- * (for example node:test). This keeps the framework from hard-coding a single runner,
8
- * the way Playwright owns its own.
9
- */
10
1
  export interface BddHooks {
11
2
  describe(title: string, fn: () => void): void;
12
3
  before(fn: () => void | Promise<void>): void;
13
4
  after(fn: () => void | Promise<void>): void;
5
+ /** Optional per-behaviour hooks; present on Mocha and node:test. */
6
+ beforeEach?(fn: () => void | Promise<void>): void;
7
+ afterEach?(fn: () => void | Promise<void>): void;
14
8
  it(title: string, fn: () => void | Promise<void>): void;
15
9
  }
16
10
  /** Wire an explicit BDD runner (e.g. node:test's hooks). Overrides global detection. */
package/dist/runner.js CHANGED
@@ -5,7 +5,7 @@ export function useRunner(hooks) {
5
5
  }
6
6
  function fromGlobals() {
7
7
  const globals = globalThis;
8
- const { describe, before, after, it } = globals;
8
+ const { describe, before, after, beforeEach, afterEach, it } = globals;
9
9
  if (typeof describe === "function" &&
10
10
  typeof before === "function" &&
11
11
  typeof after === "function" &&
@@ -15,6 +15,8 @@ function fromGlobals() {
15
15
  before: before,
16
16
  after: after,
17
17
  it: it,
18
+ ...(typeof beforeEach === "function" ? { beforeEach: beforeEach } : {}),
19
+ ...(typeof afterEach === "function" ? { afterEach: afterEach } : {}),
18
20
  };
19
21
  }
20
22
  return null;
package/dist/source.d.ts CHANGED
@@ -31,12 +31,23 @@ export declare function decodeXmlEntities(value: string): string;
31
31
  * (`text="Terms &amp; Conditions"`). `&` is encoded first to avoid double-encoding.
32
32
  */
33
33
  export declare function encodeXmlEntities(value: string): string;
34
+ /**
35
+ * The first element tag exposing `attribute` with a value matching `value`. `attribute`
36
+ * may be a regex alternation (e.g. `"(?:text|content-desc)"`). A string matches the
37
+ * entity-escaped source exactly; a RegExp is tested against each candidate's DECODED
38
+ * value, so `by.text(/Save( draft)?/)` matches whether the source XML-escaped it or not.
39
+ */
40
+ export declare function nodeForAttribute(source: string, attribute: string, value: string | RegExp): string | null;
41
+ /** Every element tag exposing `attribute` with a value matching `value`, in document order. */
42
+ export declare function nodesForAttribute(source: string, attribute: string, value: string | RegExp): string[];
43
+ /** True if any element exposes `attribute` with a value matching `value` (string exact or RegExp). */
44
+ export declare function attributeMatches(source: string, attribute: string, value: string | RegExp): boolean;
34
45
  /**
35
46
  * Bounds of the first element carrying the given attribute match. The element tag is
36
47
  * matched first, then `bounds` is extracted from within it regardless of attribute order —
37
48
  * so a source that emits `bounds` before the selector attribute still resolves.
38
49
  */
39
- export declare function boundsForAttribute(source: string, attribute: string, value: string): Bounds | null;
50
+ export declare function boundsForAttribute(source: string, attribute: string, value: string | RegExp): Bounds | null;
40
51
  /** Bounds of an element addressed by Android `content-desc`. */
41
52
  export declare function boundsForContentDesc(source: string, contentDesc: string): Bounds | null;
42
53
  /** Bounds of an element addressed by visible `text`. */
package/dist/source.js CHANGED
@@ -50,17 +50,45 @@ export function decodeXmlEntities(value) {
50
50
  export function encodeXmlEntities(value) {
51
51
  return value.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;").replace(/"/g, "&quot;");
52
52
  }
53
+ /**
54
+ * The first element tag exposing `attribute` with a value matching `value`. `attribute`
55
+ * may be a regex alternation (e.g. `"(?:text|content-desc)"`). A string matches the
56
+ * entity-escaped source exactly; a RegExp is tested against each candidate's DECODED
57
+ * value, so `by.text(/Save( draft)?/)` matches whether the source XML-escaped it or not.
58
+ */
59
+ export function nodeForAttribute(source, attribute, value) {
60
+ return nodesForAttribute(source, attribute, value)[0] ?? null;
61
+ }
62
+ /** Every element tag exposing `attribute` with a value matching `value`, in document order. */
63
+ export function nodesForAttribute(source, attribute, value) {
64
+ if (typeof value === "string") {
65
+ const escaped = escapeRegExp(encodeXmlEntities(value));
66
+ return [...source.matchAll(new RegExp(`<[^>]*${attribute}="${escaped}"[^>]*>`, "g"))].map((m) => m[0]);
67
+ }
68
+ // A `g`-flagged RegExp is stateful across `.test()` calls; use a non-global copy so the
69
+ // per-candidate test is order-independent.
70
+ const test = value.global ? new RegExp(value.source, value.flags.replace("g", "")) : value;
71
+ const candidate = new RegExp(`${attribute}="([^"]*)"`);
72
+ const nodes = [];
73
+ for (const tag of source.matchAll(/<[^>]*>/g)) {
74
+ const attr = candidate.exec(tag[0]);
75
+ if (attr && test.test(decodeXmlEntities(attr[1] ?? "")))
76
+ nodes.push(tag[0]);
77
+ }
78
+ return nodes;
79
+ }
80
+ /** True if any element exposes `attribute` with a value matching `value` (string exact or RegExp). */
81
+ export function attributeMatches(source, attribute, value) {
82
+ return nodeForAttribute(source, attribute, value) !== null;
83
+ }
53
84
  /**
54
85
  * Bounds of the first element carrying the given attribute match. The element tag is
55
86
  * matched first, then `bounds` is extracted from within it regardless of attribute order —
56
87
  * so a source that emits `bounds` before the selector attribute still resolves.
57
88
  */
58
89
  export function boundsForAttribute(source, attribute, value) {
59
- const escaped = escapeRegExp(encodeXmlEntities(value));
60
- const node = new RegExp(`<[^>]*${attribute}="${escaped}"[^>]*>`).exec(source)?.[0];
61
- if (!node)
62
- return null;
63
- return parseBounds(/bounds="([^"]+)"/.exec(node)?.[1]);
90
+ const node = nodeForAttribute(source, attribute, value);
91
+ return node ? parseBounds(/bounds="([^"]+)"/.exec(node)?.[1]) : null;
64
92
  }
65
93
  /** Bounds of an element addressed by Android `content-desc`. */
66
94
  export function boundsForContentDesc(source, contentDesc) {
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "nativeproof",
3
- "version": "0.5.0",
3
+ "version": "0.6.0",
4
4
  "license": "MIT",
5
5
  "type": "module",
6
6
  "description": "Native Mobile E2E test framework inspired by Playwright (fixtures, locators, expect, route-style mocking) on Appium/WebdriverIO.",