uiLauncher.mjs
1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
/**
* 打开自动化小程序;启动模式显式拆分 IDE HTTP 端口和自动化 WS 端口。
* CLI 某些版本可能在已成功拉起自动化服务后仍返回异常,因此失败时会对同一
* loopback WS 地址补做一次连接,并在两步均失败时保留完整原因。
*
* @param {object} automator miniprogram-automator 实例。
* @param {object} config UI 自动化运行时配置。
* @returns {Promise<object>} 已连接的小程序实例。
*/
export const openMiniProgram = async (automator, config) => {
if (!config.launchDevTools) {
return automator.connect({ wsEndpoint: config.wsEndpoint })
}
const automationPort = config.automationPort ?? config.port
const wsEndpoint =
config.wsEndpoint || `ws://127.0.0.1:${automationPort}`
const launchOptions = {
cliPath: config.cliPath,
projectPath: config.projectPath,
port: automationPort,
trustProject: true
}
if (config.servicePort !== null && config.servicePort !== undefined) {
launchOptions.args = [
'--port',
String(config.servicePort),
'--lang',
'zh'
]
}
try {
return await automator.launch(launchOptions)
} catch (launchError) {
try {
return await automator.connect({ wsEndpoint })
} catch (connectError) {
throw new Error(
`Unable to launch or connect to mini-program automation at ${wsEndpoint}`,
{ cause: { launchError, connectError } }
)
}
}
}
/**
* 释放自动化连接。复用已有开发者工具窗口时只断开 WebSocket,避免 SDK 的
* close() 同时退出小程序和自动化服务;仅关闭由本次测试自行启动的窗口。
*
* @param {object} miniProgram 已连接的小程序实例。
* @param {object} config UI 自动化运行时配置。
* @returns {Promise<void>} 连接释放完成。
*/
export const releaseMiniProgram = async (miniProgram, config) => {
if (config.launchDevTools) {
await miniProgram.close()
return
}
miniProgram.disconnect()
}