### Define Test Suite using describe in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt The `describe` function creates a test suite to group related test cases. It supports setup and teardown hooks like `beforeAll` and `afterAll` for managing test state. This example demonstrates basic setup, teardown, and assertion within a suite. ```typescript import { describe, it, expect, beforeAll, afterAll } from '@ohos/hypium'; export default function abilityTest() { describe('ActsAbilityTest', function () { beforeAll(function () { // Setup code runs once before all tests console.info('test suite setup'); }); afterAll(function () { // Cleanup code runs once after all tests console.info('test suite teardown'); }); it('testCase001', 0, function () { let result = 2 + 2; expect(result).assertEqual(4); }); it('testCase002', 0, function () { let text = 'hello'; expect(text).assertContain('ell'); }); }); } ``` -------------------------------- ### Mocking Functions with JsUnit (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Demonstrates how to use JsUnit's MockKit to mock a class method and define its return value using `afterReturn`. This example shows the setup, mocking process, and assertion for a mocked function. ```javascript import {describe, expect, it, MockKit, when} from '@ohos/hypium'; export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('testMockfunc', 0, function () { console.info("it1 begin"); // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Define the ClassName class, which contains two functions, and then create a claser object. class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); // 3. Mock method_1 of the ClassName class. let mockfunc = mocker.mockFunc(claser, claser.method_1); when(mockfunc)('test').afterReturn('1'); // 4. Assert whether the mocked function is implemented as expected. // The operation is successful if 'test' is passed in. expect(claser.method_1('test')).assertEqual('1'); // The operation is successful. // The operation fails if 'abc' is passed in. //expect(claser.method_1('abc')).assertEqual('1'); // The operation fails. }); }); } ``` -------------------------------- ### JsUnit Basic Process Support Example (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This JavaScript code demonstrates the basic process support of JsUnit for writing and executing test cases. It utilizes `describe` to define a test suite and `it` to specify individual test cases. The example also shows the use of `expect` for assertions and an asynchronous test case involving `getBundleInfo` from the '@ohos.bundle' module. ```javascript import { describe, beforeAll, beforeEach, afterEach, afterAll, it, expect } from '@ohos/hypium' import demo from '@ohos.bundle' export default async function abilityTest() { describe('ActsAbilityTest', function () { it('String_assertContain_success', 0, function () { let a = 'abc' let b = 'b' expect(a).assertContain(b) expect(a).assertEqual(a) }) it('getBundleInfo_0100', 0, async function () { const NAME1 = "com.example.MyApplicationStage" await demo.getBundleInfo(NAME1, demo.BundleFlag.GET_BUNDLE_WITH_ABILITIES | demo.BundleFlag.GET_BUNDLE_WITH_REQUESTED_PERMISSION) .then((value) => { console.info(value.appId) }) .catch((err) => { console.info(err.code) }) }) }) } ``` -------------------------------- ### Basic UiTest Example (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Demonstrates a basic UI test case using UiTest. It initializes a UiDriver, finds a component by its text attribute, simulates a click on the component, and asserts that the component's text has changed. This example highlights the asynchronous nature of UiDriver and UiComponent APIs, requiring the use of 'await'. ```javascript import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '@ohos/hypium' import {BY, UiDriver, UiComponent, MatchPattern} from '@ohos.uitest' export default async function abilityTest() { describe('uiTestDemo', function() { it('uitest_demo0', 0, async function() { // create UiDriver let driver = await UiDriver.create() // find component by text let button = await driver.findComponent(BY.text('hello').enabled(true)) // click component await button.click() // get and assert component text let content = await button.getText() expect(content).assertEquals('clicked!') }) }) } ``` -------------------------------- ### Mocking Asynchronous Functions Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Provides an example of how to mock asynchronous functions using MockKit. This snippet is intended to show the setup for handling promises or other asynchronous operations, though the specific implementation details for async mocking are not fully detailed in the provided text. ```javascript // Example 10: Mock asynchronous functions. ``` -------------------------------- ### TypeScript - Test Setup and Teardown Hooks Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Defines `beforeEach` and `afterEach` hooks for running code before and after each test case within a suite. These are useful for initializing test state or cleaning up resources. Dependencies include '@ohos/hypium'. They take callback functions as arguments. ```typescript import { describe, beforeEach, afterEach, it, expect } from '@ohos/hypium'; export default function hookTest() { describe('HookTest', function () { let testData: number; beforeEach(function () { // Runs before each test case testData = 0; console.info('beforeEach: testData initialized to 0'); }); afterEach(function () { // Runs after each test case console.info('afterEach: testData was ' + testData); testData = -1; }); it('test_increment', 0, function () { testData += 1; expect(testData).assertEqual(1); }); it('test_double', 0, function () { testData = 10; testData *= 2; expect(testData).assertEqual(20); }); }); } ``` -------------------------------- ### Mocking a System API with afterReturn Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This example illustrates how to mock a system API, specifically 'app.getInfo()', using MockKit. It demonstrates setting a return value for the mocked function and then asserting that the mocked function returns the expected value. ```javascript export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('test_systemApi', 0, function () { // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Mock the app.getInfo() function. let mockf = mocker.mockFunc(app, app.getInfo); when(mockf)('test').afterReturn('1'); // The operation is successful. expect(app.getInfo('test')).assertEqual('1'); }); }); } ``` -------------------------------- ### Install arkXtest Dependency in oh-package.json5 Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This JSON snippet shows how to add the '@ohos/hypium' dependency to your project's oh-package.json5 file to use the arkXtest framework. After adding the dependency, run 'ohpm install' to fetch the package. ```json { "dependencies": { "@ohos/hypium": "^1.0.0" } } ``` -------------------------------- ### Verify Mocked Function Calls (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Illustrates how to mock multiple methods of a class and then use `mocker.verify()` to check if these methods were called with specific arguments and with a certain frequency. This example highlights verification of call counts. ```javascript import {describe, expect, it, MockKit, when} from '@ohos.hypium'; export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('testMockfunc', 0, function () { console.info("it1 begin"); // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Define the ClassName class, which contains two functions, and then create a claser object. class ClassName { constructor() { } method_1(...arg) { return '888888'; } method_2(...arg) { return '999999'; } } let claser = new ClassName(); // 3. Mock method_1 and method_2 of the ClassName class. mocker.mockFunc(claser, claser.method_1); mocker.mockFunc(claser, claser.method_2); // 4. Call the following methods. claser.method_1('abc', 'ppp'); claser.method_1('abc'); claser.method_1('xyz'); claser.method_1(); claser.method_1('abc', 'xxx', 'yyy'); claser.method_1(); claser.method_2('111'); claser.method_2('111', '222'); //5. Verify the mocked functions. mocker.verify('method_1', []).atLeast(3); // The result is "failed". // Verify whether 'method_1' with an empty parameter list was executed at least three times. // The result is "failed" because 'method_1' with an empty parameter list was executed only twice in Step 4. //mocker.verify('method_2',['111']).once(); // The result is "success". //mocker.verify('method_2',['111',,'222']).once(); // The result is "success". }); }); } ``` -------------------------------- ### UiWindow Class Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md The UiWindow class represents a window object, providing APIs to get window attributes, drag windows, and adjust window sizes. ```APIDOC ## UiWindow Class ### Description The `UiWindow` class provides functionalities to manage and interact with application windows. You can obtain window properties, perform window manipulation actions like dragging, and resize windows. ### Methods * **`getAttributes(): Promise`** * **Description**: Retrieves the attributes of the window. * **Returns**: A `Promise` that resolves to an object containing the window's attributes. * **`drag(x1: number, y1: number, x2: number, y2: number): Promise`** * **Description**: Drags the window from a starting point (x1, y1) to an ending point (x2, y2). * **Parameters**: * `x1` (number) - Required - The starting x-coordinate. * `y1` (number) - Required - The starting y-coordinate. * `x2` (number) - Required - The ending x-coordinate. * `y2` (number) - Required - The ending y-coordinate. * **`resize(width: number, height: number): Promise`** * **Description**: Resizes the window to the specified width and height. * **Parameters**: * `width` (number) - Required - The target width of the window. * `height` (number) - Required - The target height of the window. ### Usage Example ```javascript import { UiDriver } from '@ohos.uitest'; // Assuming 'driver' is an initialized UiDriver object // const driver = await UiDriver.create(); // Define a filter to find a specific window (e.g., by title) // const windowFilter = { title: 'My App Window' }; // Find the window // const myWindow = await driver.findWindow(windowFilter); // Interact with the window // await myWindow.drag(100, 100, 200, 200); // await myWindow.resize(800, 600); // const attributes = await myWindow.getAttributes(); ``` ``` -------------------------------- ### Hypium.setData: Configure Data-Driven Testing in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Demonstrates how to set up data-driven tests using Hypium.setData by loading test parameters from a JSON configuration file. This allows a single test case to be executed multiple times with different input data. The example shows the structure of the data.json file and how to import and use it within an application's onCreate method. It requires Hypium from '@ohos/hypium', abilityDelegatorRegistry, and the test suite definition. ```json // data.json { "suites": [{ "describe": ["actsAbilityTest"], "stress": 2, "params": { "suiteParams1": "suiteParams001", "suiteParams2": "suiteParams002" }, "items": [{ "it": "testDataDriverAsync", "stress": 2, "params": [{ "name": "tom", "value": 5 }, { "name": "jerry", "value": 4 }] }, { "it": "testDataDriver", "stress": 3 }] }] } ``` ```typescript // app.ets import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; import { Hypium } from '@ohos/hypium'; import testsuite from '../test/List.test'; import data from '../test/data.json'; export default { onCreate() { console.info('Application onCreate'); const abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); const abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments(); // Load data-driven configuration Hypium.setData(data); Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite); } }; ``` ```typescript // test.ets import { describe, it, expect } from '@ohos/hypium'; export default function abilityTest() { describe('actsAbilityTest', function () { it('testDataDriverAsync', 0, async function (done, data) { // Data from data.json params array console.info('name: ' + data.name); console.info('value: ' + data.value); expect(data.value).assertLarger(0); done(); }); it('testDataDriver', 0, function () { console.info('stress test execution'); expect(true).assertTrue(); }); }); } ``` -------------------------------- ### Verifying Minimum Function Call Count with atLeast() Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This example demonstrates how to use MockKit's 'atLeast(count)' method to verify that a mocked function has been called at least a specified number of times. It mocks 'ClassName.method_1' and then checks if it was invoked a minimum of times. ```javascript import { describe, expect, it, MockKit, when } from '@ohos/hypium' export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('test_verify_atLeast', 0, function () { // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Define the class to be mocked. class ClassName { constructor() { } method_1(...arg) { return '888888'; } } // 3. Create an object of the class. let claser = new ClassName(); // 4. Mock a function, for example, method_1, of the object. let func_1 = mocker.mockFunc(claser, claser.method_1); // 5. Set the expected value to be returned by the mocked function. when(func_1)('123').afterReturn('4'); // 6. Execute the function several times, with parameters set as follows: claser.method_1('123', 'ppp'); claser.method_1('abc'); claser.method_1('xyz'); claser.method_1(); claser.method_1('abc', 'xxx', 'yyy'); claser.method_1(); ``` -------------------------------- ### Mock Function with Any String Parameter using ArkUI-XTest Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This snippet illustrates mocking a function to accept any string argument using `ArgumentMatchers.anyString`. It sets up a mock for `method_1` and expects it to return '1' when any string is provided. The code implies that assertions would follow to verify this behavior, similar to other examples. ```javascript import {describe, expect, it, MockKit, when, ArgumentMatchers} from '@ohos/hypium'; export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('testMockfunc', 0, function () { console.info("it1 begin"); // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Define the ClassName class, which contains two functions, and then create a claser object. class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); // 3. Mock method_1 of the ClassName class. ``` -------------------------------- ### Mock Function with Any Parameter Type using ArkUI-XTest Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This example demonstrates mocking a function to accept any parameter type except undefined or null using `ArgumentMatchers.any`. It requires importing `ArgumentMatchers` and then using it within the `when` condition. The code asserts that the mocked function returns '1' regardless of whether a string, number, or boolean is passed as an argument. ```javascript import {describe, expect, it, MockKit, when, ArgumentMatchers} from '@ohos/hypium'; export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('testMockfunc', 0, function () { console.info("it1 begin"); // 1. Create a MockKit object. let mocker = new MockKit(); // 2. Define the ClassName class, which contains two functions, and then create a claser object. class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); // 3. Mock method_1 of the ClassName class. let mockfunc = mocker.mockFunc(claser, claser.method_1); // Set the parameter matcher and expected return value as required. when(mockfunc)(ArgumentMatchers.any).afterReturn('1'); // 4. Assert whether the mocked function is implemented as expected. // The operation is successful if a string is passed in. expect(claser.method_1('test')).assertEqual('1'); // The operation is successful. // The operation is successful if a number (for example '123') is passed in. expect(claser.method_1(123)).assertEqual('1'); // The operation is successful. // The operation is successful if a Boolean value (for example 'true') is passed in. expect(claser.method_1(true)).assertEqual('1');// The operation is successful. // The operation fails if an empty value is passed in. //expect(claser.method_1()).assertEqual('1');// The operation fails. }); }); } ``` -------------------------------- ### ArgumentMatchers: Match by Regex Pattern in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Shows how to use ArgumentMatchers.matchRegexs to match string arguments based on a regular expression. This allows for more specific validation of string inputs in mock scenarios. The example uses a regex to check if the input string matches a specific pattern. It requires MockKit and ArgumentMatchers from '@ohos/hypium'. ```typescript import { describe, expect, it, MockKit, when, ArgumentMatchers } from '@ohos/hypium'; export default function matcherTest() { describe('MatcherTest', function () { it('testMatcher_regex', 0, function () { let mocker = new MockKit(); class ClassName { method_1(arg: string): string { return '888888'; } } let claser = new ClassName(); let mockfunc = mocker.mockFunc(claser, claser.method_1); when(mockfunc)(ArgumentMatchers.matchRegexs(/123456/)).afterReturn('1'); // Matches regex pattern expect(claser.method_1('1234567898')).assertEqual('1'); // Doesn't match - returns original behavior expect(claser.method_1('1234')).assertEqual('888888'); mocker.clear(claser); }); }); } ``` -------------------------------- ### Assert Component Existence (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Shows how to use the `assertComponentExist` API from UiTest to verify if a UI component exists on the current screen. This is a crucial assertion method for UI testing, as it throws a JS exception if the component is not found, leading to test case failure. The example wraps the assertion in a try-finally block to ensure `done()` is called. ```javascript import {BY,UiDriver,UiComponent} from '@ohos.uitest' export default async function abilityTest() { describe('UiTestDemo', function() { it('Uitest_demo0', 0, async function(done) { try{ // create UiDriver let driver = await UiDriver.create() // assert text 'hello' exists on current Ui await assertComponentExist(BY.text('hello')) } finally { done() } }) }) } ``` -------------------------------- ### Driver.create - Initialize UI Test Driver Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Initializes the main entry point for UI testing. The Driver object provides methods for finding components, injecting events, and capturing screenshots. ```APIDOC ## Driver.create - Initialize UI Test Driver ### Description Creates the main entry point for UI testing. Driver provides methods for finding components, injecting events, and capturing screenshots. ### Method `POST` (implicitly, as `Driver.create()` is a static factory method) ### Endpoint N/A (Static method) ### Parameters None ### Request Example ```typescript import { Driver } from '@kit.TestKit'; let driver: Driver = Driver.create(); ``` ### Response #### Success Response (200) - **driver** (Driver) - An instance of the UI Test Driver. #### Response Example ```typescript (Conceptual) // driver object is returned and can be used for further operations ``` ``` -------------------------------- ### Driver.create - Initialize UI Test Driver (TypeScript) Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Initializes the main entry point for UI testing in ArkUI. The Driver class provides essential methods for finding components, injecting events, and capturing screenshots. It requires '@ohos/hypium' for testing utilities and '@kit.TestKit' for driver functionalities. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { Driver, ON, Component } from '@kit.TestKit'; import { abilityDelegatorRegistry } from '@kit.TestKit'; export default function uiTest() { describe('UiTestDemo', function () { it('uitest_create_driver', 0, async function () { // Create Driver instance let driver: Driver = Driver.create(); // Verify driver is ready await driver.delayMs(1000); console.info('Driver created successfully'); }); it('uitest_component_click', 0, async function () { let driver: Driver = Driver.create(); // Find button by text and click it let button: Component = await driver.findComponent(ON.text('Submit')); await button.click(); // Wait for UI to update await driver.delayMs(500); // Assert success message appears await driver.assertComponentExist(ON.text('Success')); }); }); } ``` -------------------------------- ### UiDriver API Documentation Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Documentation for the UiDriver class, which serves as the main entry point for UiTest. It provides APIs for component matching, key injection, coordinate operations, and screenshots. ```APIDOC ## UiDriver API Documentation ### Description The `UiDriver` class is the primary interface for interacting with the UI in test scenarios. It offers a comprehensive set of functionalities for UI testing, including finding components, simulating user interactions, and capturing screen content. ### Methods * **`create(): Promise`** * **Description**: Creates and returns a new `UiDriver` object. This is a static method and the entry point for initializing the driver. * **Type**: Static Method * **`findComponent(b: By): Promise`** * **Description**: Searches for a UI component based on the criteria defined by the `By` object. * **Parameters**: * `b` (By) - Required - An object specifying the attributes to match for the component. * **Returns**: A `Promise` that resolves to a `UiComponent` object if found. * **`pressBack(): Promise`** * **Description**: Simulates a back button press on the device or emulator. * **`click(x: number, y: number): Promise`** * **Description**: Performs a click action at the specified screen coordinates (x, y). * **Parameters**: * `x` (number) - Required - The x-coordinate for the click. * `y` (number) - Required - The y-coordinate for the click. * **`swipe(x1: number, y1: number, x2: number, y2: number): Promise`** * **Description**: Simulates a swipe gesture between two points (x1, y1) and (x2, y2). * **Parameters**: * `x1` (number) - Required - The starting x-coordinate. * `y1` (number) - Required - The starting y-coordinate. * `x2` (number) - Required - The ending x-coordinate. * `y2` (number) - Required - The ending y-coordinate. * **`assertComponentExist(b: By): Promise`** * **Description**: Asserts that a component matching the given `By` criteria exists on the current screen. Throws an error if the component is not found. * **Parameters**: * `b` (By) - Required - An object specifying the attributes to match for the component. * **`delayMs(t: number): Promise`** * **Description**: Pauses the execution of the test for a specified duration in milliseconds. * **Parameters**: * `t` (number) - Required - The delay time in milliseconds. * **`screenCap(s: string): Promise`** * **Description**: Captures the current screen and saves it to the specified path. * **Parameters**: * `s` (string) - Required - The file path to save the screenshot. * **`findWindow(filter: WindowFilter): Promise`** * **Description**: Searches for a window based on the provided filter criteria. * **Parameters**: * `filter` (WindowFilter) - Required - An object specifying the criteria to filter windows. * **Returns**: A `Promise` that resolves to a `UiWindow` object if found. ### Usage Example ```javascript import { BY, UiDriver } from '@ohos.uitest'; export default async function uiTestExample() { describe('UiDriver Usage', function() { it('should find and click a component', async function() { const driver = await UiDriver.create(); const button = await driver.findComponent(BY.text('Login Button')); await button.click(); }); it('should assert component existence', async function() { const driver = await UiDriver.create(); await driver.assertComponentExist(BY.id('username_input')); }); }); } ``` ``` -------------------------------- ### Perform UI Component Interactions with TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Demonstrates various interactions on UI components like clicking, double-clicking, long-clicking, inputting text, scrolling, and performing gestures such as pinch-out. It utilizes the `Driver` and `Component` classes from '@kit.TestKit'. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { Driver, ON, Component } from '@kit.TestKit'; export default function interactionTest() { describe('ComponentInteractionTest', function () { it('component_click', 0, async function () { let driver: Driver = Driver.create(); let button: Component = await driver.findComponent(ON.text('Submit')); // Click the component await button.click(); await driver.delayMs(500); }); it('component_doubleClick', 0, async function () { let driver: Driver = Driver.create(); let item: Component = await driver.findComponent(ON.type('Text')); // Double click the component await item.doubleClick(); }); it('component_longClick', 0, async function () { let driver: Driver = Driver.create(); let item: Component = await driver.findComponent(ON.text('Item 1')); // Long click (press and hold) await item.longClick(); await driver.delayMs(500); }); it('component_inputText', 0, async function () { let driver: Driver = Driver.create(); let input: Component = await driver.findComponent(ON.type('TextInput')); // Clear existing text await input.clearText(); // Input new text await input.inputText('Hello World'); // Verify text was entered let text: string = await input.getText(); expect(text).assertEqual('Hello World'); }); it('component_scroll', 0, async function () { let driver: Driver = Driver.create(); let scrollView: Component = await driver.findComponent(ON.type('Scroll')); // Scroll to search for component let targetItem: Component = await scrollView.scrollSearch(ON.text('Item 50')); expect(await targetItem.isVisible()).assertTrue(); }); it('component_getProperties', 0, async function () { let driver: Driver = Driver.create(); let button: Component = await driver.findComponent(ON.text('Submit')); // Get component properties let text: string = await button.getText(); let type: string = await button.getType(); let isEnabled: boolean = await button.isEnabled(); let isVisible: boolean = await button.isVisible(); let bounds: object = await button.getBounds(); console.info(`Component: ${type}, text: ${text}, enabled: ${isEnabled}`); expect(isEnabled).assertTrue(); }); it('component_pinchOut', 0, async function () { let driver: Driver = Driver.create(); let image: Component = await driver.findComponent(ON.type('Image')); // Pinch out (zoom in) gesture - scale by 1.5x await image.pinchOut(1.5); await driver.delayMs(500); }); }); } ``` -------------------------------- ### Define Data Driven Test Cases Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This example shows how to define test cases that utilize data driving. The 'testDataDriverAsync' case accepts and logs 'name' and 'value' parameters passed from the data.json configuration. The 'testDataDriver' case is a simpler stress test. ```javascript import {describe, beforeAll, beforeEach, afterEach, afterAll, it, expect} from '@ohos/hypium'; export default function abilityTest() { describe('actsAbilityTest', function () { it('testDataDriverAsync', 0, async function (done, data) { console.info('name: ' + data.name); console.info('value: ' + data.value); done(); }); it('testDataDriver', 0, function () { console.info('stress test'); }); }); } ``` -------------------------------- ### Define Test Case using it in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt The `it` function defines an individual test case within a test suite, used for validating specific behaviors. It supports both synchronous and asynchronous test execution. This example shows a synchronous assertion and an asynchronous API call with promise handling. ```typescript import { describe, it, expect } from '@ohos/hypium'; import demo from '@ohos.bundle'; export default function abilityTest() { describe('BundleTest', function () { // Synchronous test it('String_assertContain_success', 0, function () { let a = 'abc'; let b = 'b'; expect(a).assertContain(b); expect(a).assertEqual(a); }); // Asynchronous test it('getBundleInfo_0100', 0, async function () { const NAME1 = "com.example.MyApplicationStage"; await demo.getBundleInfo(NAME1, demo.BundleFlag.GET_BUNDLE_WITH_ABILITIES) .then((value) => { console.info('Bundle appId: ' + value.appId); expect(value.appId).assertInstanceOf('String'); }) .catch((err) => { console.error('Error code: ' + err.code); expect().assertFail(); }); }); }); } ``` -------------------------------- ### Build Component Matchers with ON in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Demonstrates how to use the ON builder to create matching criteria for finding UI components. Supports matching by text, type, enabled state, and chaining multiple conditions. Requires @ohos/hypium and @kit.TestKit. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { Driver, ON, Component } from '@kit.TestKit'; export default function matcherTest() { describe('OnMatcherTest', function () { it('matcher_text', 0, async function () { let driver: Driver = Driver.create(); // Match by exact text let component: Component = await driver.findComponent(ON.text('Login')); expect(await component.getText()).assertEqual('Login'); }); it('matcher_type', 0, async function () { let driver: Driver = Driver.create(); // Match by component type let button: Component = await driver.findComponent(ON.type('Button')); console.info('Found button component'); }); it('matcher_enabled', 0, async function () { let driver: Driver = Driver.create(); // Match enabled components only let enabledButton: Component = await driver.findComponent( ON.type('Button').enabled(true) ); expect(await enabledButton.isEnabled()).assertTrue(); }); it('matcher_chain', 0, async function () { let driver: Driver = Driver.create(); // Chain multiple matchers let component: Component = await driver.findComponent( ON.text('Submit') .type('Button') .enabled(true) .clickable(true) ); await component.click(); }); it('matcher_within', 0, async function () { let driver: Driver = Driver.create(); // Find component within another component let listItem: Component = await driver.findComponent( ON.text('Item 5').within(ON.type('Scroll')) ); await listItem.scrollIntoView(); }); it('matcher_isBefore_isAfter', 0, async function () { let driver: Driver = Driver.create(); // Relative position matching let component: Component = await driver.findComponent( ON.text('Username').isBefore(ON.text('Password')) ); let anotherComponent: Component = await driver.findComponent( ON.text('Submit').isAfter(ON.text('Password')) ); }); }); } ``` -------------------------------- ### Configure Data Driving with Hypium Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This snippet demonstrates how to import the data configuration from data.json and set it using Hypium's setData method before executing tests with hypiumTest. It requires Hypium, the test suite, and the delegator arguments. ```javascript import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import { Hypium } from '@ohos/hypium' import testsuite from '../test/List.test' import data from '../test/data.json'; ... Hypium.setData(data); Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) ... ``` -------------------------------- ### ArgumentMatchers: Match Any Number in TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Illustrates the use of ArgumentMatchers.anyNumber to match any numeric argument passed to a mocked function. This is useful when the exact value of a numeric parameter is not important, but its type is. The example mocks a calculation method and asserts that it returns a predefined value when any number is passed. It requires MockKit and ArgumentMatchers from '@ohos/hypium'. ```typescript import { describe, expect, it, MockKit, when, ArgumentMatchers } from '@ohos/hypium'; export default function matcherTest() { describe('MatcherTest', function () { it('testMatcher_anyNumber', 0, function () { let mocker = new MockKit(); class ClassName { calculate(num: number): number { return num * 2; } } let calc = new ClassName(); let mockfunc = mocker.mockFunc(calc, calc.calculate); when(mockfunc)(ArgumentMatchers.anyNumber).afterReturn(100); expect(calc.calculate(5)).assertEqual(100); expect(calc.calculate(999)).assertEqual(100); mocker.clear(calc); }); }); } ``` -------------------------------- ### Import UiTest Classes (TypeScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Imports the necessary classes (UiDriver, BY, UiComponent, Uiwindow, MatchPattern) from the '@ohos.uitest' module for UI testing in TypeScript. These classes provide the fundamental APIs for interacting with and testing UI components. ```typescript import {UiDriver,BY,UiComponent,Uiwindow,MatchPattern} from '@ohos.uitest' ``` -------------------------------- ### Driver.findComponent - Locate UI Components Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Searches for a UI component matching specified criteria. Returns the first matching component for interaction or validation. Supports searching by text, type, and combined criteria. ```APIDOC ## Driver.findComponent - Locate UI Components ### Description Searches for a UI component matching specified criteria. Returns the first matching component for interaction or validation. ### Method `GET` (implicitly, as it retrieves component information) ### Endpoint N/A (Static method) ### Parameters #### Query Parameters - **criteria** (object) - Required - Defines the search criteria for the component. Can include `text()`, `type()`, `enabled()`, `within()`, etc. ### Request Example ```typescript import { Driver, ON, Component } from '@kit.TestKit'; let driver: Driver = Driver.create(); // Find by text content let component: Component = await driver.findComponent(ON.text('Login')); // Find by component type let button: Component = await driver.findComponent(ON.type('Button')); // Combine multiple criteria let complexComponent: Component = await driver.findComponent( ON.text('Submit').type('Button').enabled(true) ); // Find component within a specific container let listItem: Component = await driver.findComponent( ON.text('Item 3').within(ON.type('List')) ); ``` ### Response #### Success Response (200) - **component** (Component) - The first UI component that matches the specified criteria. #### Response Example ```typescript (Conceptual) // A Component object representing the found UI element ``` ``` -------------------------------- ### Create a Basic Test Case with arkXtest in TypeScript Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md This TypeScript code demonstrates how to create a basic test case using the arkXtest framework. It imports necessary functions from '@ohos/hypium' and defines a test suite with a single test case that asserts a boolean value. ```typescript import { describe, it, expect } from '@ohos/hypium'; export default function abilityTest() { describe('Test Suite Name', () => { it('Test Case Name', 0, async () => { // Test code expect(true).assertTrue(); }) }) } ``` -------------------------------- ### Mock Function with Argument Matching (JavaScript) Source: https://github.com/super3001/arkui-xtest-corpus/blob/main/README.md Demonstrates how to mock a class method and assert its behavior when called with specific string arguments. It uses `mocker.mockFunc` and `expect` for assertions. ```javascript let mockfunc = mocker.mockFunc(claser, claser.method_1); // Set the following parameters as required. when(mockfunc)(ArgumentMatchers.anyString).afterReturn('1'); // 4. Assert whether the mocked function is implemented as expected. // The operation is successful if a string is passed in. expect(claser.method_1('test')).assertEqual('1'); // The operation is successful. expect(claser.method_1('abc')).assertEqual('1'); // The operation is successful. // The operation fails if a number or a Boolean value is passed in. //expect(claser.method_1(123)).assertEqual('1'); // The operation fails. //expect(claser.method_1(true)).assertEqual('1'); // The operation fails. }); }); } ``` -------------------------------- ### Inject Key Events: pressBack and triggerKey Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Injects hardware key events such as the back button, home button, or arbitrary key codes. This functionality is crucial for testing navigation flows and keyboard interactions within the application. It relies on the '@kit.TestKit' module. ```typescript import { describe, it } from '@ohos/hypium'; import { Driver, ON } from '@kit.TestKit'; export default function keyEventTest() { describe('KeyEventTest', function () { it('pressBack_navigation', 0, async function () { let driver: Driver = Driver.create(); // Navigate to second page let button = await driver.findComponent(ON.text('Next Page')); await button.click(); await driver.delayMs(1000); // Press back button await driver.pressBack(); await driver.delayMs(500); // Verify we're back on first page await driver.assertComponentExist(ON.text('First Page')); }); it('triggerKey_home', 0, async function () { let driver: Driver = Driver.create(); // Simulate home key press (key code 1) await driver.triggerKey(1); await driver.delayMs(1000); }); it('triggerKey_combination', 0, async function () { let driver: Driver = Driver.create(); // Test multiple key presses await driver.triggerKey(2000); // Volume up await driver.delayMs(200); await driver.triggerKey(2001); // Volume down await driver.delayMs(200); }); }); } ``` -------------------------------- ### Assert UI Component Existence with TypeScript Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Shows how to assert the presence of UI components using `driver.assertComponentExist` with various criteria, including text, type, and enabled state. It also demonstrates handling cases where a component might not exist. ```typescript import { describe, it } from '@ohos/hypium'; import { Driver, ON } from '@kit.TestKit'; export default function assertionTest() { describe('UiAssertionTest', function () { it('assertComponentExist_basic', 0, async function () { let driver: Driver = Driver.create(); // Assert component with text 'Login' exists await driver.assertComponentExist(ON.text('Login')); console.info('Component exists as expected'); }); it('assertComponentExist_afterClick', 0, async function () { let driver: Driver = Driver.create(); // Click submit button let button = await driver.findComponent(ON.text('Submit')); await button.click(); // Assert success message appears await driver.assertComponentExist(ON.text('Submission successful')); }); it('assertComponentExist_complex', 0, async function () { let driver: Driver = Driver.create(); // Assert component with multiple criteria exists await driver.assertComponentExist( ON.text('Confirm') .type('Button') .enabled(true) ); }); it('assertComponentExist_notFound', 0, async function () { let driver: Driver = Driver.create(); try { // This will throw if component doesn't exist await driver.assertComponentExist(ON.text('NonexistentText')); // Test fails if no exception thrown } catch (error) { console.info('Component correctly not found: ' + error); // Test passes - component doesn't exist as expected } }); }); } ``` -------------------------------- ### Test Utility Functions with SysTestKit Source: https://context7.com/super3001/arkui-xtest-corpus/llms.txt Provides utilities for retrieving test context (suite and case names) and managing test execution, such as action tracking and log manipulation. It depends on '@ohos/hypium'. Functions like getDescribeName, getItName, actionStart, actionEnd, clearLog, and existKeyword are available. ```typescript import { describe, it, expect, SysTestKit } from '@ohos/hypium'; export default function sysTestKitTest() { describe('SystemTestSuite', function () { it('testSysTestKit_getNames', 0, function () { // Get current test suite name let suiteName = SysTestKit.getDescribeName(); expect(suiteName).assertEqual('SystemTestSuite'); // Get current test case name let testName = SysTestKit.getItName(); expect(testName).assertEqual('testSysTestKit_getNames'); console.info(`Running: ${suiteName} - ${testName}`); }); it('testSysTestKit_actionTracking', 0, async function () { // Track action start and end for performance monitoring SysTestKit.actionStart('user_login'); // Simulate login operation await someLoginOperation(); SysTestKit.actionEnd('user_login'); expect(true).assertTrue(); }); it('testSysTestKit_logOperations', 0, function () { // Clear existing logs let cleared = SysTestKit.clearLog(); expect(cleared).assertTrue(); // Perform operations that generate logs console.info('Test log entry'); // Check if specific keyword exists in logs let hasKeyword = SysTestKit.existKeyword('Test log entry', 1000); expect(hasKeyword).assertTrue(); }); }); } async function someLoginOperation() { // Simulated async operation await new Promise(resolve => setTimeout(resolve, 100)); } ```