1# arkXtest User Guide 2 3 4## Overview 5 6arkXtest is an automated test framework that consists of JsUnit and UiTest.<br>JsUnit is a unit test framework that provides basic APIs for compiling test cases and generating test reports for testing system and application APIs.<br>UiTest is a UI test framework that provides the UI component search and operation capabilities through simple and easy-to-use APIs, and allows you to develop automated test scripts based on GUI operations.<br>This document will help to familiarize you with arkXtest, describing its main functions, implementation principles, environment setup, and test script compilation and execution. In addition, the shell commands are provided for the following features: obtaining screenshots, component trees, recording user operations, and conveniently injecting UI simulation operations, which facilitates testing and verification. 7 8## Implementation 9 10arkXtest is divided into two parts: unit test framework and UI test framework.<br>As the backbone of arkXtest, the unit test framework offers such features as identifying, scheduling, and executing test scripts, as well as summarizing test script execution results.<br>The UI test framework provides UiTest APIs for you to call in different test scenarios. Its test scripts are executed on top of the unit test framework. 11 12### Unit Test Framework 13 14 Figure 1 Main functions of the unit test framework 15 16  17 18 Figure 2 Basic script process 19 20  21 22### UI Test Framework 23 24 Figure 3 Main functions of the UI test framework 25 26  27 28## Compile and Execute Tests Based on ArkTS 29 30### Setting Up the Environment 31 32[Download DevEco Studio](https://developer.harmonyos.com/cn/develop/deveco-studio#download) and set it up as instructed on the official website. 33 34### Creating and Compiling a Test Script 35 36#### Creating a Test Script 37 38<!--RP2--> 391. Open DevEco Studio and create a project, in which the **ohos** directory is where the test script is located. 40 412. Open the .ets file of the module to be tested in the project directory. Move the cursor to any position in the code, and then right-click and choose **Show Context Actions** > **Create Ohos Test** or press **Alt+Enter** and choose **Create Ohos Test** to create a test class. For more details, see [DevEco Studio User Guide](https://developer.harmonyos.com/en/docs/documentation/doc-guides-V3/harmonyos_jnit_jsunit-0000001092459608-V3?catalogVersion=V3#section13366184061415). 42 43<!--RP2End--> 44 45#### Writing a Unit Test Script 46 47This section describes how to use the unit test framework to write a unit test script. For details about the functionality of the unit test framework, see [arkXtest](https://gitee.com/openharmony/testfwk_arkxtest/blob/master/README_en.md). 48 49The unit test script must contain the following basic elements: 50 511. Import of the dependencies so that the dependent test APIs can be used. 52 532. Test code, mainly about the related logic, such as API invoking. 54 553. Invoking of the assertion APIs and setting of checkpoints. If there is no checkpoint, the test script is considered as incomplete. 56 57The following sample code is used to start the test page to check whether the page displayed on the device is the expected page. 58 59```ts 60import { describe, it, expect } from '@ohos/hypium'; 61import { abilityDelegatorRegistry } from '@kit.TestKit'; 62import { UIAbility, Want } from '@kit.AbilityKit'; 63 64const delegator = abilityDelegatorRegistry.getAbilityDelegator() 65const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 66function sleep(time: number) { 67 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 68} 69export default function abilityTest() { 70 describe('ActsAbilityTest', () =>{ 71 it('testUiExample',0, async (done: Function) => { 72 console.info("uitest: TestUiExample begin"); 73 //start tested ability 74 const want: Want = { 75 bundleName: bundleName, 76 abilityName: 'EntryAbility' 77 } 78 await delegator.startAbility(want); 79 await sleep(1000); 80 // Check the top display ability. 81 const ability: UIAbility = await delegator.getCurrentTopAbility(); 82 console.info("get top ability"); 83 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 84 done(); 85 }) 86 }) 87} 88``` 89 90#### Writing a UI Test Script 91 92 <br>To write a UI test script to complete the corresponding test activities, simply add the invoking of the UiTest API to a unit test script. <!--RP1-->For details about the available APIs, see [@ohos.UiTest](..reference/apis-test-kit/js-apis-uitest.md).<!--RP1End--><br>In this example, the UI test script is written based on the preceding unit test script. It implements the click operation on the started application page and checks whether the page changes as expected. 93 941. Write the demo code in the **index.ets**file. 95 96 ```ts 97 @Entry 98 @Component 99 struct Index { 100 @State message: string = 'Hello World' 101 102 build() { 103 Row() { 104 Column() { 105 Text(this.message) 106 .fontSize(50) 107 .fontWeight(FontWeight.Bold) 108 Text("Next") 109 .fontSize(50) 110 .margin({top:20}) 111 .fontWeight(FontWeight.Bold) 112 Text("after click") 113 .fontSize(50) 114 .margin({top:20}) 115 .fontWeight(FontWeight.Bold) 116 } 117 .width('100%') 118 } 119 .height('100%') 120 } 121 } 122 ``` 123 1242. Write test code in the .test.ets file under **ohosTest** > **ets** > **test**. 125 126 ```ts 127 import { describe, it, expect } from '@ohos/hypium'; 128 // Import the test dependencies. 129 import { abilityDelegatorRegistry, Driver, ON } from '@kit.TestKit'; 130 import { UIAbility, Want } from '@kit.AbilityKit'; 131 132 const delegator: abilityDelegatorRegistry.AbilityDelegator = abilityDelegatorRegistry.getAbilityDelegator() 133 const bundleName = abilityDelegatorRegistry.getArguments().bundleName; 134 function sleep(time: number) { 135 return new Promise<void>((resolve: Function) => setTimeout(resolve, time)); 136 } 137 export default function abilityTest() { 138 describe('ActsAbilityTest', () => { 139 it('testUiExample',0, async (done: Function) => { 140 console.info("uitest: TestUiExample begin"); 141 //start tested ability 142 const want: Want = { 143 bundleName: bundleName, 144 abilityName: 'EntryAbility' 145 } 146 await delegator.startAbility(want); 147 await sleep(1000); 148 // Check the top display ability. 149 const ability: UIAbility = await delegator.getCurrentTopAbility(); 150 console.info("get top ability"); 151 expect(ability.context.abilityInfo.name).assertEqual('EntryAbility'); 152 // UI test code 153 // Initialize the driver. 154 const driver = Driver.create(); 155 await driver.delayMs(1000); 156 // Find the button on text 'Next'. 157 const button = await driver.findComponent(ON.text('Next')); 158 // Click the button. 159 await button.click(); 160 await driver.delayMs(1000); 161 // Check text. 162 await driver.assertComponentExist(ON.text('after click')); 163 await driver.pressBack(); 164 done(); 165 }) 166 }) 167 } 168 ``` 169 170### Running the Test Script 171 172#### In DevEco Studio 173 174To execute the script, you need to connect to a hardware device. You can run a test script in DevEco Studio in any of the following modes: 175 1761. Test package level: All test cases in the test package are executed. 177 1782. Test suite level: All test cases defined in the **describe** method are executed. 179 1803. Test method level: The specified **it** method, that is, a single test case, is executed. 181 182 183 184**Viewing the Test Result** 185 186After the test is complete, you can view the test result in DevEco Studio, as shown in the following figure. 187 188 189 190**Viewing the Test Case Coverage** 191 192After the test is complete, you can view the test coverage. For details, see the coverage statistics modes in [Code Test](https://developer.huawei.com/consumer/cn/doc/harmonyos-guides-V5/ide-code-test-V5). 193 194#### In the CMD 195 196To run the script, you need to connect to a hardware device, install the application test package on the test device, and run the **aa** command in the cmd window. 197 198> **NOTE** 199> 200> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 201 202The table below lists the keywords in **aa** test commands. 203 204| Keyword | Abbreviation| Description | Example | 205| ------------- | ------------ | -------------------------------------- | ---------------------------------- | 206| --bundleName | -b | Application bundle name. | - b com.test.example | 207| --packageName | -p | Application module name, which is applicable to applications developed in the FA model. | - p com.test.example.entry | 208| --moduleName | -m | Application module name, which is applicable to applications developed in the stage model. | -m entry | 209| NA | -s | \<key, value> pair.| - s unittest /ets/testrunner/OpenHarmonyTestRunner | 210 211The framework supports multiple test case execution modes, which are triggered by the key-value pair following the **-s** keyword. The table below lists the available keys and values. 212 213| Name | Description | Value | Example | 214| ------------ | ----------------------------------------------------------------------------- | ------------------------------------------------------------ | ----------------------------------------- | 215| unittest | **OpenHarmonyTestRunner** object used for test case execution. | **OpenHarmonyTestRunner** or custom runner name. | - s unittest OpenHarmonyTestRunner | 216| class | Test suite or test case to be executed. | {describeName}#{itName}, {describeName} | -s class attributeTest#testAttributeIt | 217| notClass | Test suite or test case that does not need to be executed. | {describeName}#{itName}, {describeName} | -s notClass attributeTest#testAttributeIt | 218| itName | Test case to be executed. | {itName} | -s itName testAttributeIt | 219| timeout | Timeout interval for executing a test case. | Positive integer (unit: ms). If no value is set, the default value **5000** is used. | -s timeout 15000 | 220| breakOnError | Whether to enable break-on-error mode. When this mode is enabled, the test execution process exits if a test assertion failure or error occurs.| **true**/**false** (default value) | -s breakOnError true | 221| random | Whether to execute test cases in random sequence.| **true**/**false** (default value) | -s random true | 222| testType | Type of the test case to be executed. | function, performance, power, reliability, security, global, compatibility, user, standard, safety, resilience| -s testType function | 223| level | Level of the test case to be executed. | 0, 1, 2, 3, 4 | -s level 0 | 224| size | Size of the test case to be executed. | small, medium, large | -s size small 225| stress | Number of times that the test case is executed. | Positive integer | -s stress 1000 | 226 227**Running Commands** 228 229> **NOTE** 230> 231>Parameter configuration and commands are based on the stage model. 232 233 234Example 1: Execute all test cases. 235 236```shell 237 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner 238``` 239 240Example 2: Execute cases in the specified test suites, separated by commas (,). 241 242```shell 243 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class s1,s2 244``` 245 246Example 3: Execute specified cases in the specified test suites, separated by commas (,). 247 248```shell 249 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s class testStop#stop_1,testStop1#stop_0 250``` 251 252Example 4: Execute all test cases except the specified ones, separated by commas (,). 253 254```shell 255 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s notClass testStop 256``` 257 258Example 5: Execute specified test cases, separated by commas (,). 259 260```shell 261 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s itName stop_0 262``` 263 264Example 6: Set the timeout interval for executing a test case. 265 266```shell 267 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s timeout 15000 268``` 269 270Example 7: Enable break-on-error mode. 271 272```shell 273 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s breakOnError true 274``` 275 276Example 8: Execute test cases of the specified type. 277 278```shell 279 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s testType function 280``` 281 282Example 9: Execute test cases at the specified level. 283 284```shell 285 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s level 0 286``` 287 288Example 10: Execute test cases with the specified size. 289 290```shell 291 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s size small 292``` 293 294Example 11: Execute test cases for a specified number of times. 295 296```shell 297 hdc shell aa test -b xxx -m xxx -s unittest OpenHarmonyTestRunner -s stress 1000 298``` 299 300**Viewing the Test Result** 301 302- During test execution in the CLI, the log information similar to the following is displayed: 303 304 ``` 305 OHOS_REPORT_STATUS: class=testStop 306 OHOS_REPORT_STATUS: current=1 307 OHOS_REPORT_STATUS: id=JS 308 OHOS_REPORT_STATUS: numtests=447 309 OHOS_REPORT_STATUS: stream= 310 OHOS_REPORT_STATUS: test=stop_0 311 OHOS_REPORT_STATUS_CODE: 1 312 313 OHOS_REPORT_STATUS: class=testStop 314 OHOS_REPORT_STATUS: current=1 315 OHOS_REPORT_STATUS: id=JS 316 OHOS_REPORT_STATUS: numtests=447 317 OHOS_REPORT_STATUS: stream= 318 OHOS_REPORT_STATUS: test=stop_0 319 OHOS_REPORT_STATUS_CODE: 0 320 OHOS_REPORT_STATUS: consuming=4 321 ``` 322 323| Log Field | Description | 324| ------- | -------------------------| 325| OHOS_REPORT_SUM | Total number of test cases in the current test suite.| 326| OHOS_REPORT_STATUS: class | Name of the test suite that is being executed.| 327| OHOS_REPORT_STATUS: id | Case execution language. The default value is JS. | 328| OHOS_REPORT_STATUS: numtests | Total number of test cases in the test package.| 329| OHOS_REPORT_STATUS: stream | Error information of the current test case.| 330| OHOS_REPORT_STATUS: test| Name of the current test case.| 331| OHOS_REPORT_STATUS_CODE | Execution result of the current test case. **0**: pass.<br>**1**: error.<br>**2**: fail.| 332| OHOS_REPORT_STATUS: consuming | Time spent in executing the current test case, in milliseconds.| 333 334- After the commands are executed, the following log information is displayed: 335 336 ``` 337 OHOS_REPORT_RESULT: stream=Tests run: 447, Failure: 0, Error: 1, Pass: 201, Ignore: 245 338 OHOS_REPORT_CODE: 0 339 340 OHOS_REPORT_RESULT: breakOnError model, Stopping whole test suite if one specific test case failed or error 341 OHOS_REPORT_STATUS: taskconsuming=16029 342 343 ``` 344 345| Log Field | Description | 346| ------------------| -------------------------| 347| run | Total number of test cases in the current test package.| 348| Failure | Number of failed test cases.| 349| Error | Number of test cases whose execution encounters errors. | 350| Pass | Number of passed test cases.| 351| Ignore | Number of test cases not yet executed.| 352| taskconsuming| Total time spent in executing the current test case, in milliseconds.| 353 354> **NOTE** 355> 356> When an error occurs in break-on-error mode, check the **Ignore** and interrupt information. 357 358## Executing Tests Based on Shell Commands 359 360During development, you can use shell commands to quickly perform operations such as screenshot capturing, screen recording, UI injection simulation, and component tree obtaining. 361 362> **NOTE** 363> 364> Before running commands in the CLI, make sure hdc-related environment variables have been configured. 365 366**Commands** 367| Command | Parameter |Description | 368|---------------|---------------------------------|---------------------------------| 369| help | help| Displays the commands supported by the uitest tool. | 370| screenCap |[-p] | Captures the current screen. This parameter is optional.<br>The file can be stored only in **/data/local/tmp/** by default.<br>The file name is in the format of **Timestamp + .png**.| 371| dumpLayout |[-p] \<-i \| -a>|Obtains the component tree when the daemon is running.<br> **-p**: specifies the path and name of the file, which can be stored only in **/data/local/tmp/** by default. The file name is in the format of **Timestamp + .json**.<br> **-i**: disables filtering of invisible components and window merging.<br> **-a**: stores the data of the **BackgroundColor**, **Content**, **FontColor**, **FontSize** and **extraAttrs** attributes.<br> The preceding attribute data is not saved by default.<br> The **-a** and **-i** parameters cannot be used at the same time.| 372| uiRecord | uiRecord \<record \| read>|Records UI operations.<br> **record**: starts recording the operations on the current page to **/data/local/tmp/record.csv**. To stop recording, press **Ctrl+C**.<br> **read**: Reads and prints recorded data.<br>For details about the parameters, see [Recording User Operations](#recording-user-operations).| 373| uiInput | \<help \| click \| doubleClick \| longClick \| fling \| swipe \| drag \| dircFling \| inputText \| keyEvent>| Injects simulated UI operations.<br>For details about the parameters, see [Injecting Simulated UI Operations](#injecting-simulated-ui-operations). | 374| --version | --version|Obtains the version information about the current tool. | 375| start-daemon|start-daemon| Starts the uitest process.| 376 377### Example of Capturing Screenshots 378 379```bash 380# Specify the file name in the format of Timestamp + .png. 381hdc shell uitest screenCap 382# Save the file in /data/local/tmp/. 383hdc shell uitest screenCap -p /data/local/tmp/1.png 384``` 385 386### Example of Obtaining the Component Tree 387 388```bash 389hdc shell uitest dumpLayout -p /data/local/tmp/1.json 390``` 391 392### Recording User Operations 393>**NOTE** 394> 395> During the recording, you should perform the next operation after the recognition result of the current operation is displayed in the command line. 396 397```bash 398# Record the operations on the current page to **/data/local/tmp/record.csv**. To stop the recording, press **Ctrl+C**. 399hdc shell uitest uiRecord record 400# Read and print record data. 401hdc shell uitest uiRecord read 402``` 403 404The following describes the fields in the recording data: 405 406 ``` 407 { 408 "ABILITY": "com.ohos.launcher.MainAbility", // Foreground application page. 409 "BUNDLE": "com.ohos.launcher", // Application. 410 "CENTER_X": "", // Reserved field. 411 "CENTER_Y": "", // Reserved field. 412 "EVENT_TYPE": "pointer", // 413 "LENGTH": "0", // Total length. 414 "OP_TYPE": "click", // Event type. Currently, click, double-click, long-press, drag, pinch, swipe, and fling types are supported. 415 "VELO": "0.000000", // Hands-off velocity. 416 "direction.X": "0.000000",// Movement along the x-axis. 417 "direction.Y": "0.000000", // Movement along the y-axis. 418 "duration": 33885000.0, // Gesture duration. 419 "fingerList": [{ 420 "LENGTH": "0", // Total length. 421 "MAX_VEL": "40000", // Maximum velocity. 422 "VELO": "0.000000", // Hands-off velocity. 423 "W1_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Starting component bounds. 424 "W1_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Starting component hierarchy. 425 "W1_ID": "", // ID of the starting component. 426 "W1_Text": "", // Text of the starting component. 427 "W1_Type": "Image", // Type of the starting component. 428 "W2_BOUNDS": "{"bottom":361,"left":37,"right":118,"top":280}", // Ending component bounds. 429 "W2_HIER": "ROOT,3,0,0,0,0,0,0,0,0,5,0,0,0,0,0,0,0", // Ending component hierarchy. 430 "W2_ID": "", // ID of the ending component. 431 "W2_Text": "", // Text of the ending component. 432 "W2_Type": "Image", // Type of the ending component. 433 "X2_POSI": "47", // X coordinate of the ending point. 434 "X_POSI": "47", // X coordinate of the starting point. 435 "Y2_POSI": "301", // Y coordinate of the ending point. 436 "Y_POSI": "301", // Y coordinate of the starting point. 437 "direction.X": "0.000000", // Movement along the x-axis. 438 "direction.Y": "0.000000" // Movement along the y-axis. 439 }], 440 "fingerNumber": "1" // Number of fingers. 441 } 442 ``` 443 444### Injecting Simulated UI Operations 445 446| Command | Mandatory| Description | 447|------|------|-----------------| 448| help | Yes | Displays help information about the uiInput commands.| 449| click | Yes | Simulates a click event. | 450| doubleClick | Yes | Simulates a double-click event. | 451| longClick | Yes | Simulates a long-click event. | 452| fling | Yes | Simulates a fling event. | 453| swipe | Yes | Simulates a swipe event. | 454| drag | Yes | Simulates a drag event. | 455| dircFling | Yes | Simulates a directional fling event. | 456| inputText | Yes | Simulates text input in a text box at specified coordinates. | 457| text | Yes | Simulates text input in a text box at the focused position without specifying coordinates. | 458| keyEvent | Yes | Simulates a physical key event (such as pressing a keyboard key, pressing the power key, returning to the previous page, or returning to the home screen) or a key combination. | 459 460 461#### Example of Running the click/doubleClick/longClick Commands 462 463| Parameter | Mandatory| Description | 464|---------|------|-----------------| 465| point_x | Yes | The x-coordinate point to click.| 466| point_y | Yes | The y-coordinate point to click.| 467 468```shell 469# Execute the click event. 470hdc shell uitest uiInput click 100 100 471 472# Execute the double-click event. 473hdc shell uitest uiInput doubleClick 100 100 474 475# Execute a long-click event. 476hdc shell uitest uiInput longClick 100 100 477``` 478 479#### Example of Running the uiInput fling Command 480 481| Parameter | Mandatory | Description | 482|------|------------------|-----------------| 483| from_x | Yes | The x-coordinate of the start point.| 484| from_y | Yes | The y-coordinate of the start point.| 485| to_x | Yes | The x-coordinate of the stop point.| 486| to_y | Yes | The y-coordinate of the stop point.| 487| swipeVelocityPps_ | No | Swipe speed, in px/s. The value ranges from 200 to 40000.<br> The default value is **600**.| 488| stepLength_ | No| Step length. The default value is the swipe distance divided by 50.<br> To achieve better simulation effect, you are advised to use the default value. | 489 490 491```shell 492# Execute the fling event. The default value of stepLength_ is used. 493hdc shell uitest uiInput fling 10 10 200 200 500 494``` 495 496#### Example of Running the uiInput swipe/drag Command 497 498| Parameter | Mandatory | Description | 499|------|------------------|-----------------| 500| from_x | Yes | The x-coordinate of the start point.| 501| from_y | Yes | The y-coordinate of the start point.| 502| to_x | Yes | The x-coordinate of the stop point.| 503| to_y | Yes | The y-coordinate of the stop point.| 504| swipeVelocityPps_ | No | Swipe speed, in px/s. Value range: 200 to 40000.<br> The default value is 600.| 505 506```shell 507# Execute the swipe event. 508hdc shell uitest uiInput swipe 10 10 200 200 500 509 510# Execute the drag event. 511hdc shell uitest uiInput drag 10 10 100 100 500 512``` 513 514#### Example of Running the uiInput dircFling Command 515 516| Parameter | Mandatory | Description| 517|-------------------|-------------|----------| 518| direction | No| Fling direction, which can be **0**, **1**, **2**, or **3**. The default value is **0**.<br> The value **0** indicates leftward fling, **1** indicates rightward fling, **2** indicates upward fling, and **3** indicates downward fling. | 519| swipeVelocityPps_ | No| Swipe speed, in px/s. Value range: 200 to 40000.<br> The default value is 600. | 520| stepLength | No | Step length.<br> The default value is the swipe distance divided by 50. To achieve better simulation effect, you are advised to use the default value.| 521 522```shell 523# Execute the leftward fling event. 524hdc shell uitest uiInput dircFling 0 500 525# Execute the rightward fling event. 526hdc shell uitest uiInput dircFling 1 600 527# Execute the upward fling event. 528hdc shell uitest uiInput dircFling 2 529# Execute the downward fling event. 530hdc shell uitest uiInput dircFling 3 531``` 532 533#### Example of Running the uiInput inputText Command 534 535| Parameter | Mandatory | Description| 536|------|------------------|----------| 537| point_x | Yes | The x-coordinate of the input box.| 538| point_y | Yes | The y-coordinate of the input box.| 539| text | Yes | Text in the input box. | 540 541```shell 542# Execute the input text event. 543hdc shell uitest uiInput inputText 100 100 hello 544``` 545 546#### Example of Running the uiInput text Command 547 548| Parameter | Mandatory | Description| 549|------|------------------|----------| 550| text | Yes | Text in the input box. | 551 552```shell 553# Execute the text input in the text box at the focused position. If the current focused position does not support text input, no effect is displayed. 554hdc shell uitest uiInput text hello 555``` 556 557#### Example of Running the uiInput keyEvent Command 558 559| Parameter | Mandatory | Description| 560|------|------|----------| 561| keyID1 | Yes | ID of a physical key, which can be **KeyCode**, **Back**, **Home**, or **Power**.<br>When the value is set to **Back**, **Home**, or **Power**, the combination keys are not supported.| 562| keyID2 | No | ID of a physical key.| 563| keyID3 | No | ID of a physical key.| 564 565>**NOTE** 566> 567> A maximum of three key values can be passed. <!--RP3-->For details about the key values, see [KeyCode](../reference/apis-input-kit/js-apis-keycode.md)<!--RP3End-->. 568 569```shell 570# Back to home page. 571hdc shell uitest uiInput keyEvent Home 572# Back to the last page. 573hdc shell uitest uiInput keyEvent Back 574# Perform a key combination to copy and paste text. 575hdc shell uitest uiInput keyEvent 2072 2038 576``` 577 578### Obtaining the Version Information 579 580```bash 581hdc shell uitest --version 582``` 583### Starting the Uitest Process 584 585```shell 586hdc shell uitest start-daemon 587``` 588 589>**NOTE** 590> 591> You need to enable the developer mode for the device. 592> 593> Only the test HAP started by the **aa test** ability can call the ability of the UiTest. 594> 595> The <!--RP4End-->[Ability Privilege Level (APL)](../security/AccessToken/app-permission-mgmt-overview.md#basic-concepts-in-the-permission-mechanism) of the <!--RP4End-->test HAP must be **system_basic** or **normal**. 596 597<!--Del--> 598## Examples 599 600### Unit Test Scripts 601 602#### Using Assertion APIs of the Unit Test 603For details about how to use the available APIs, see [Example of Using Assertion APIs](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/assertExampleTest/assertExample.test.ets). 604 605#### Defining Unit Test Suites 606For details about how to define and nest the unit test suite, see [Example of Defining Test Suites](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/coverExampleTest/coverExample.test.ets). 607 608#### Testing Custom Application Functions Using Unit Test 609For details about how to test the custom functions in an application, see [Example of Testing Custom Application Functions](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/customExampleTest/customExample.test.ets). 610 611#### Using Data-Driven Capability of the Unit Test 612For details about how to use the data-driven capability and configure repeat script execution, see [Example of Using Data-Driven Capability](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/jsunit/entry/src/ohosTest/ets/test/paramExampleTest/paramExample.test.ets). 613 614### UI Test Scripts for Components 615 616#### Searching for Specified Components 617For details about how to search for a component in an application UI by specifying the attributes of the component, see [Example of Searching for Specified Components](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/Component/findCommentExample.test.ets). 618 619#### Simulating Click Events 620For details about how to simulate a click event, a long-click event or a double-click event, see [Example of Simulating Click Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/clickEvent.test.ets). 621 622#### Simulating Mouse Events 623For details about how to simulate a mouse left-click event, a mouse right-click event, or a mouse scroll wheel event, see [Example of Simulating Mouse Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/MouseEvent.test.ets). 624 625#### Simulating Input Events 626For details about how to simulate the input of Chinese and English text, see [Example of Simulating Input Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/InputEvent.test.ets). 627 628#### Simulating Screenshot Events 629For details about how to simulate capturing a screenshot (in a specified area), see [Example of Simulating Screenshot Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScreenCapEvent.test.ets). 630 631#### Simulating Fling Events 632For details about how to simulate a fling event (the finger leaves the screen after sliding), see [Example of Simulating Fling Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/FlingEvent.test.ets). 633 634#### Simulating Swipe Events 635For details about how to simulate a swipe event (the finger stays on the screen after sliding), see [Example of Simulating Swipe Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/SwipeEvent.test.ets). 636 637#### Simulating Pinch Events 638For details about how to simulate a zoom-in and zoom-out operation on pictures, see [Example of Simulating Pinch Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/PinchEvent.test.ets). 639 640#### Simulating Scroll Events 641For details about how to simulate components scrolling, see [Example of Simulating Scroll Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/ui/ScrollerEvent.test.ets). 642 643### UI Test Scripts for Windows 644 645#### Searching for Specified Windows 646For details about how to search for an application window by using the bundle name of the application, see [Example of Searching for Specified Windows](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/findCommentExampleTest/window/findWindowExample.test.ets). 647 648#### Simulating Window Move Events 649For details about how to simulate moving a window to a specified position, see [Example of Simulating Window Move Events](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/MoveToEvent.test.ets). 650 651#### Simulating Window Size Adjustments 652For details about how to simulate a window size adjustment and direction specification, see [Example of Simulating Window Size Adjustments](https://gitee.com/openharmony/applications_app_samples/blob/master/code/Project/Test/uitest/entry/src/ohosTest/ets/test/operationExampleTest/window/ReSizeWindow.test.ets). 653 654<!--DelEnd--> 655 656## FAQs 657 658### FAQs About Unit Test Cases 659 660**1. What should I do if logs in the test case are printed after the test case result?** 661 662**Problem** 663 664The logs added to the test case are displayed after the test case execution, rather than during the test case execution. 665 666**Possible Causes** 667 668More than one asynchronous API is called in the test case.<br>In principle, logs in the test case are printed before the test case execution is complete. 669 670**Solutions** 671 672If more than one asynchronous API is called, you are advised to encapsulate the API invoking into the promise mode. 673 674**2. What should I do if the message "error: fail to start ability" is reported during test case execution?** 675 676**Problem** 677 678When a test case is executed, the console returns the error message "fail to start ability". 679 680**Possible Causes** 681 682An error occurs during the packaging of the test package, and the test framework dependency file is not included in the test package. 683 684**Solutions** 685 686Check whether the test package contains the **OpenHarmonyTestRunner.abc** file. If the file does not exist, rebuild and pack the file and perform the test again. 687 688**3. What should I do if a timeout error is reported during case execution?** 689 690**Problem** 691 692After the test case execution is complete, the console displays the error message "execute time XXms", indicating that the case execution times out. 693 694**Possible Causes** 695 6961. The test case is executed through an asynchronous API, but the **done** function is not executed during the execution. As a result, the test case execution does not end until it times out. 697 6982. The time taken for API invocation is longer than the timeout interval set for test case execution. 699 7003. Test assertion fails, and a failure exception is thrown. As a result, the test case execution does not end until it times out. 701 702**Solutions** 703 7041. Check the code logic of the test case to ensure that the **done** function is executed even if the assertion fails. 705 7062. Modify the case execution timeout settings under **Run/Debug Configurations** in DevEco Studio. 707 7083. Check the code logic and assertion result of the test case and make sure that the assertion is passed. 709### FAQs About UI Test Cases 710 711**1. What should I do if the failure log contains "Get windows failed/GetRootByWindow failed"?** 712 713**Problem** 714 715The UI test case fails to be executed. The HiLog file contains the error message "Get windows failed/GetRootByWindow failed." 716 717**Possible Causes** 718 719The ArkUI feature is disabled. As a result, the component tree information is not generated on the test page. 720 721**Solutions** 722 723Run the following command, restart the device, and execute the test case again: 724 725```shell 726hdc shell param set persist.ace.testmode.enabled 1 727``` 728 729**2. What should I do if the failure log contains "uitest-api does not allow calling concurrently"?** 730 731**Problem** 732 733The UI test case fails to be executed. The HiLog file contains the error message "uitest-api does not allow calling concurrently." 734 735**Possible Causes** 736 7371. In the test case, the **await** operator is not added to the asynchronous API provided by the UI test framework. 738 7392. The UI test case is executed in multiple processes. As a result, multiple UI test processes are started. The framework does not support multi-process invoking. 740 741**Solutions** 742 7431. Check the case implementation and add the **await** operator to the asynchronous API. 744 7452. Do not execute UI test cases in multiple processes. 746 747**3. What should I do if the failure log contains "does not exist on current UI! Check if the UI has changed after you got the widget object"?** 748 749**Problem** 750 751The UI test case fails to be executed. The HiLog file contains the error message "does not exist on current UI! Check if the UI has changed after you got the widget object." 752 753**Possible Causes** 754 755After the target component is found in the code of the test case, the device UI changes, resulting in loss of the found component and inability to perform emulation. 756 757**Solutions** 758 759Run the UI test case again. 760