### Mocking Functions with afterReturn in JsUnit Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Demonstrates how to mock a function within a class using JsUnit's MockKit and the afterReturn API. This example shows the setup, mocking, and assertion process. It requires importing MockKit and when from '@ohos/hypium'. ```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 Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Demonstrates the basic structure of a JsUnit test suite using describe, it, and expect. It includes example assertions and asynchronous API calls. This snippet requires the '@ohos/hypium' and '@ohos.bundle' modules. ```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) }) }) }) } ``` -------------------------------- ### Define Test Suite and Lifecycle Hooks with describe() - JavaScript Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Defines a test suite using the `describe` function and includes lifecycle hooks (`beforeAll`, `beforeEach`, `afterEach`, `afterAll`) for setup and teardown operations in JavaScript. It also demonstrates basic assertions using `expect` and asynchronous operations with `it`. ```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 () { // Runs once before all tests beforeAll(function () { console.info('Test suite starting') }) // Runs before each test beforeEach(function () { console.info('Test case starting') }) // Runs after each test afterEach(function () { console.info('Test case completed') }) // Runs once after all tests afterAll(function () { console.info('Test suite completed') }) 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) }) }) }) } ``` -------------------------------- ### Mock Function with Regex Argument Matcher Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This example demonstrates mocking a class method using a regular expression to match arguments. The mocked function returns '1' if the input string matches the provided regex. It includes setup for MockKit, class definition, mocking, and assertions. Dependencies include MockKit, ArgumentMatchers, and Hypium testing utilities. ```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/. }); }); } ``` -------------------------------- ### Mock Function with Any String Argument Matcher Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Mocks a class method to accept any string argument. This example demonstrates the use of `ArgumentMatchers.anyString` for specific string matching. The code snippet is incomplete, but it sets up the mocking scenario using `MockKit` and `when` from '@ohos/hypium'. ```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. ``` -------------------------------- ### Verifying Function Execution At Least a Certain Number of Times Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This example illustrates how to use MockKit's `verify` and `atLeast` methods to ensure a mocked function is called a minimum number of times. It follows a similar setup to the `times` verification, including mocking a class method, executing it multiple times, and then verifying that a specific method was called at least once. ```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(); // The verify method is used here to check if method_1 was called at least once. mocker.verify('method_1').atLeast(1); }); }); } ``` -------------------------------- ### Data-Driven Testing Setup with Hypium.setData() in JavaScript Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Configures parameterized tests by loading data from a JSON file using Hypium.setData(). This enables tests to run multiple times with different input parameters defined in the 'data.json' configuration. It's crucial for efficient testing of scenarios with varying data sets. ```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 }] }] } ``` ```javascript // app.js - Test initialization import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry' import { Hypium } from '@ohos/hypium' import testsuite from '../test/List.test' import data from '../test/data.json' // Configure data-driven parameters Hypium.setData(data) Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) // Test implementation import { describe, it, expect } from '@ohos/hypium' export default function abilityTest() { describe('actsAbilityTest', function () { // Test executes 2 times (stress: 2) with 2 different param sets it('testDataDriverAsync', 0, async function (done, data) { console.info('Testing with name: ' + data.name) console.info('Testing with value: ' + data.value) expect(data.value).assertLarger(0) done() }) // Test executes 3 times (stress: 3) without params it('testDataDriver', 0, function () { console.info('Stress test execution') }) }) } ``` -------------------------------- ### Mock Function with Any Argument Matcher and Specific Return Value Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Mocks a class method to accept any argument (except undefined and null) and return a specific value. This example utilizes `ArgumentMatchers.any` for flexible argument handling and `afterReturn('1')` to set the return value. It requires importing `ArgumentMatchers` from '@ohos/hypium'. Assertions demonstrate successful calls with various data types. ```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. }); }); } ``` -------------------------------- ### Asserting Component Existence with UiDriver in JavaScript Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Illustrates how to assert the existence of a UI component using UiDriver and the assertComponentExist method in JavaScript. The example demonstrates creating a UiDriver, checking for the presence of a component identified by its text, and handling potential exceptions within a try-finally block. This function is crucial for validating UI state during tests. ```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() } }) }) } ``` -------------------------------- ### Mock Function with No Return Value using afterReturnNothing Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Mocks a class method and configures it to return undefined after being called with a specific argument. This example demonstrates the use of `afterReturnNothing()` and asserts that the mocked method returns undefined when called with the expected argument. It requires importing MockKit and related functions from '@ohos/hypium'. ```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. // 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. }); }); } ``` -------------------------------- ### Verifying Function Execution Count (times) Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This example demonstrates how to use MockKit's `verify` and `times` methods to check if a mocked function was called a specific number of times. It involves creating a MockKit instance, defining and mocking a class method, setting up a mock return value, executing the mocked function multiple times, and finally verifying that it was called exactly twice with a given parameter. ```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); }); }); } ``` -------------------------------- ### Deploy UiTest Binaries and Libraries Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md These commands are used to send the compiled UiTest executable and its shared library to the target device's system directories. It involves mounting the system partition in read-write mode, transferring files using `hdc_std file send`, and setting execute 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 ``` -------------------------------- ### Basic UI Test Case with UiDriver in JavaScript Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Demonstrates a basic UI test case using UiDriver in JavaScript. It shows how to create a UiDriver instance, find a component by its text, simulate a click event on the component, retrieve its text content, and assert that the text matches an expected value. This requires importing necessary testing utilities and UiTest classes. ```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!') }) }) } ``` -------------------------------- ### Clear All Mocks with clear() Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This example demonstrates how to use the `clear()` method from MockKit to remove all active mocks for a given object. It shows that after clearing mocks, subsequent calls to the mocked methods will execute the original implementations. ```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. }); }); } ``` -------------------------------- ### Window Management API Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Provides APIs for window manipulation including focus, resize, move, and split-screen operations. ```APIDOC ## Window Management - UiWindow ### Description Provides APIs for window manipulation including focus, resize, move, and split-screen operations. ### Method GET (implicitly used via findWindow) ### Endpoint N/A (Operates on an existing window object) ### Parameters #### Query Parameters - **actived** (boolean) - Optional - Filters for the currently active window. ### Request Example ```javascript let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) ``` ### Response #### Success Response (200) - **Window Object** - Represents the application window with associated methods. #### Response Example ```javascript // Assuming window object is obtained let bundleName = await window.getBundleName() let title = await window.getTitle() ``` ## Window Operations ### Description These methods operate on a `Window` object to perform specific actions. ### Method - `moveTo(x, y)` - `resize(width, height, direction)` - `focus()` - `split()` - `close()` ### Endpoint N/A (Operates on an existing window object) ### Parameters #### `moveTo` Parameters - **x** (number) - Required - The target X-coordinate. - **y** (number) - Required - The target Y-coordinate. #### `resize` Parameters - **width** (number) - Required - The target width. - **height** (number) - Required - The target height. - **direction** (ResizeDirection) - Required - The direction of resizing. ### Request Example ```javascript // Move window let resultMove = await window.moveTo(500, 500) // Resize window let resultResize = await window.resize(800, 600, ResizeDirection.LEFT) // Focus window let resultFocus = await window.focus() // Split window let resultSplit = await window.split() // Close window let resultClose = await window.close() ``` ### Response #### Success Response (200) - **result** (boolean) - Indicates if the operation was successful. #### Response Example ```javascript expect(result).assertTrue() ``` ``` -------------------------------- ### Manage UiWindow using JavaScript Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This snippet shows how to interact with UI windows using the UiWindow class. It includes methods for finding a window, retrieving its bundle name, moving the window to a new position, and closing it. The primary dependency is the UiDriver class. ```javascript let window = await driver.findWindow({actived: true}) let bundelName = await window.getBundleName() ``` ```javascript let window = await driver.findWindow({actived: true}) await window.moveTo(500,500) ``` ```javascript let window = await driver.findWindow({actived: true}) await window.close() ``` -------------------------------- ### Build UiTest Kit for rk3568 Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This command initiates the build process for the UiTest kit, specifically targeting the `rk3568` product. This script is used when modifications to the UiTest source code need to be compiled. ```shell ./build.sh --product-name rk3568 --build-target uitestkit ``` -------------------------------- ### JsUnit Mocking APIs Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This section lists and describes the available APIs for JsUnit's mocking framework. ```APIDOC ## JsUnit Mocking API Documentation ### Overview JsUnit provides mocking capabilities starting from npm version 1.0.1. Ensure your `package.info` file reflects this version before utilizing these features. ### Available APIs 1. **`mockFunc(obj: object, f: function())`** * **Description**: Mocks a function within a given object. Both `obj` and `f` are required parameters. Supports asynchronous functions. * **Note**: This API focuses on mocking and does not alter the original function's implementation details (synchronous or asynchronous). 2. **`when(mockedfunc: function)`** * **Description**: Checks if a function is mocked and marked. Returns a function declaration. 3. **`afterReturn(x: value)`** * **Description**: Sets a specific expected return value (e.g., string, promise). 4. **`afterReturnNothing()`** * **Description**: Sets the expected return value to `undefined` (no value returned). 5. **`afterAction(x: action)`** * **Description**: Sets the expected return value to be an action executed by a function. 6. **`afterThrow(x: msg)`** * **Description**: Sets an exception to be thrown along with an error message. 7. **`clear()`** * **Description**: Restores the mocked object to its original state after the test case is complete. 8. **`any`** * **Description**: Matches any parameter type except `undefined` and `null`. Must be called via `ArgumentMatchers.any()`. 9. **`anyString`** * **Description**: Matches any string parameter. Must be called via `ArgumentMatchers.anyString()`. 10. **`anyBoolean`** * **Description**: Matches any boolean parameter. Must be called via `ArgumentMatchers.anyBoolean()`. 11. **`anyFunction`** * **Description**: Matches any function parameter. Must be called via `ArgumentMatchers.anyFunction()`. 12. **`anyNumber`** * **Description**: Matches any number parameter. Must be called via `ArgumentMatchers.anyNumber()`. 13. **`anyObj`** * **Description**: Matches any object parameter. Must be called via `ArgumentMatchers.anyObj()`. 14. **`matchRegexs(Regex)`** * **Description**: Matches if a regular expression is passed. Must be called via `ArgumentMatchers.matchRegexs(Regex)`. 15. **`verify(methodName, argsArray)`** * **Description**: Verifies if a function and its parameters were processed as expected. Returns a `VerificationMode` object. 16. **`times(count)`** * **Description**: Verifies if the function was executed a specific number of times. Used with `verify()`. 17. **`once()`** * **Description**: Verifies if the function was executed exactly once. Used with `verify()`. 18. **`atLeast(count)`** * **Description**: Verifies if the function was executed at least `count` times. Used with `verify()`. 19. **`atMost(count)`** * **Description**: Verifies if the function was executed at most `count` times. Used with `verify()`. 20. **`never`** * **Description**: Verifies if the function was never executed. Used with `verify()`. 21. **`ignoreMock(obj, method)`** * **Description**: Restores a mocked function in the object. This is valid for mocked functions. 22. **`clearAll()`** * **Description**: Clears all data and memory after test cases are completed. ### Usage Example **Notice**: You must import `MockKit` and `when`. Other assertion APIs can be imported as needed. Example import: ```javascript import {describe, expect, it, MockKit, when} from '@ohos/hypium'; ``` **Example 1: Using `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. }); }); } ``` ``` -------------------------------- ### Manage Windows with UiWindow API in JavaScript Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Provides APIs for window manipulation including focus, resize, move, and split-screen operations. Requires the '@ohos.uitest' library. It takes no explicit input but operates on the currently active window, returning boolean results for most operations. ```javascript import { describe, it, expect } from '@ohos/hypium' import { UiDriver } from '@ohos.uitest' export default async function abilityTest() { describe('WindowTests', function() { it('window_get_properties', 0, async function() { let driver = await UiDriver.create() // Find active window let window = await driver.findWindow({ actived: true }) // Get window properties let bundleName = await window.getBundleName() let title = await window.getTitle() console.info('Bundle: ' + bundleName) console.info('Title: ' + title) }) it('window_move', 0, async function() { let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) // Move window to coordinates (500, 500) let result = await window.moveTo(500, 500) expect(result).assertTrue() }) it('window_resize', 0, async function() { let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) // Resize window: width=800, height=600 let result = await window.resize(800, 600, ResizeDirection.LEFT) expect(result).assertTrue() }) it('window_focus', 0, async function() { let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) // Give focus to window let result = await window.focus() expect(result).assertTrue() }) it('window_split_screen', 0, async function() { let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) // Split window (if supported) let result = await window.split() expect(result).assertTrue() }) it('window_close', 0, async function() { let driver = await UiDriver.create() let window = await driver.findWindow({ actived: true }) // Close window let result = await window.close() expect(result).assertTrue() }) }) } ``` -------------------------------- ### Ignore Mocked Method Calls Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This example illustrates how to use `ignoreMock(obj, method)` to disable mocking for a specific method on an object. This allows the original implementation of the method to be called instead of the mocked version. The code sets up a MockKit object and defines a class, but the specific implementation for `ignoreMock` is not shown in the provided snippet. ```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() { } ``` -------------------------------- ### Mocking a System API Function Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This snippet shows how to mock a system API function, specifically `app.getInfo()`, using MockKit. It involves creating a MockKit instance, mocking the target function, defining its return value, and then asserting the expected outcome. This is useful for isolating your test code from external system dependencies. ```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'); }); }); } ``` -------------------------------- ### Mock Functions with Argument Matchers using MockKit Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Illustrates using MockKit with ArgumentMatchers to mock functions based on specific argument patterns. Supports matching any number, any string, or using regular expressions for flexible mocking. ```javascript import { describe, expect, it, MockKit, when, ArgumentMatchers } from '@ohos/hypium' export default function ActsAbilityTest() { describe('MockingTests', function () { it('mockFunc_with_ArgumentMatchers', 0, function () { let mocker = new MockKit() class Calculator { add(a, b) { return a + b } } let calc = new Calculator() let mockAdd = mocker.mockFunc(calc, calc.add) // Match any number argument when(mockAdd)(ArgumentMatchers.anyNumber).afterReturn(100) expect(calc.add(5)).assertEqual(100) expect(calc.add(999)).assertEqual(100) // Match string arguments let mockFunc2 = mocker.mockFunc(calc, calc.add) when(mockFunc2)(ArgumentMatchers.anyString).afterReturn('matched') // Match with regex let mockFunc3 = mocker.mockFunc(calc, calc.add) when(mockFunc3)(ArgumentMatchers.matchRegexs(/\d{3}/)).afterReturn('digit match') }) }) } ``` -------------------------------- ### Mock Functions with Return Values and Exceptions using MockKit Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Demonstrates mocking a function's return value and simulating exceptions using MockKit. It shows how to replace original function behavior with controlled outputs or errors, and how to restore the original behavior. ```javascript import { describe, expect, it, MockKit, when, ArgumentMatchers } from '@ohos/hypium' export default function ActsAbilityTest() { describe('MockingTests', function () { it('mockFunc_with_afterReturn', 0, function () { // Create MockKit instance let mocker = new MockKit() // Define class to mock class ClassName { constructor() {} method_1(arg) { return '888888' } method_2(arg) { return '999999' } } let claser = new ClassName() // Mock method_1 let mockfunc = mocker.mockFunc(claser, claser.method_1) when(mockfunc)('test').afterReturn('1') // Assertions expect(claser.method_1('test')).assertEqual('1') // Returns mocked value expect(claser.method_2('test')).assertEqual('999999') // Original behavior }) it('mockFunc_afterThrow', 0, function () { let mocker = new MockKit() class Service { fetchData(id) { return 'data' } } let service = new Service() let mockFetch = mocker.mockFunc(service, service.fetchData) when(mockFetch)('invalid').afterThrow('error: invalid ID') try { service.fetchData('invalid') } catch (e) { expect(e).assertEqual('error: invalid ID') } }) it('mockFunc_clear_and_restore', 0, function () { let mocker = new MockKit() class Counter { count() { return 1 } } let counter = new Counter() let mockCount = mocker.mockFunc(counter, counter.count) when(mockCount)().afterReturn(10) expect(counter.count()).assertEqual(10) // Mocked // Restore original mocker.clear(counter) expect(counter.count()).assertEqual(1) // Original behavior }) }) } ``` -------------------------------- ### JsUnit Data Driving Test Execution (JavaScript) Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This JavaScript code demonstrates how to import and set the data driving configuration using Hypium. It then executes the Hypium test suite, passing the configured data to the test cases. ```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 Class Methods and Restore Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md Demonstrates mocking class methods, setting return values, and restoring specific methods using ignoreMock. It verifies that mocked methods return modified values while restored methods return original 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. 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. }); }); } ``` -------------------------------- ### JsUnit Data Driving Configuration (data.json) Source: https://github.com/super3001/testfwk_arkxtest/blob/master/README_en.md This JSON file defines the configuration for data driving in JsUnit tests. It specifies test suite names, stress/execution counts, parameters for suites and individual test cases, and the structure for passing data to tests. ```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 }] }] } ``` -------------------------------- ### UI Component Location and Interaction with UiDriver and By in JavaScript Source: https://context7.com/super3001/testfwk_arkxtest/llms.txt Provides utilities for finding and interacting with UI components using various selectors like text, ID, and type. It supports pattern matching, relative positioning, assertions for existence, text input, scrolling, coordinate-based gestures, and screenshot capture. Dependencies include '@ohos.uitest'. ```javascript import { describe, it, expect } from '@ohos.hypium' import { BY, UiDriver, UiComponent, MatchPattern } from '@ohos.uitest' export default async function abilityTest() { describe('UiTestDemo', function() { it('uitest_find_and_click', 0, async function() { // Create UiDriver instance let driver = await UiDriver.create() // Find component by text let button = await driver.findComponent(BY.text('hello').enabled(true)) // Click component await button.click() // Verify component text changed let content = await button.getText() expect(content).assertEqual('clicked!') }) it('uitest_find_by_id', 0, async function() { let driver = await UiDriver.create() // Find by component ID let button = await driver.findComponent(BY.id('submit_button')) await button.click() }) it('uitest_find_with_pattern_matching', 0, async function() { let driver = await UiDriver.create() // Find with text pattern matching let txt = await driver.findComponent( BY.text("hello", MatchPattern.CONTAINS) ) let fullText = await txt.getText() expect(fullText).assertContain('hello') }) it('uitest_relative_positioning', 0, async function() { let driver = await UiDriver.create() // Find switch after specific text let switchComp = await driver.findComponent( BY.id('toggle_switch').isAfter(BY.text("Enable Feature")) ) await switchComp.click() }) it('uitest_assert_component_exists', 0, async function(done) { try { let driver = await UiDriver.create() // Assert component exists await driver.assertComponentExist(BY.text('Login')) // Test passes if component found, throws exception otherwise } finally { done() } }) it('uitest_input_text', 0, async function() { let driver = await UiDriver.create() // Find text input and enter text let editText = await driver.findComponent(BY.type('InputText')) await editText.inputText("user@example.com") let inputValue = await editText.getText() expect(inputValue).assertEqual("user@example.com") }) it('uitest_scroll_to_find', 0, async function() { let driver = await UiDriver.create() // Find scrollable list let list = await driver.findComponent(BY.id('item_list')) // Scroll to find specific item let found = await list.scrollSearch(BY.text("Item3_3")) expect(found).assertTrue() }) it('uitest_coordinate_interaction', 0, async function() { let driver = await UiDriver.create() // Click at specific coordinates await driver.click(100, 200) // Swipe gesture await driver.swipe(100, 500, 100, 100) // Swipe up // Press back button await driver.pressBack() // Delay execution await driver.delayMs(1000) }) it('uitest_capture_screenshot', 0, async function() { let driver = await UiDriver.create() // Capture screen await driver.screenCap('/data/screenshots/test_result.png') }) }) } ```