@shipvo/test 0.0.0-stage → 0.1.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +73 -0
- package/README.md +61 -2
- package/dist/index.d.ts +4 -0
- package/dist/index.js +2 -0
- package/dist/phone.d.ts +129 -0
- package/dist/phone.js +148 -0
- package/dist/tree.d.ts +24 -0
- package/dist/tree.js +48 -0
- package/dist/vitest.d.ts +20 -0
- package/dist/vitest.js +21 -0
- package/package.json +53 -3
package/LICENSE
ADDED
|
@@ -0,0 +1,73 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction, and distribution as defined by Sections 1 through 9 of this document.
|
|
10
|
+
|
|
11
|
+
"Licensor" shall mean the copyright owner or entity authorized by the copyright owner that is granting the License.
|
|
12
|
+
|
|
13
|
+
"Legal Entity" shall mean the union of the acting entity and all other entities that control, are controlled by, or are under common control with that entity. For the purposes of this definition, "control" means (i) the power, direct or indirect, to cause the direction or management of such entity, whether by contract or otherwise, or (ii) ownership of fifty percent (50%) or more of the outstanding shares, or (iii) beneficial ownership of such entity.
|
|
14
|
+
|
|
15
|
+
"You" (or "Your") shall mean an individual or Legal Entity exercising permissions granted by this License.
|
|
16
|
+
|
|
17
|
+
"Source" form shall mean the preferred form for making modifications, including but not limited to software source code, documentation source, and configuration files.
|
|
18
|
+
|
|
19
|
+
"Object" form shall mean any form resulting from mechanical transformation or translation of a Source form, including but not limited to compiled object code, generated documentation, and conversions to other media types.
|
|
20
|
+
|
|
21
|
+
"Work" shall mean the work of authorship, whether in Source or Object form, made available under the License, as indicated by a copyright notice that is included in or attached to the work (an example is provided in the Appendix below).
|
|
22
|
+
|
|
23
|
+
"Derivative Works" shall mean any work, whether in Source or Object form, that is based on (or derived from) the Work and for which the editorial revisions, annotations, elaborations, or other modifications represent, as a whole, an original work of authorship. For the purposes of this License, Derivative Works shall not include works that remain separable from, or merely link (or bind by name) to the interfaces of, the Work and Derivative Works thereof.
|
|
24
|
+
|
|
25
|
+
"Contribution" shall mean any work of authorship, including the original version of the Work and any modifications or additions to that Work or Derivative Works thereof, that is intentionally submitted to Licensor for inclusion in the Work by the copyright owner or by an individual or Legal Entity authorized to submit on behalf of the copyright owner. For the purposes of this definition, "submitted" means any form of electronic, verbal, or written communication sent to the Licensor or its representatives, including but not limited to communication on electronic mailing lists, source code control systems, and issue tracking systems that are managed by, or on behalf of, the Licensor for the purpose of discussing and improving the Work, but excluding communication that is conspicuously marked or otherwise designated in writing by the copyright owner as "Not a Contribution."
|
|
26
|
+
|
|
27
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity on behalf of whom a Contribution has been received by Licensor and subsequently incorporated within the Work.
|
|
28
|
+
|
|
29
|
+
2. Grant of Copyright License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable copyright license to reproduce, prepare Derivative Works of, publicly display, publicly perform, sublicense, and distribute the Work and such Derivative Works in Source or Object form.
|
|
30
|
+
|
|
31
|
+
3. Grant of Patent License. Subject to the terms and conditions of this License, each Contributor hereby grants to You a perpetual, worldwide, non-exclusive, no-charge, royalty-free, irrevocable (except as stated in this section) patent license to make, have made, use, offer to sell, sell, import, and otherwise transfer the Work, where such license applies only to those patent claims licensable by such Contributor that are necessarily infringed by their Contribution(s) alone or by combination of their Contribution(s) with the Work to which such Contribution(s) was submitted. If You institute patent litigation against any entity (including a cross-claim or counterclaim in a lawsuit) alleging that the Work or a Contribution incorporated within the Work constitutes direct or contributory patent infringement, then any patent licenses granted to You under this License for that Work shall terminate as of the date such litigation is filed.
|
|
32
|
+
|
|
33
|
+
4. Redistribution. You may reproduce and distribute copies of the Work or Derivative Works thereof in any medium, with or without modifications, and in Source or Object form, provided that You meet the following conditions:
|
|
34
|
+
|
|
35
|
+
(a) You must give any other recipients of the Work or Derivative Works a copy of this License; and
|
|
36
|
+
|
|
37
|
+
(b) You must cause any modified files to carry prominent notices stating that You changed the files; and
|
|
38
|
+
|
|
39
|
+
(c) You must retain, in the Source form of any Derivative Works that You distribute, all copyright, patent, trademark, and attribution notices from the Source form of the Work, excluding those notices that do not pertain to any part of the Derivative Works; and
|
|
40
|
+
|
|
41
|
+
(d) If the Work includes a "NOTICE" text file as part of its distribution, then any Derivative Works that You distribute must include a readable copy of the attribution notices contained within such NOTICE file, excluding those notices that do not pertain to any part of the Derivative Works, in at least one of the following places: within a NOTICE text file distributed as part of the Derivative Works; within the Source form or documentation, if provided along with the Derivative Works; or, within a display generated by the Derivative Works, if and wherever such third-party notices normally appear. The contents of the NOTICE file are for informational purposes only and do not modify the License. You may add Your own attribution notices within Derivative Works that You distribute, alongside or as an addendum to the NOTICE text from the Work, provided that such additional attribution notices cannot be construed as modifying the License.
|
|
42
|
+
|
|
43
|
+
You may add Your own copyright statement to Your modifications and may provide additional or different license terms and conditions for use, reproduction, or distribution of Your modifications, or for any such Derivative Works as a whole, provided Your use, reproduction, and distribution of the Work otherwise complies with the conditions stated in this License.
|
|
44
|
+
|
|
45
|
+
5. Submission of Contributions. Unless You explicitly state otherwise, any Contribution intentionally submitted for inclusion in the Work by You to the Licensor shall be under the terms and conditions of this License, without any additional terms or conditions. Notwithstanding the above, nothing herein shall supersede or modify the terms of any separate license agreement you may have executed with Licensor regarding such Contributions.
|
|
46
|
+
|
|
47
|
+
6. Trademarks. This License does not grant permission to use the trade names, trademarks, service marks, or product names of the Licensor, except as required for reasonable and customary use in describing the origin of the Work and reproducing the content of the NOTICE file.
|
|
48
|
+
|
|
49
|
+
7. Disclaimer of Warranty. Unless required by applicable law or agreed to in writing, Licensor provides the Work (and each Contributor provides its Contributions) on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied, including, without limitation, any warranties or conditions of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR PURPOSE. You are solely responsible for determining the appropriateness of using or redistributing the Work and assume any risks associated with Your exercise of permissions under this License.
|
|
50
|
+
|
|
51
|
+
8. Limitation of Liability. In no event and under no legal theory, whether in tort (including negligence), contract, or otherwise, unless required by applicable law (such as deliberate and grossly negligent acts) or agreed to in writing, shall any Contributor be liable to You for damages, including any direct, indirect, special, incidental, or consequential damages of any character arising as a result of this License or out of the use or inability to use the Work (including but not limited to damages for loss of goodwill, work stoppage, computer failure or malfunction, or any and all other commercial damages or losses), even if such Contributor has been advised of the possibility of such damages.
|
|
52
|
+
|
|
53
|
+
9. Accepting Warranty or Additional Liability. While redistributing the Work or Derivative Works thereof, You may choose to offer, and charge a fee for, acceptance of support, warranty, indemnity, or other liability obligations and/or rights consistent with this License. However, in accepting such obligations, You may act only on Your own behalf and on Your sole responsibility, not on behalf of any other Contributor, and only if You agree to indemnify, defend, and hold each Contributor harmless for any liability incurred by, or claims asserted against, such Contributor by reason of your accepting any such warranty or additional liability.
|
|
54
|
+
|
|
55
|
+
END OF TERMS AND CONDITIONS
|
|
56
|
+
|
|
57
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
58
|
+
|
|
59
|
+
To apply the Apache License to your work, attach the following boilerplate notice, with the fields enclosed by brackets "[]" replaced with your own identifying information. (Don't include the brackets!) The text should be enclosed in the appropriate comment syntax for the file format. We also recommend that a file or class name and description of purpose be included on the same "printed page" as the copyright notice for easier identification within third-party archives.
|
|
60
|
+
|
|
61
|
+
Copyright [yyyy] [name of copyright owner]
|
|
62
|
+
|
|
63
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
64
|
+
you may not use this file except in compliance with the License.
|
|
65
|
+
You may obtain a copy of the License at
|
|
66
|
+
|
|
67
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
68
|
+
|
|
69
|
+
Unless required by applicable law or agreed to in writing, software
|
|
70
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
71
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
72
|
+
See the License for the specific language governing permissions and
|
|
73
|
+
limitations under the License.
|
package/README.md
CHANGED
|
@@ -1,3 +1,62 @@
|
|
|
1
|
-
#
|
|
1
|
+
# @shipvo/test
|
|
2
2
|
|
|
3
|
-
|
|
3
|
+
Typed end-to-end tests for React Native apps that run in the Shipvo simulator. Open your app, tap, type, set the phone's location, camera, permissions, biometrics, payment result and network, and assert on what is on screen. Headless, so it runs in CI with no emulator and no device.
|
|
4
|
+
|
|
5
|
+
```ts
|
|
6
|
+
import { test, expect } from "@shipvo/test/vitest";
|
|
7
|
+
|
|
8
|
+
test("location: the app asks, then reads the phone's location", async ({ phone }) => {
|
|
9
|
+
await phone.device.set({ location: { latitude: 4.0511, longitude: 9.7679 } });
|
|
10
|
+
await phone.tap("Use my location");
|
|
11
|
+
expect(phone).toSee("access this device's location");
|
|
12
|
+
await phone.tap("While using the app");
|
|
13
|
+
await phone.waitFor(/4\.05/);
|
|
14
|
+
});
|
|
15
|
+
```
|
|
16
|
+
|
|
17
|
+
```bash
|
|
18
|
+
npm i -D @shipvo/test vitest @shipvo/sim playwright
|
|
19
|
+
npx shipvo sim # the simulator, http://localhost:4545
|
|
20
|
+
npx vitest run
|
|
21
|
+
```
|
|
22
|
+
|
|
23
|
+
## Failure-path examples
|
|
24
|
+
|
|
25
|
+
Runnable versions are in [`examples/flows.ts`](examples/flows.ts). They use the Tide & Tackle labels. Change them to match your app. The checkout flows need a cart, so open the phone with one: `openApp({ seedCart: [{ product_id: "rod-surf-36", quantity: 1 }] })`. The full purchase is in [`checkout.test.ts`](../../apps/tide-and-tackle/tests/checkout.test.ts).
|
|
26
|
+
|
|
27
|
+
**Permission denied**
|
|
28
|
+
|
|
29
|
+
```ts
|
|
30
|
+
await phone.tap(/^Open cart/);
|
|
31
|
+
await phone.tap("Choose delivery and pay");
|
|
32
|
+
await phone.tap("Use my location");
|
|
33
|
+
await phone.tap("Deny");
|
|
34
|
+
await phone.waitFor("Location permission was not granted.");
|
|
35
|
+
```
|
|
36
|
+
|
|
37
|
+
**Offline**
|
|
38
|
+
|
|
39
|
+
```ts
|
|
40
|
+
await phone.device.set({ online: false });
|
|
41
|
+
await phone.waitFor("You're offline");
|
|
42
|
+
```
|
|
43
|
+
|
|
44
|
+
**Payment decline**
|
|
45
|
+
|
|
46
|
+
```ts
|
|
47
|
+
await phone.device.set({ payment: { nextResult: "decline", pin: "1234" }, biometrics: { enrolled: true, nextResult: "success" } });
|
|
48
|
+
await phone.tap(/^Open cart/);
|
|
49
|
+
await phone.tap("Choose delivery and pay");
|
|
50
|
+
await phone.tap(/^Any day Shop pickup/);
|
|
51
|
+
await phone.tap("Mobile money");
|
|
52
|
+
await phone.type("Mobile money number", "677000111");
|
|
53
|
+
await phone.tap("Place order");
|
|
54
|
+
await phone.tap("Use fingerprint");
|
|
55
|
+
await phone.type("Mobile money PIN", "1234");
|
|
56
|
+
await phone.tap("Confirm payment");
|
|
57
|
+
await phone.waitFor("Payment declined");
|
|
58
|
+
```
|
|
59
|
+
|
|
60
|
+
The tests for these flows run against a small fake simulator, not the real app. The fake follows the real screen order and button names.
|
|
61
|
+
|
|
62
|
+
Works with any runner through `openApp` from `@shipvo/test`. Full guide, CI workflow and API: [Test your app in CI](https://shipvo.dev/docs/testing/).
|
package/dist/index.d.ts
ADDED
package/dist/index.js
ADDED
package/dist/phone.d.ts
ADDED
|
@@ -0,0 +1,129 @@
|
|
|
1
|
+
import { type Node, type Target } from "./tree.js";
|
|
2
|
+
type Grant = "granted" | "denied" | "undetermined";
|
|
3
|
+
/** What the simulated phone has. Takes effect for the next action. */
|
|
4
|
+
export type DeviceSettings = {
|
|
5
|
+
location?: {
|
|
6
|
+
latitude: number;
|
|
7
|
+
longitude: number;
|
|
8
|
+
accuracy?: number;
|
|
9
|
+
};
|
|
10
|
+
/** What is in front of the camera: a barcode or QR code, or null for nothing. */
|
|
11
|
+
camera?: {
|
|
12
|
+
barcode?: {
|
|
13
|
+
type: string;
|
|
14
|
+
data: string;
|
|
15
|
+
} | null;
|
|
16
|
+
delayMs?: number;
|
|
17
|
+
};
|
|
18
|
+
permissions?: {
|
|
19
|
+
camera?: Grant;
|
|
20
|
+
location?: Grant;
|
|
21
|
+
notifications?: Grant;
|
|
22
|
+
};
|
|
23
|
+
biometrics?: {
|
|
24
|
+
enrolled?: boolean;
|
|
25
|
+
nextResult?: "success" | "fail" | "cancel";
|
|
26
|
+
};
|
|
27
|
+
payment?: {
|
|
28
|
+
nextResult?: "approve" | "decline" | "timeout" | "insufficient_funds";
|
|
29
|
+
pin?: string;
|
|
30
|
+
};
|
|
31
|
+
online?: boolean;
|
|
32
|
+
};
|
|
33
|
+
export type DeviceProfile = {
|
|
34
|
+
platform?: "android" | "ios";
|
|
35
|
+
api?: number;
|
|
36
|
+
};
|
|
37
|
+
export type OpenOptions = {
|
|
38
|
+
/** App id (default: SHIPVO_APP, else appId from ./shipvo.json). "id@latest" or "id@r13" opens a published release. */
|
|
39
|
+
app?: string;
|
|
40
|
+
/** Simulator URL (default: PN_SIM, else http://localhost:4545). */
|
|
41
|
+
sim?: string;
|
|
42
|
+
dark?: boolean;
|
|
43
|
+
session?: string;
|
|
44
|
+
/** Test shortcut passed to the app as globalThis.__PN_SIM__.seed_cart, in whatever shape your app reads (Tide reads { product_id, quantity }). */
|
|
45
|
+
seedCart?: Record<string, unknown>[];
|
|
46
|
+
/** Applied right after opening, before the first screen is read. */
|
|
47
|
+
device?: DeviceSettings;
|
|
48
|
+
};
|
|
49
|
+
export type Notification = {
|
|
50
|
+
id: string;
|
|
51
|
+
title: string;
|
|
52
|
+
body: string;
|
|
53
|
+
data?: Record<string, unknown>;
|
|
54
|
+
};
|
|
55
|
+
type Reply = {
|
|
56
|
+
ok: boolean;
|
|
57
|
+
screen?: string | null;
|
|
58
|
+
error?: string;
|
|
59
|
+
path?: string;
|
|
60
|
+
notifications?: Notification[];
|
|
61
|
+
log?: unknown[];
|
|
62
|
+
capabilities?: unknown;
|
|
63
|
+
release?: string | number;
|
|
64
|
+
};
|
|
65
|
+
/** A simulated phone running your app. Every action returns once the screen has settled, and updates `screen`. */
|
|
66
|
+
export declare class Phone {
|
|
67
|
+
readonly session: string;
|
|
68
|
+
private readonly sim;
|
|
69
|
+
readonly app: string;
|
|
70
|
+
readonly release: string | number;
|
|
71
|
+
/** The current screen as an accessibility tree. */
|
|
72
|
+
screen: string;
|
|
73
|
+
readonly device: Device;
|
|
74
|
+
constructor(session: string, sim: string, app: string, release: string | number);
|
|
75
|
+
/** @internal */
|
|
76
|
+
call(path: string, body: Record<string, unknown>): Promise<Reply>;
|
|
77
|
+
/** @internal */
|
|
78
|
+
act(action: string, extra?: Record<string, unknown>): Promise<Reply>;
|
|
79
|
+
/** Every element on the current screen. */
|
|
80
|
+
nodes(): Node[];
|
|
81
|
+
/** Is this text (or pattern) anywhere on the current screen? */
|
|
82
|
+
sees(text: string | RegExp): boolean;
|
|
83
|
+
/** Find one element without acting on it. Throws if none or several match. */
|
|
84
|
+
locate(target: Target): Node;
|
|
85
|
+
tap(target: Target): Promise<this>;
|
|
86
|
+
type(target: Target, text: string, opts?: {
|
|
87
|
+
enter?: boolean;
|
|
88
|
+
}): Promise<this>;
|
|
89
|
+
scroll(direction?: "down" | "up" | "left" | "right", on?: Target): Promise<this>;
|
|
90
|
+
back(): Promise<this>;
|
|
91
|
+
refresh(): Promise<this>;
|
|
92
|
+
/** Wait until the text appears (default 5 s). On timeout the error carries the last screen. */
|
|
93
|
+
waitFor(text: string | RegExp, opts?: {
|
|
94
|
+
timeout?: number;
|
|
95
|
+
interval?: number;
|
|
96
|
+
}): Promise<this>;
|
|
97
|
+
/** Wait until the text is gone. */
|
|
98
|
+
waitForGone(text: string | RegExp, opts?: {
|
|
99
|
+
timeout?: number;
|
|
100
|
+
interval?: number;
|
|
101
|
+
}): Promise<this>;
|
|
102
|
+
/** Deliver a push notification: it shows as a banner the app can be opened from. */
|
|
103
|
+
notify(n: {
|
|
104
|
+
title: string;
|
|
105
|
+
body: string;
|
|
106
|
+
data?: Record<string, unknown>;
|
|
107
|
+
}): Promise<this>;
|
|
108
|
+
/** The notification shade (banners vanish after about 5 s, the shade keeps them). */
|
|
109
|
+
notifications(): Promise<Notification[]>;
|
|
110
|
+
/** Tap a notification from the shade (the newest if no id). */
|
|
111
|
+
openNotification(id?: string): Promise<this>;
|
|
112
|
+
/** What the app did with the device: permission prompts and answers, location reads, scans, fingerprint checks, payments. */
|
|
113
|
+
deviceLog(): Promise<unknown[]>;
|
|
114
|
+
/** A PNG of the screen. Works when the test runs on the same machine as the simulator, as in CI. */
|
|
115
|
+
screenshot(): Promise<Uint8Array>;
|
|
116
|
+
/** Nothing to release on the simulator side today; kept so tests read the same if that changes. */
|
|
117
|
+
close(): Promise<void>;
|
|
118
|
+
}
|
|
119
|
+
/** The simulated phone's hardware and settings. */
|
|
120
|
+
export declare class Device {
|
|
121
|
+
private readonly phone;
|
|
122
|
+
constructor(phone: Phone);
|
|
123
|
+
set(settings: DeviceSettings): Promise<Phone>;
|
|
124
|
+
/** Back to a known state: permissions undetermined, default location, nothing in front of the camera, log cleared. */
|
|
125
|
+
reset(profile?: DeviceProfile): Promise<Phone>;
|
|
126
|
+
}
|
|
127
|
+
/** Open your app in a fresh simulated phone. */
|
|
128
|
+
export declare function openApp(opts?: OpenOptions): Promise<Phone>;
|
|
129
|
+
export {};
|
package/dist/phone.js
ADDED
|
@@ -0,0 +1,148 @@
|
|
|
1
|
+
import { existsSync, readFileSync } from "node:fs";
|
|
2
|
+
import { find, parseScreen } from "./tree.js";
|
|
3
|
+
/** A simulated phone running your app. Every action returns once the screen has settled, and updates `screen`. */
|
|
4
|
+
export class Phone {
|
|
5
|
+
session;
|
|
6
|
+
sim;
|
|
7
|
+
app;
|
|
8
|
+
release;
|
|
9
|
+
/** The current screen as an accessibility tree. */
|
|
10
|
+
screen = "";
|
|
11
|
+
device;
|
|
12
|
+
constructor(session, sim, app, release) {
|
|
13
|
+
this.session = session;
|
|
14
|
+
this.sim = sim;
|
|
15
|
+
this.app = app;
|
|
16
|
+
this.release = release;
|
|
17
|
+
this.device = new Device(this);
|
|
18
|
+
}
|
|
19
|
+
/** @internal */
|
|
20
|
+
async call(path, body) {
|
|
21
|
+
const r = await fetch(this.sim + path, { method: "POST", headers: { "content-type": "application/json" }, body: JSON.stringify(body) });
|
|
22
|
+
if (!r.ok)
|
|
23
|
+
throw new Error(`simulator ${path} answered ${r.status}. Is it running at ${this.sim}? Start it with: npx shipvo sim`);
|
|
24
|
+
return (await r.json());
|
|
25
|
+
}
|
|
26
|
+
/** @internal */
|
|
27
|
+
async act(action, extra = {}) {
|
|
28
|
+
const r = await this.call("/act", { session: this.session, action, ...extra });
|
|
29
|
+
if (typeof r.screen === "string")
|
|
30
|
+
this.screen = r.screen;
|
|
31
|
+
// A page that is still loading reads as empty: give it a moment rather than report a blank screen.
|
|
32
|
+
for (let i = 0; r.ok && action !== "screenshot" && !this.screen.trim() && i < 10; i++) {
|
|
33
|
+
await new Promise((res) => setTimeout(res, 200));
|
|
34
|
+
const again = await this.call("/act", { session: this.session, action: "screen" });
|
|
35
|
+
if (typeof again.screen === "string")
|
|
36
|
+
this.screen = again.screen;
|
|
37
|
+
}
|
|
38
|
+
if (!r.ok)
|
|
39
|
+
throw new Error(`${action} failed: ${r.error}\n\nScreen now:\n${this.screen}`);
|
|
40
|
+
return r;
|
|
41
|
+
}
|
|
42
|
+
/** Every element on the current screen. */
|
|
43
|
+
nodes() { return parseScreen(this.screen); }
|
|
44
|
+
/** Is this text (or pattern) anywhere on the current screen? */
|
|
45
|
+
sees(text) {
|
|
46
|
+
return text instanceof RegExp ? text.test(this.screen) : this.screen.toLowerCase().includes(text.toLowerCase());
|
|
47
|
+
}
|
|
48
|
+
/** Find one element without acting on it. Throws if none or several match. */
|
|
49
|
+
locate(target) {
|
|
50
|
+
try {
|
|
51
|
+
return find(this.nodes(), target);
|
|
52
|
+
}
|
|
53
|
+
catch (e) {
|
|
54
|
+
throw new Error(`${e.message}\n\nScreen now:\n${this.screen}`);
|
|
55
|
+
}
|
|
56
|
+
}
|
|
57
|
+
async tap(target) { await this.act("tap", { ref: this.locate(target).ref }); return this; }
|
|
58
|
+
async type(target, text, opts = {}) {
|
|
59
|
+
const n = find(this.nodes(), target, typeof target === "string" || target instanceof RegExp ? { roles: ["textbox", "searchbox", "spinbutton", "combobox"] } : {});
|
|
60
|
+
await this.act("type", { ref: n.ref, text, enter: opts.enter });
|
|
61
|
+
return this;
|
|
62
|
+
}
|
|
63
|
+
async scroll(direction = "down", on) {
|
|
64
|
+
await this.act("scroll", { direction, ref: on ? this.locate(on).ref : undefined });
|
|
65
|
+
return this;
|
|
66
|
+
}
|
|
67
|
+
async back() { await this.act("back"); return this; }
|
|
68
|
+
async refresh() { await this.act("screen"); return this; }
|
|
69
|
+
/** Wait until the text appears (default 5 s). On timeout the error carries the last screen. */
|
|
70
|
+
async waitFor(text, opts = {}) {
|
|
71
|
+
const end = Date.now() + (opts.timeout ?? 5000);
|
|
72
|
+
for (;;) {
|
|
73
|
+
await this.refresh();
|
|
74
|
+
if (this.sees(text))
|
|
75
|
+
return this;
|
|
76
|
+
if (Date.now() > end)
|
|
77
|
+
throw new Error(`timed out waiting for ${text instanceof RegExp ? text : `"${text}"`}\n\nScreen now:\n${this.screen}`);
|
|
78
|
+
await new Promise((r) => setTimeout(r, opts.interval ?? 250));
|
|
79
|
+
}
|
|
80
|
+
}
|
|
81
|
+
/** Wait until the text is gone. */
|
|
82
|
+
async waitForGone(text, opts = {}) {
|
|
83
|
+
const end = Date.now() + (opts.timeout ?? 5000);
|
|
84
|
+
for (;;) {
|
|
85
|
+
await this.refresh();
|
|
86
|
+
if (!this.sees(text))
|
|
87
|
+
return this;
|
|
88
|
+
if (Date.now() > end)
|
|
89
|
+
throw new Error(`"${text}" is still on screen after ${opts.timeout ?? 5000} ms\n\nScreen now:\n${this.screen}`);
|
|
90
|
+
await new Promise((r) => setTimeout(r, opts.interval ?? 250));
|
|
91
|
+
}
|
|
92
|
+
}
|
|
93
|
+
/** Deliver a push notification: it shows as a banner the app can be opened from. */
|
|
94
|
+
async notify(n) { await this.act("push_notification", n); return this; }
|
|
95
|
+
/** The notification shade (banners vanish after about 5 s, the shade keeps them). */
|
|
96
|
+
async notifications() { return (await this.act("notifications")).notifications ?? []; }
|
|
97
|
+
/** Tap a notification from the shade (the newest if no id). */
|
|
98
|
+
async openNotification(id) { await this.act("open_notification", { id }); return this; }
|
|
99
|
+
/** What the app did with the device: permission prompts and answers, location reads, scans, fingerprint checks, payments. */
|
|
100
|
+
async deviceLog() { return (await this.act("device_log")).log ?? []; }
|
|
101
|
+
/** A PNG of the screen. Works when the test runs on the same machine as the simulator, as in CI. */
|
|
102
|
+
async screenshot() {
|
|
103
|
+
const r = await this.act("screenshot");
|
|
104
|
+
if (!r.path)
|
|
105
|
+
throw new Error("the simulator returned no screenshot");
|
|
106
|
+
return new Uint8Array(readFileSync(r.path));
|
|
107
|
+
}
|
|
108
|
+
/** Nothing to release on the simulator side today; kept so tests read the same if that changes. */
|
|
109
|
+
async close() { }
|
|
110
|
+
}
|
|
111
|
+
/** The simulated phone's hardware and settings. */
|
|
112
|
+
export class Device {
|
|
113
|
+
phone;
|
|
114
|
+
constructor(phone) {
|
|
115
|
+
this.phone = phone;
|
|
116
|
+
}
|
|
117
|
+
async set(settings) { await this.phone.act("set_device", { device: settings }); return this.phone; }
|
|
118
|
+
/** Back to a known state: permissions undetermined, default location, nothing in front of the camera, log cleared. */
|
|
119
|
+
async reset(profile = {}) { await this.phone.act("device_reset", { device: profile }); return this.phone; }
|
|
120
|
+
}
|
|
121
|
+
function defaultApp() {
|
|
122
|
+
if (process.env.SHIPVO_APP)
|
|
123
|
+
return process.env.SHIPVO_APP;
|
|
124
|
+
if (existsSync("shipvo.json")) {
|
|
125
|
+
try {
|
|
126
|
+
return JSON.parse(readFileSync("shipvo.json", "utf8")).appId;
|
|
127
|
+
}
|
|
128
|
+
catch { /* fall through */ }
|
|
129
|
+
}
|
|
130
|
+
throw new Error("which app? Pass { app } to openApp, set SHIPVO_APP, or run from a folder with shipvo.json");
|
|
131
|
+
}
|
|
132
|
+
/** Open your app in a fresh simulated phone. */
|
|
133
|
+
export async function openApp(opts = {}) {
|
|
134
|
+
const sim = (opts.sim ?? process.env.PN_SIM ?? "http://localhost:4545").replace(/\/$/, "");
|
|
135
|
+
const app = opts.app ?? defaultApp();
|
|
136
|
+
const session = opts.session ?? `t-${Math.random().toString(36).slice(2, 10)}`;
|
|
137
|
+
const probe = new Phone(session, sim, app.split("@")[0], "local");
|
|
138
|
+
const r = await probe.call("/session", { session, app, seed_cart: opts.seedCart, dark: opts.dark });
|
|
139
|
+
if (!r.ok)
|
|
140
|
+
throw new Error(`could not open "${app}": ${r.error}`);
|
|
141
|
+
const phone = new Phone(session, sim, app.split("@")[0], r.release ?? "local");
|
|
142
|
+
phone.screen = r.screen ?? "";
|
|
143
|
+
if (!phone.screen.trim())
|
|
144
|
+
await phone.refresh(); // a seeded cart reloads the page: read the screen again
|
|
145
|
+
if (opts.device)
|
|
146
|
+
await phone.device.set(opts.device);
|
|
147
|
+
return phone;
|
|
148
|
+
}
|
package/dist/tree.d.ts
ADDED
|
@@ -0,0 +1,24 @@
|
|
|
1
|
+
/** One line of the simulator's screen: the accessibility tree an agent sees. */
|
|
2
|
+
export type Node = {
|
|
3
|
+
role: string;
|
|
4
|
+
/** Accessible name: the quoted label (buttons, links, fields, headings). */
|
|
5
|
+
name: string;
|
|
6
|
+
/** Text after the colon (plain text nodes). */
|
|
7
|
+
text: string;
|
|
8
|
+
ref: string;
|
|
9
|
+
/** Raw attribute brackets, e.g. ["level=1", "disabled"]. */
|
|
10
|
+
attrs: string[];
|
|
11
|
+
line: string;
|
|
12
|
+
};
|
|
13
|
+
/** Parse a screen into nodes. Lines that are not elements (url lines, blank) are skipped. */
|
|
14
|
+
export declare function parseScreen(screen: string): Node[];
|
|
15
|
+
/** What to act on: a visible label or text, a pattern, a role and name, or a ref from the screen. */
|
|
16
|
+
export type Target = string | RegExp | {
|
|
17
|
+
role?: string;
|
|
18
|
+
name?: string | RegExp;
|
|
19
|
+
ref?: string;
|
|
20
|
+
};
|
|
21
|
+
/** Find one element. Exact label wins; otherwise a unique case-insensitive substring. Ambiguity is an error that lists the candidates. */
|
|
22
|
+
export declare function find(nodes: Node[], target: Target, { roles }?: {
|
|
23
|
+
roles?: string[];
|
|
24
|
+
}): Node;
|
package/dist/tree.js
ADDED
|
@@ -0,0 +1,48 @@
|
|
|
1
|
+
const LINE = /^\s*- ([\w-]+)(?: "((?:[^"\\]|\\.)*)")?((?: \[[^\]]*\])*)(?::\s*(.*))?$/;
|
|
2
|
+
const unquote = (s) => s.replace(/\\(.)/g, "$1");
|
|
3
|
+
/** Parse a screen into nodes. Lines that are not elements (url lines, blank) are skipped. */
|
|
4
|
+
export function parseScreen(screen) {
|
|
5
|
+
const out = [];
|
|
6
|
+
for (const raw of screen.split("\n")) {
|
|
7
|
+
// The snapshot YAML-quotes a line when its name contains ": " or similar: - 'button "a: b" [ref=e1]':
|
|
8
|
+
const q = /^(\s*- )'(.*)'(:?)$/.exec(raw);
|
|
9
|
+
const line = q ? q[1] + q[2].replace(/''/g, "'") + q[3] : raw;
|
|
10
|
+
const m = LINE.exec(line);
|
|
11
|
+
if (!m)
|
|
12
|
+
continue;
|
|
13
|
+
const attrs = [...(m[3] ?? "").matchAll(/\[([^\]]*)\]/g)].map((x) => x[1]);
|
|
14
|
+
const ref = attrs.find((a) => /^ref=/.test(a))?.slice(4) ?? "";
|
|
15
|
+
if (!ref)
|
|
16
|
+
continue;
|
|
17
|
+
let text = (m[4] ?? "").trim();
|
|
18
|
+
if (/^".*"$/.test(text))
|
|
19
|
+
text = unquote(text.slice(1, -1));
|
|
20
|
+
out.push({ role: m[1], name: m[2] === undefined ? "" : unquote(m[2]), text, ref, attrs: attrs.filter((a) => !/^(ref|cursor)=/.test(a)), line: line.trim() });
|
|
21
|
+
}
|
|
22
|
+
return out;
|
|
23
|
+
}
|
|
24
|
+
const matches = (v, want, exact) => want instanceof RegExp ? want.test(v) : exact ? v === want : v.toLowerCase().includes(want.toLowerCase());
|
|
25
|
+
const label = (n) => n.name || n.text;
|
|
26
|
+
/** Find one element. Exact label wins; otherwise a unique case-insensitive substring. Ambiguity is an error that lists the candidates. */
|
|
27
|
+
export function find(nodes, target, { roles } = {}) {
|
|
28
|
+
const pool = (list) => (roles ? list.filter((n) => roles.includes(n.role)) : list);
|
|
29
|
+
const describe = typeof target === "string" ? `"${target}"` : target instanceof RegExp ? String(target) : JSON.stringify(target);
|
|
30
|
+
let hits;
|
|
31
|
+
if (typeof target === "object" && !(target instanceof RegExp)) {
|
|
32
|
+
if (target.ref)
|
|
33
|
+
hits = nodes.filter((n) => n.ref === target.ref);
|
|
34
|
+
else
|
|
35
|
+
hits = nodes.filter((n) => (!target.role || n.role === target.role) && (target.name === undefined || matches(label(n), target.name, typeof target.name === "string")));
|
|
36
|
+
}
|
|
37
|
+
else {
|
|
38
|
+
const all = pool(nodes).filter((n) => label(n) !== "");
|
|
39
|
+
hits = all.filter((n) => matches(label(n), target, true));
|
|
40
|
+
if (hits.length === 0 && typeof target === "string")
|
|
41
|
+
hits = all.filter((n) => matches(label(n), target, false));
|
|
42
|
+
}
|
|
43
|
+
if (hits.length === 0)
|
|
44
|
+
throw new Error(`nothing on screen matches ${describe}`);
|
|
45
|
+
if (hits.length > 1)
|
|
46
|
+
throw new Error(`${hits.length} elements match ${describe}; be more specific:\n${hits.slice(0, 6).map((n) => " " + n.line).join("\n")}`);
|
|
47
|
+
return hits[0];
|
|
48
|
+
}
|
package/dist/vitest.d.ts
ADDED
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
import { expect } from "vitest";
|
|
2
|
+
import { openApp, type Phone } from "./phone.js";
|
|
3
|
+
interface ShipvoMatchers<R = unknown> {
|
|
4
|
+
/** The phone's current screen contains this text or pattern. */
|
|
5
|
+
toSee(text: string | RegExp): R;
|
|
6
|
+
/** There is a button with this name (exact, or a pattern) on screen. */
|
|
7
|
+
toHaveButton(name: string | RegExp): R;
|
|
8
|
+
}
|
|
9
|
+
declare module "vitest" {
|
|
10
|
+
interface Assertion<T = any> extends ShipvoMatchers<T> {
|
|
11
|
+
}
|
|
12
|
+
interface AsymmetricMatchersContaining extends ShipvoMatchers {
|
|
13
|
+
}
|
|
14
|
+
}
|
|
15
|
+
/** A fresh simulated phone per test, closed afterwards. Needs the simulator running (npx shipvo sim). */
|
|
16
|
+
export declare const test: import("vitest").TestAPI<{
|
|
17
|
+
phone: Phone;
|
|
18
|
+
}>;
|
|
19
|
+
export { expect, openApp };
|
|
20
|
+
export type { Phone };
|
package/dist/vitest.js
ADDED
|
@@ -0,0 +1,21 @@
|
|
|
1
|
+
// Vitest integration: a `phone` fixture (a fresh simulated phone per test) and screen matchers.
|
|
2
|
+
// import { test, expect } from "@shipvo/test/vitest";
|
|
3
|
+
// test("checkout", async ({ phone }) => { await phone.tap("Add to cart"); expect(phone).toSee("Cart (1)"); });
|
|
4
|
+
import { expect, test as base } from "vitest";
|
|
5
|
+
import { openApp } from "./phone.js";
|
|
6
|
+
const show = (t) => (t instanceof RegExp ? String(t) : JSON.stringify(t));
|
|
7
|
+
expect.extend({
|
|
8
|
+
toSee(phone, text) {
|
|
9
|
+
const pass = phone.sees(text);
|
|
10
|
+
return { pass, message: () => (pass ? `expected the screen not to show ${show(text)}\n\n${phone.screen}` : `expected the screen to show ${show(text)}\n\nScreen now:\n${phone.screen}`) };
|
|
11
|
+
},
|
|
12
|
+
toHaveButton(phone, name) {
|
|
13
|
+
const pass = phone.nodes().some((n) => n.role === "button" && (name instanceof RegExp ? name.test(n.name) : n.name === name));
|
|
14
|
+
return { pass, message: () => (pass ? `expected no button ${show(name)}` : `expected a button ${show(name)}\n\nScreen now:\n${phone.screen}`) };
|
|
15
|
+
},
|
|
16
|
+
});
|
|
17
|
+
/** A fresh simulated phone per test, closed afterwards. Needs the simulator running (npx shipvo sim). */
|
|
18
|
+
export const test = base.extend({
|
|
19
|
+
phone: async ({}, use) => { const phone = await openApp(); await use(phone); await phone.close(); },
|
|
20
|
+
});
|
|
21
|
+
export { expect, openApp };
|
package/package.json
CHANGED
|
@@ -1,6 +1,56 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@shipvo/test",
|
|
3
|
-
"version": "0.
|
|
4
|
-
"
|
|
5
|
-
"
|
|
3
|
+
"version": "0.1.1",
|
|
4
|
+
"type": "module",
|
|
5
|
+
"license": "Apache-2.0",
|
|
6
|
+
"description": "Typed end-to-end tests for React Native apps that run in the Shipvo simulator: open the app, tap, type, set the phone's location, camera and permissions, and assert on what is on screen. Works in Vitest or any test runner, headless, in CI.",
|
|
7
|
+
"main": "dist/index.js",
|
|
8
|
+
"types": "dist/index.d.ts",
|
|
9
|
+
"exports": {
|
|
10
|
+
".": {
|
|
11
|
+
"types": "./dist/index.d.ts",
|
|
12
|
+
"default": "./dist/index.js"
|
|
13
|
+
},
|
|
14
|
+
"./vitest": {
|
|
15
|
+
"types": "./dist/vitest.d.ts",
|
|
16
|
+
"default": "./dist/vitest.js"
|
|
17
|
+
}
|
|
18
|
+
},
|
|
19
|
+
"files": [
|
|
20
|
+
"dist",
|
|
21
|
+
"README.md"
|
|
22
|
+
],
|
|
23
|
+
"peerDependencies": {
|
|
24
|
+
"vitest": ">=2"
|
|
25
|
+
},
|
|
26
|
+
"peerDependenciesMeta": {
|
|
27
|
+
"vitest": {
|
|
28
|
+
"optional": true
|
|
29
|
+
}
|
|
30
|
+
},
|
|
31
|
+
"devDependencies": {
|
|
32
|
+
"@types/node": "^22.8.0",
|
|
33
|
+
"typescript": "^5.6.3",
|
|
34
|
+
"vitest": "^2.1.4"
|
|
35
|
+
},
|
|
36
|
+
"keywords": [
|
|
37
|
+
"react-native",
|
|
38
|
+
"expo",
|
|
39
|
+
"testing",
|
|
40
|
+
"e2e",
|
|
41
|
+
"simulator",
|
|
42
|
+
"vitest",
|
|
43
|
+
"ci",
|
|
44
|
+
"shipvo"
|
|
45
|
+
],
|
|
46
|
+
"homepage": "https://shipvo.dev/docs/testing/",
|
|
47
|
+
"repository": {
|
|
48
|
+
"type": "git",
|
|
49
|
+
"url": "git+https://github.com/shipvo/shipvo.git",
|
|
50
|
+
"directory": "packages/test"
|
|
51
|
+
},
|
|
52
|
+
"scripts": {
|
|
53
|
+
"build": "tsc -p tsconfig.json",
|
|
54
|
+
"test": "tsc -p tsconfig.examples.json && vitest run"
|
|
55
|
+
}
|
|
6
56
|
}
|