### JsUnit Basic Process Support Example Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Demonstrates the basic structure of a JsUnit test suite using describe, it, and expect. Includes an example of asynchronous API usage with getBundleInfo. ```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 Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Demonstrates creating a UiDriver, finding a component by text, clicking it, and asserting its text content. Requires asynchronous syntax and JsUnit specifications. ```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!') }) }) } ``` -------------------------------- ### Assertion Library Examples Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Demonstrates the usage of various assertion methods including assertClose and assertInstanceOf. These examples are part of a test suite and require the @ohos/hypium framework. ```javascript import { describe, it, expect } from '@ohos/hypium' export default async function abilityTest() { describe('assertClose', function () { it('assertBeClose_success', 0, function () { let a = 100 let b = 0.1 expect(a).assertClose(99, b) }) it('assertBeClose_fail', 0, function () { let a = 100 let b = 0.1 expect(a).assertClose(1, b) }) it('assertBeClose_fail', 0, function () { let a = 100 let b = 0.1 expect(a).assertClose(null, b) }) it('assertBeClose_fail', 0, function () { expect(null).assertClose(null, 0) }) it('assertInstanceOf_success', 0, function () { let a = 'strTest' expect(a).assertInstanceOf('String') }) }) } ``` -------------------------------- ### Mocking a System API with afterReturn Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This example demonstrates how to mock a global system API, such as 'app.getInfo()', using MockKit. It's useful for isolating your code from external dependencies during testing and controlling the behavior of system calls. ```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'); }); }); } ``` -------------------------------- ### Mocking a function with afterReturn Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This example demonstrates how to mock a method of a class using MockKit and set a specific return value using afterReturn. Ensure the MockKit version is compatible. ```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. }); }); } ``` -------------------------------- ### Verifying Function Execution Count with atLeast() Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This example demonstrates using MockKit's 'verify' method with the 'atLeast(count)' matcher to ensure a mocked function is called a minimum number of times. This is useful when you need to confirm that a certain operation occurs at least once or a specified number of times, but the exact count is not critical beyond that minimum. ```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(); ``` -------------------------------- ### JsUnit Test Case with Data Driving Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Example of a JsUnit test case that utilizes data driving. The 'data' parameter in the test function receives values from the 'params' in data.json. ```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'); }); }); } ``` -------------------------------- ### Mock Method to Throw an Exception Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This example shows how to configure a mocked function to throw a specific error message using `afterThrow`. It includes a try-catch block to capture the exception and assert that the error message matches the expected value. ```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'; } } let claser = new ClassName(); // 3. Mock method_1 of the ClassName class. let mockfunc = mocker.mockFunc(claser, claser.method_1); // 4. Set the action to be performed when the test case ends. For example, set it to afterReturnNothing(), which returns no value. when(mockfunc)('test').afterThrow('error xxx'); // 5. Execute the mocked function, capture the exception, and use assertEqual() to check whether message meets the expectation. try { claser.method_1('test'); } catch (e) { expect(e).assertEqual('error xxx'); // The execution is successful. } }); }); } ``` -------------------------------- ### Clear All Mocks for a Class Instance Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This example demonstrates how to use `mocker.clear(claser)` to remove all mock behaviors previously set for methods of a given class instance. It verifies that after clearing, calls to mocked methods do not return the mocked values. ```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 and method_2 of the ClassName class. let func_1 = mocker.mockFunc(claser, claser.method_1); let func_2 = mocker.mockFunc(claser, claser.method_2); // 4. Modify the mocked functions. when(func_1)(ArgumentMatchers.anyNumber).afterReturn('4'); when(func_2)(ArgumentMatchers.anyNumber).afterReturn('5'); // 5. Call the following methods. //expect(claser.method_1(123)).assertEqual('4'); // The return value is the same as the expected value. //expect(claser.method_2(456)).assertEqual('5'); // The return value is the same as the expected value. // 6. Clear the mock operation. mocker.clear(claser); // Call claser.method_1 and check the execution result. expect(claser.method_1(123)).assertEqual('4'); // The return value is "failed", which meets the expectation. expect(claser.method_2(456)).assertEqual('5'); // The return value is "failed", which meets the expectation. }); }); } ``` -------------------------------- ### Build UiTest from Source Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use these commands to build the UiTest framework if you have modified its source code. Ensure you are in the correct project directory. ```shell ./build.sh --product-name rk3568 --build-target uitestkit ``` -------------------------------- ### Deploy UiTest to Device Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md These commands are used to send the built UiTest executable and its shared library to the target device and set the correct permissions. ```shell hdc_std target mount hdc_std shell mount -o rw,remount / hdc_std file send uitest /system/bin/uitest hdc_std file send libuitest.z.so /system/lib/module/libuitest.z.so hdc_std shell chmod +x /system/bin/uitest ``` -------------------------------- ### Import MockKit and when Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md You must import MockKit and when to use the mocking features. Other assertion APIs can be imported as needed. ```javascript import {describe, expect, it, MockKit, when} from '@ohos/hypium'; ``` -------------------------------- ### Enable UiTest Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Run this command on the device to enable UiTest mode. This is required before using UiTest APIs. ```shell hdc_std shell param set persist.ace.testmode.enabled 1 ``` -------------------------------- ### JsUnit Mocking APIs Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This section provides a structured overview of the JsUnit mocking APIs. It includes functions for mocking, setting return values, handling exceptions, verifying calls, and cleaning up mocks. ```APIDOC ## JsUnit Mocking API Reference This document outlines the available APIs for the JsUnit mocking framework. ### Available APIs | No. | API | Description| | --- | --- | --- | | 1 | `mockFunc(obj: object, f: function())` | Mocks a function in the object of a class. The parameters **obj** and **f** must be passed in. This API supports asynchronous functions.
**NOTE**: This API does not focus on the implementation of the original function. Therefore, it does not matter whether the original function is implemented synchronously or asynchronously.| | 2 | `when(mockedfunc: function)` | Checks whether the input function is mocked and marked. A function declaration is returned.| | 3 | `afterReturn(x: value)` | Sets an expected return value, for example, a string or promise.| | 4 | `afterReturnNothing()` | Sets the expected return value to **undefined**, that is, no value will be returned.| | 5 | `afterAction(x: action)` | Sets the expected return value to be an action executed by a function.| | 6 | `afterThrow(x: msg)` | Sets an exception to throw and the error message.| | 7 | `clear()` | Restores the mocked object after the test case is complete (restores the original features of the object).| | 8 | `any` | Returns the expected value if a parameter of any type (except **undefined** and **null**) is passed in. This API must be called by **ArgumentMatchers.any**.| | 9 | `anyString` | Returns the expected value if a string is passed in. This API must be called by **ArgumentMatchers.anyString**.| | 10 | `anyBoolean` | Returns the expected value if a Boolean value is passed in. This API must be called by **ArgumentMatchers.anyBoolean**.| | 11 | `anyFunction` | Returns the expected value if a function is passed in. This API must be called by **ArgumentMatchers.anyFunction**.| | 12 | `anyNumber` | Returns the expected value if a number is passed in. This API must be called by **ArgumentMatchers.anyNumber**.| | 13 | `anyObj` | Returns the expected value if an object is passed in. This API must be called by **ArgumentMatchers.anyObj**.| | 14 | `matchRegexs(Regex)` | Returns the expected value if a regular expression is passed in. This API must be called by **ArgumentMatchers.matchRegexs(Regex)**.| | 15 | `verify(methodName, argsArray)` | Verifies whether a function and its parameters are processed as expected. This API returns a **VerificationMode**, which is a class that provides the verification mode. This class provides functions such as **times(count)**, **once()**, **atLeast(x)**, **atMost(x)**, and **never()**.| | 16 | `times(count)` | Verifies whether the function was executed the specified number of times.| | 17 | `once()` | Verifies whether the function was executed only once.| | 18 | `atLeast(count)` | Verifies whether the function was executed at least **count** times.| | 19 | `atMost(count)` | Verifies whether the function was executed at most **count** times.| | 20 | `never` | Verifies whether the function has never been executed.| | 21 | `ignoreMock(obj, method)` | Restores the mocked function in the object. This API is valid for mocked functions.| | 22 | `clearAll()` | Clears all data and memory after the test cases are complete.| ### Constraints JsUnit provides the mock capability since npm [1.0.1](https://repo.harmonyos.com/#/en/application/atomService/@ohos%2Fhypium). You must modify the npm version in **package.info** of the source code project before using the mock capability. ### Examples #### Example 1: Use `afterReturn` ```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. }); }); } ``` ``` -------------------------------- ### Mock Class Methods and Restore Original Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This snippet shows how to mock specific methods of a class, define their behavior using `when` and `afterReturn`, and then restore one of the methods using `ignoreMock`. It verifies that the restored method behaves as the original while the other remains mocked. ```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 and method_2 of the ClassName class. let func_1 = mocker.mockFunc(claser, claser.method_1); let func_2 = mocker.mockFunc(claser, claser.method_2); // 4. Modify the mocked functions. when(func_1)(ArgumentMatchers.anyNumber).afterReturn('4'); when(func_2)(ArgumentMatchers.anyNumber).afterReturn('5'); // 5. Call the following methods. console.log(claser.method_1(123)); // The return value is 4, which is the same as the expected value in Step 4. console.log(claser.method_2(456)); // The return value is 5, which is the same as the expected value in Step 4. // 6. Restore method_1 using ignoreMock(). mocker.ignoreMock(claser, claser.method_1); // Call claser.method_1 and check the execution result. console.log(claser.method_1(123)); // The return value is 888888, which is the same as that returned by the original function. // Test with assertions. expect(claser.method_1(123)).assertEqual('4'); // The return value is "failed", which meets the expected value of ignoreMock(). claser.method_2(456); // The return value is 5, which is the same as the expected value in Step 4 because method_2 is not restored. }); }); } ``` -------------------------------- ### UiWindow APIs Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md APIs for interacting with UI windows, including obtaining attributes, moving, resizing, and closing windows. ```APIDOC ## UiWindow APIs ### Description Provides methods to interact with UI windows. You can find a window using `UiDriver.findWindow(by)`. ### Methods - **getBundleName()**: Obtains the bundle name of the window. - **getTitle()**: Obtains the window title. - **focus()**: Gives focus to the current window. - **moveTo(x: number, y: number)**: Moves the current window to the specified position. Applicable to windows that can be moved. - **resize(wide: number, height: number, direction: ResizeDirection)**: Adjusts the window size. Applicable to windows that can be resized. - **split()**: Splits the current window. Applicable to windows that support split-screen mode. - **close()**: Closes the current window. ### Examples **Obtain window attributes:** ```javascript let window = await driver.findWindow({actived: true}) let bundelName = await window.getBundleName() ``` **Move the window:** ```javascript let window = await driver.findWindow({actived: true}) await window.moveTo(500,500) ``` **Close the window:** ```javascript let window = await driver.findWindow({actived: true}) await window.close() ``` ``` -------------------------------- ### Import and Set Data in app.js/app.ets Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Import the data.json file and set it using Hypium.setData() before executing Hypium.hypiumTest(). This configures the test runner with your data-driven parameters. ```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) ... ``` -------------------------------- ### Mock Function with Any Argument Matcher Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use ArgumentMatchers.any to mock a function that accepts any parameter value except undefined and null. Ensure ArgumentMatchers is imported. ```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. }); }); } ``` -------------------------------- ### Move a UI Window Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This snippet demonstrates how to reposition an active UI window to a specified coordinate (x, y). This functionality is applicable to windows that support being moved. ```javascript let window = await driver.findWindow({actived: true}) await window.moveTo(500,500) ``` -------------------------------- ### Mocking an Instance Method with afterReturn Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This snippet shows how to mock an instance method of a class using MockKit and define a custom promise to be returned after the mocked function executes. It's useful for testing asynchronous operations or controlling return values in specific scenarios. ```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() { } async method_1(arg) { return new Promise((res, rej) => { // Perform asynchronous operations. setTimeout(function () { console.log ('Execute'); res('Pass data'); }, 2000); }); } } let claser = new ClassName(); // 3. Mock method_1 of the ClassName class. let mockfunc = mocker.mockFunc(claser, claser.method_1); // 4. Set the action to be performed after the test case ends. For example, set it to afterRetrun(), which returns a custom promise. when(mockfunc)('test').afterReturn(new Promise((res, rej) => { console.log("do something"); res('success something'); })); // 5. Execute the mocked function, that is, execute the promise. claser.method_1('test').then(function (data) { // Code for data processing console.log('result : ' + data); }); }); }); } ``` -------------------------------- ### data.json Configuration Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This JSON file defines the parameters and execution counts for test suites and test cases. It should be placed in the same directory as your test files. ```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 }] }] } ``` -------------------------------- ### Import UiTest Classes Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Import necessary classes from the '@ohos.uitest' module to use UiTest functionalities. ```typescript import {UiDriver,BY,UiComponent,Uiwindow,MatchPattern} from '@ohos.uitest' ``` -------------------------------- ### UiComponent APIs Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md APIs for interacting with UI components, including clicking, inputting text, scrolling, and retrieving component attributes. ```APIDOC ## UiComponent APIs ### Description Provides methods to interact with UI components. You can find a component using `UiDriver.findComponent(by)`. ### Methods - **click()**: Clicks the component. - **inputText(t: string)**: Inputs text into the component. Applicable to text box components. - **scrollSearch(s: By)**: Scrolls on this component to search for the target component. Applicable to List components. - **getText()**: Obtains the component text. - **getId()**: Obtains the component ID. - **getType()**: Obtains the component type. - **isEnabled()**: Obtains the component state (enabled or disabled). ### Examples **Click a component:** ```javascript let button = await driver.findComponent(BY.id(Id_button)) await button.click() ``` **Input text in a text box:** ```javascript let editText = await driver.findComponent(BY.type('InputText')) await editText.inputText("user_name") ``` **Scroll to locate a child component:** ```javascript let list = await driver.findComponent(BY.id(Id_list)) let found = await list.scrollSearch(BY.text("Item3_3")) expect(found).assertTrue() ``` ``` -------------------------------- ### Mock Function with Regex Argument Matcher Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Mock a function and specify argument matching using regular expressions. This allows for flexible matching of string arguments that conform to a pattern. ```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 a regular expression to match, for example, /123456/. when(mockfunc)(ArgumentMatchers.matchRegexs(/123456/)).afterReturn('1'); // 4. Assert whether the mocked function is implemented as expected. // The operation is successful if a string, for example, '1234567898', is passed in. expect(claser.method_1('1234567898')).assertEqual('1'); // The operation is successful. // The string '1234567898' matches the regular expression /123456/. // The operation fails if '1234' is passed in. //expect(claser.method_1('1234').assertEqual('1'); // The operation fails because '1234' does not match the regular expression /123456/. }); }); } ``` -------------------------------- ### Assert Component Existence with UiDriver Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Shows how to use UiDriver to assert the existence of a component by its text attribute. This API throws a JS exception if the component is not found. ```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() } }) }) } ``` -------------------------------- ### Find Component by ID and Type Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Searches for a component by its ID and specifies its type. This helps in distinguishing between components of the same ID but different types. ```javascript let button = await driver.findComponent(BY.id(Id_button).type("Button")) ``` -------------------------------- ### Mock Function with AnyString Argument Matcher Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use ArgumentMatchers.anyString to mock a function that specifically expects a string argument. Ensure ArgumentMatchers is imported. ```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. ``` -------------------------------- ### Click a UI Component Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use this snippet to simulate a click action on a specific UI component identified by its ID. Ensure the component is found before attempting to click. ```javascript let button = await driver.findComponent(BY.id(Id_button)) await button.click() ``` -------------------------------- ### Assert UI Component Existence Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Verify that a UI component exists by finding it using its ID and then asserting its non-null value. This is useful for ensuring UI elements are present before interacting with them. ```javascript let component = await driver.findComponent(BY.id(Id_title)) expect(component !== null).assertTrue() ``` -------------------------------- ### Verify Mocked Function Calls with Constraints Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use the verify() method to check if mocked functions were called with specific arguments and with a certain frequency. This is crucial for ensuring correct interaction between different parts of your code. ```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". }); }); } ``` -------------------------------- ### Find Component by Text with Default Equals Match Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Searches for a component where the text attribute exactly matches the specified string. This is the default behavior when no match pattern is provided. ```javascript let txt = await driver.findComponent(BY.text("hello")) ``` -------------------------------- ### Mock Function with Any String Argument Matcher Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Mock a function and assert its behavior when called with any string argument. This is useful for testing function calls where the specific string value is not critical. ```javascript let mockfunc = mocker.mockFunc(claser, claser.method_1); when(mockfunc)(ArgumentMatchers.anyString).afterReturn('1'); expect(claser.method_1('test')).assertEqual('1'); // The operation is successful. expect(claser.method_1('abc')).assertEqual('1'); // The operation is successful. ``` -------------------------------- ### Verifying Function Execution Count with times() Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md This snippet illustrates how to use MockKit's 'verify' method with the 'times(count)' matcher to assert that a specific mocked function was called exactly a certain number of times. This is crucial for ensuring that certain code paths are executed the expected number of repetitions. ```javascript import { describe, expect, it, MockKit, when } from '@ohos/hypium' export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('test_verify_times', 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('abc'); claser.method_1(); // 7. Check whether method_1 with the parameter of 'abc' was executed twice. mocker.verify('method_1', ['abc']).times(2); }); }); } ``` -------------------------------- ### Input Text into a UI Component Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use this code to input text into a component, typically a text box or input field. Ensure the component is of a type that accepts text input. ```javascript let editText = await driver.findComponent(BY.type('InputText')) await editText.inputText("user_name") ``` -------------------------------- ### Obtain UI Window Bundle Name Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Retrieve the bundle name of the currently active UI window. This is useful for identifying which application the window belongs to. ```javascript let window = await driver.findWindow({actived: true}) let bundelName = await window.getBundleName() ``` -------------------------------- ### Find Component by ID Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Searches for a UI component using its unique ID. This is a basic method for component identification. ```javascript let button = await driver.findComponent(BY.id(Id_button)) ``` -------------------------------- ### Find Component Before Another Component Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Locates a component that appears before a specified feature component. This is used for relative positioning within the UI hierarchy. ```javascript let switch = await driver.findComponent(BY.id(Id_switch).isBefore(BY.text("Item3_3"))) ``` -------------------------------- ### Mock Function to Return Nothing Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use afterReturnNothing() to mock a function that should not return any value. This is useful for testing side effects or verifying that a function was called without expecting a specific return. ```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); // 4. Set the action to be performed when the test case ends. For example, set it to afterReturnNothing(), which returns no value. when(mockfunc)('test').afterReturnNothing(); // 5. Assert whether the mocked function is implemented as expected. Use the assertion APIs corresponding to Step 4. // The operation is successful if 'test' is passed in. // The mocked claser.method_1 does not return '888888'. Instead, afterReturnNothing() takes effect, that is, no value is returned. expect(claser.method_1('test')).assertUndefined(); // The operation is successful. // The operation fails if '123' is passed in. // expect(method_1(123)).assertUndefined();// The operation fails. }); }); } ``` -------------------------------- ### Find Component by ID and Text with Contains Match Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Combines ID and text matching to find a component. The text attribute is matched using the CONTAINS pattern. ```javascript let button = await driver.findComponent(BY.id(Id_button).text("hello", MatchPattern.CONTAINS)) ``` -------------------------------- ### Find Component by Text with Contains Match Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Searches for a component whose text attribute contains a specific substring. Use this when the exact text is unknown or only a partial match is needed. ```javascript let txt = await driver.findComponent(BY.text("hello", MatchPattern.CONTAINS)) ``` -------------------------------- ### Find Component After Another Component Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Locates a component that appears after a specified feature component. This is used for relative positioning within the UI hierarchy. ```javascript let switch = await driver.findComponent(BY.id(Id_switch).isAfter(BY.text("Item3_3"))) ``` -------------------------------- ### Find Component by ID and Enabled State Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Locates a component by its ID and checks if it is enabled. Useful when a single attribute is insufficient for unique identification. ```javascript let button = await driver.findComponent(BY.id(Id_button).enabled(true)) ``` -------------------------------- ### assertLess Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Checks whether the actual value is strictly less than the expected value. ```APIDOC ## assertLess ### Description Checks whether the actual value is less than the expected value. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters This method is called as an extension on an expectation object. - **expectedValue** (any) - The value to compare against. ### Request Example ```javascript expect(actualValue).assertLess(expectedValue) ``` ### Response N/A (This method performs an assertion and may throw an error if the assertion fails.) #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### assertEqual Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Checks whether the actual value is strictly equal to the expected value. ```APIDOC ## assertEqual ### Description Checks whether the actual value is equal to the expected value. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters This method is called as an extension on an expectation object. - **expectedValue** (any) - The value to compare against. ### Request Example ```javascript expect(actualValue).assertEqual(expectedValue) ``` ### Response N/A (This method performs an assertion and may throw an error if the assertion fails.) #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Close a UI Window Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use this code to close the currently active UI window. This action will terminate the window and any associated processes. ```javascript let window = await driver.findWindow({actived: true}) await window.close() ``` -------------------------------- ### Find Component by ID and Clickable State Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Searches for a component by its ID and checks if it is clickable. This is useful for interacting with interactive elements. ```javascript let button = await driver.findComponent(BY.id(Id_button).clickable(true)) ``` -------------------------------- ### Verify Method Call Count Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Use mocker.verify to check if a specific method was called at least a certain number of times with given arguments. This is useful for ensuring that certain operations are performed repeatedly. ```typescript mocker.verify('method_1', []).atLeast(2); ``` -------------------------------- ### assertInstanceOf Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Checks whether the actual value is of the specified type. ```APIDOC ## assertInstanceOf ### Description Checks whether the actual value is of the type specified by the expected value. Basic types are supported. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters This method is called as an extension on an expectation object. - **expectedType** (string) - The expected type of the actual value (e.g., 'String', 'Number', 'Boolean'). ### Request Example ```javascript expect(actualValue).assertInstanceOf(expectedType) ``` ### Response N/A (This method performs an assertion and may throw an error if the assertion fails.) #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### assertFail Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Throws an error, causing the test to fail. ```APIDOC ## assertFail ### Description Throws an error. ### Method N/A (This is a library function, not an HTTP endpoint) ### Endpoint N/A ### Parameters This method is called as an extension on an expectation object. ### Request Example ```javascript expect().assertFail() ``` ### Response N/A (This method always throws an error.) #### Success Response N/A #### Response Example N/A ``` -------------------------------- ### Find Component by ID and Focused State Source: https://github.com/openharmony/testfwk_arkxtest/blob/master/README_en.md Locates a component by its ID and determines if it has focus. This can be used for components that require focus to be active. ```javascript let button = await driver.findComponent(BY.id(Id_button).focused(true)) ```