### Start JsUnit Test Execution with Hypium.hypiumTest() Source: https://context7.com/openharmony/arkxtest/llms.txt This is the main entry point for the JsUnit unit testing framework. It handles service registration, argument parsing, report initialization, and UI test environment setup before executing all test cases. ```typescript import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; import { Hypium } from '@ohos/hypium'; import testsuite from '../test/List.test'; export default class TestAbility extends Ability { onCreate(want, launchParam) { console.info('TestAbility onCreate'); } onWindowStageCreate(windowStage: window.WindowStage) { const abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); const abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments(); console.info('start run testcase!!!'); // 启动测试框架,自动注册断言服务、报告服务,并执行所有测试用例 Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite); } } ``` -------------------------------- ### Hypium.hypiumTest() - Start Test Execution Entry Source: https://context7.com/openharmony/arkxtest/llms.txt `Hypium.hypiumTest()` is the main entry point for the unit testing framework. It initializes services, parses arguments, sets up reporting, and automatically initializes the UI testing environment if detected, before executing all test cases. ```APIDOC ## Hypium.hypiumTest() - Start Test Execution Entry ### Description `Hypium.hypiumTest()` is the main entry point for the unit testing framework. It initializes services, parses arguments, sets up reporting, and automatically initializes the UI testing environment if detected, before executing all test cases. ### Method ```typescript Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite) ``` ### Parameters - **abilityDelegator**: An instance of AbilityDelegator used for interacting with the system. - **abilityDelegatorArguments**: Arguments passed to the delegator. - **testsuite**: A function or module containing the test cases. ### Request Example ```typescript // TestAbility/TestAbility.ts import AbilityDelegatorRegistry from '@ohos.application.abilityDelegatorRegistry'; import { Hypium } from '@ohos/hypium'; import testsuite from '../test/List.test'; export default class TestAbility extends Ability { onCreate(want, launchParam) { console.info('TestAbility onCreate'); } onWindowStageCreate(windowStage: window.WindowStage) { const abilityDelegator = AbilityDelegatorRegistry.getAbilityDelegator(); const abilityDelegatorArguments = AbilityDelegatorRegistry.getArguments(); console.info('start run testcase!!!'); // Start the test framework, automatically register assertion and reporting services, and execute all test cases Hypium.hypiumTest(abilityDelegator, abilityDelegatorArguments, testsuite); } } ``` ``` -------------------------------- ### UiWindow Operations Source: https://context7.com/openharmony/arkxtest/llms.txt Demonstrates how to use the UiWindow object to perform operations on a UI window, such as finding, getting properties, moving, resizing, splitting, and closing. ```APIDOC ## UiWindow Operations ### Description This section details the operations that can be performed on a `UiWindow` object, which represents a window on the user interface. These operations include finding a window, retrieving its properties, and managing its state (moving, resizing, splitting, closing). ### Methods - `UiDriver.findWindow({ actived: true })`: Finds the currently active window. - `activeWindow.getBundleName()`: Retrieves the package name of the window. - `activeWindow.getTitle()`: Retrieves the title of the window. - `activeWindow.moveTo(x, y)`: Moves the window to the specified coordinates (x, y). Returns a boolean indicating success. - `activeWindow.resize(width, height, direction)`: Resizes the window to the specified width and height. The `direction` parameter specifies the resize direction (e.g., RIGHT_DOWN). - `activeWindow.split()`: Switches the window to split-screen mode. Returns a boolean indicating success. - `activeWindow.close()`: Closes the window. Returns a boolean indicating success. ### Example Usage ```typescript import { describe, it, expect } from '@ohos/hypium'; import { BY, UiDriver, UiWindow } from '@ohos.uitest'; export default async function uiWindowDemo() { describe('UiWindowDemo', () => { it('window_operations', 0, async (done) => { const driver = await UiDriver.create(); // 1. Find the current active window const activeWindow: UiWindow = await driver.findWindow({ actived: true }); // 2. Read window properties const bundleName: string = await activeWindow.getBundleName(); const title: string = await activeWindow.getTitle(); console.info(`Current app bundle name: ${bundleName}`); console.info(`Window title: ${title}`); expect(bundleName).assertContain('com.example'); // 3. Move the window to a specified position (only for movable windows) const moved: boolean = await activeWindow.moveTo(100, 200); console.info(`Move result: ${moved}`); // 4. Resize the window (drag to expand towards bottom-right) // ResizeDirection: LEFT=0, RIGHT=1, UP=2, DOWN=3, LEFT_UP=4, LEFT_DOWN=5, RIGHT_UP=6, RIGHT_DOWN=7 const resized: boolean = await activeWindow.resize(800, 600, 7); // RIGHT_DOWN console.info(`Resize result: ${resized}`); // 5. Switch to split-screen mode const split: boolean = await activeWindow.split(); console.info(`Split result: ${split}`); // 6. Close the window const closed: boolean = await activeWindow.close(); expect(closed).assertTrue(); done(); }); }); } ``` ``` -------------------------------- ### BY Selector Chaining Example Source: https://context7.com/openharmony/arkxtest/llms.txt Illustrates advanced component selection using the BY class with chained methods for various attributes and relative positioning. Supports exact, contains, and starts-with text matching. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { BY, UiDriver, UiComponent, MatchPattern } from '@ohos.uitest'; export default async function byDemo() { describe('ByDemo', () => { it('by_chaining_selectors', 0, async (done) => { const driver = await UiDriver.create(); // 1. 按 id 查找 const submitBtn: UiComponent = await driver.findComponent(BY.id('btn_submit')); // 2. 多属性组合:id + 可点击状态 const enabledBtn: UiComponent = await driver.findComponent( BY.id('btn_next').enabled(true).clickable(true) ); // 3. 文本模糊匹配(CONTAINS 模式) const hint: UiComponent = await driver.findComponent( BY.text('请输入', MatchPattern.CONTAINS) ); // 4. 前缀匹配(STARTS_WITH 模式) const item: UiComponent = await driver.findComponent( BY.text('商品', MatchPattern.STARTS_WITH) ); // 5. 相对定位:查找位于 "用户名" 标签之后的输入框 const usernameInput: UiComponent = await driver.findComponent( BY.type('InputText').isAfter(BY.text('用户名')) ); if (usernameInput) { await usernameInput.inputText('test_user'); const inputValue = await usernameInput.getText(); expect(inputValue).assertEqual('test_user'); } // 6. 相对定位:查找位于 "提交" 按钮之前的复选框 const agreeCheckbox: UiComponent = await driver.findComponent( BY.type('Checkbox').isBefore(BY.text('提交')) ); // 7. 可滚动列表中滑动查找子控件 const list: UiComponent = await driver.findComponent(BY.id('list_orders').scrollable(true)); const targetItem = await list.scrollSearch(BY.text('订单-2024001')); expect(targetItem).assertTrue(); done(); }); }); } ``` -------------------------------- ### UiDriver Full Flow Example Source: https://context7.com/openharmony/arkxtest/llms.txt Demonstrates the complete lifecycle of UI testing using UiDriver, including component finding, interaction, assertion, and screen capture. Requires `hdc_std shell param set persist.ace.testmode.enabled 1` to be run on the device beforehand. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { BY, UiDriver, UiComponent, MatchPattern } from '@ohos.uitest'; export default async function uiDriverDemo() { describe('UiDriverDemo', () => { it('uitest_full_flow', 0, async (done) => { try { // 1. 创建 UiDriver 实例(静态工厂方法) const driver: UiDriver = await UiDriver.create(); // 2. 延时等待界面渲染 await driver.delayMs(500); // 3. 按文本查找按钮控件(精确匹配) const loginBtn: UiComponent = await driver.findComponent(BY.text('登录')); expect(loginBtn !== null).assertTrue(); // 4. 点击按钮 await loginBtn.click(); await driver.delayMs(1000); // 5. 断言特定控件存在(若不存在则用例直接失败) await driver.assertComponentExist(BY.text('欢迎回来')); // 6. 按坐标点击 await driver.click(540, 960); // 7. 基于坐标滑动(从底部向上滑动) await driver.swipe(540, 1600, 540, 400); // 8. 截图保存 await driver.screenCap('/data/storage/el2/base/test_screenshot.png'); // 9. 按 BACK 键 await driver.pressBack(); } finally { done(); } }); }); } ``` -------------------------------- ### UiComponent Operations Example Source: https://context7.com/openharmony/arkxtest/llms.txt Demonstrates common operations on a UiComponent instance, such as reading properties (text, ID, type, enabled state), inputting text, and performing scroll searches within lists. Ensure the component is focused before inputting text. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { BY, UiDriver, UiComponent } from '@ohos.uitest'; export default async function uiComponentDemo() { describe('UiComponentDemo', () => { it('component_operations', 0, async (done) => { const driver = await UiDriver.create(); // 读取控件属性 const title: UiComponent = await driver.findComponent(BY.id('tv_title')); const text: string = await title.getText(); const compId: number = await title.getId(); const type: string = await title.getType(); const isEnabled: boolean = await title.isEnabled(); expect(text).assertContain('首页'); expect(isEnabled).assertTrue(); console.info(`控件类型: ${type}, ID: ${compId}`); // 输入文本到输入框 const searchBox: UiComponent = await driver.findComponent(BY.type('InputText').focused(false)); await searchBox.click(); // 先点击获得焦点 await searchBox.inputText('OpenHarmony'); const inputContent = await searchBox.getText(); expect(inputContent).assertEqual('OpenHarmony'); // 点击搜索按钮 const searchBtn: UiComponent = await driver.findComponent(BY.text('搜索').clickable(true)); await searchBtn.click(); await driver.delayMs(1500); // 在列表中滑动查找 const resultList: UiComponent = await driver.findComponent(BY.id('rv_results')); const firstResult = await resultList.scrollSearch(BY.text('OpenHarmony 入门教程')); expect(firstResult).assertTrue(); done(); }); }); } ``` -------------------------------- ### Verifying Function Calls with Verify Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md This snippet demonstrates the setup for using the 'verify' function, which is used to check if a mocked function was called. Further steps would involve calling the mocked functions and then using 'verify' to assert the calls. ```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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(...arg) { return '888888'; } method_2(...arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1和method_2两个函数进行mock mocker.mockFunc(claser, claser.method_1); mocker.mockFunc(claser, claser.method_2); //4.我们来做一些调用,如下 ``` -------------------------------- ### Hypium expect() Full Assertion API Example Source: https://context7.com/openharmony/arkxtest/llms.txt Demonstrates the usage of various assertion methods provided by the expect() function in Hypium. Ensure necessary imports are present. Note that assertClose has a tolerance parameter for precision. ```typescript import { describe, it, expect } from '@ohos/hypium'; export default function assertDemoTest() { describe('AssertDemo', () => { it('assert_all_apis', 0, () => { // assertEqual: 严格相等 expect(42).assertEqual(42); // assertClose: 数值精度比较,|actual - expected[0]| <= expected[1] expect(100).assertClose(99, 0.1); // |100-99|=1 > 0.1,此用例会失败 expect(100).assertClose(100.05, 0.1); // 通过 // assertContain: 字符串包含 expect('hello world').assertContain('world'); // assertTrue / assertFalse expect(true).assertTrue(); expect(false).assertFalse(); // assertNull / assertUndefined expect(null).assertNull(); expect(undefined).assertUndefined(); // assertInstanceOf: 类型检查(传入类型名称字符串) expect('abc').assertInstanceOf('String'); expect(123).assertInstanceOf('Number'); // assertLarger / assertLess expect(10).assertLarger(5); expect(3).assertLess(7); // assertThrowError: 验证抛出的错误消息 expect(() => { throw new Error('invalid input'); }).assertThrowError('invalid input'); // assertFail: 直接使当前用例失败 // expect(0).assertFail(); // 取消注释则强制失败 }); }); } ``` -------------------------------- ### Hypium Data-Driven Test Case Implementation Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Example of implementing test cases for data-driven testing in Hypium. Supports asynchronous tests with parameters and simple stress tests. ```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'); }); }); } ``` -------------------------------- ### expect() Assertion Methods Source: https://context7.com/openharmony/arkxtest/llms.txt The expect() function returns an Assert object with 12 assertion methods. This example demonstrates the usage of various assertion methods including assertEqual, assertClose, assertContain, assertTrue, assertFalse, assertNull, assertUndefined, assertInstanceOf, assertLarger, assertLess, assertThrowError, and assertFail. ```APIDOC ## expect() ### Description The `expect(actualValue)` function returns an `Assert` object that provides 12 assertion methods. Any assertion failure will cause the current test case to be marked as FAIL and output an error message. ### Usage ```typescript import { describe, it, expect } from '@ohos/hypium'; export default function assertDemoTest() { describe('AssertDemo', () => { it('assert_all_apis', 0, () => { // assertEqual: strict equality expect(42).assertEqual(42); // assertClose: numerical precision comparison, |actual - expected[0]| <= expected[1] expect(100).assertClose(99, 0.1); // |100-99|=1 > 0.1, this case will fail expect(100).assertClose(100.05, 0.1); // Pass // assertContain: string containment expect('hello world').assertContain('world'); // assertTrue / assertFalse expect(true).assertTrue(); expect(false).assertFalse(); // assertNull / assertUndefined expect(null).assertNull(); expect(undefined).assertUndefined(); // assertInstanceOf: type check (pass type name string) expect('abc').assertInstanceOf('String'); expect(123).assertInstanceOf('Number'); // assertLarger / assertLess expect(10).assertLarger(5); expect(3).assertLess(7); // assertThrowError: verify thrown error message expect(() => { throw new Error('invalid input'); }).assertThrowError('invalid input'); // assertFail: directly cause the current case to fail // expect(0).assertFail(); // Uncomment to force failure }); }); } ``` ### Methods - **assertEqual(expectedValue)**: Checks if the actual value is strictly equal to the expected value. - **assertClose(expectedValue, delta)**: Checks if the absolute difference between the actual value and the expected value is within the specified delta. - **assertContain(substring)**: Checks if the actual string contains the specified substring. - **assertTrue()**: Checks if the actual value is strictly true. - **assertFalse()**: Checks if the actual value is strictly false. - **assertNull()**: Checks if the actual value is null. - **assertUndefined()**: Checks if the actual value is undefined. - **assertInstanceOf(typeName)**: Checks if the actual value is an instance of the specified type name. - **assertLarger(expectedValue)**: Checks if the actual value is strictly larger than the expected value. - **assertLess(expectedValue)**: Checks if the actual value is strictly less than the expected value. - **assertThrowError(errorMessage)**: Checks if the function call throws an error with the specified message. - **assertFail()**: Directly causes the current test case to fail. ``` -------------------------------- ### UI Test Case with Component Interaction Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Example of a UI test case using UiDriver to find a component by text, click it, and assert its text content. Requires 'await' for asynchronous operations. ```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!') }) }) } ``` -------------------------------- ### Mock System Function with MockKit Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Illustrates how to mock a system function, `app.getInfo`, using `MockKit`. It sets a return value for the mocked function and then asserts the result. ```javascript export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { it('test_systemApi', 0, function () { //1.创建MockKit对象 let mocker = new MockKit(); //2.mock app.getInfo函数 let mockf = mocker.mockFunc(app, app.getInfo); when(mockf)('test').afterReturn('1'); //执行成功案例 expect(app.getInfo('test')).assertEqual('1'); }); }); } ``` -------------------------------- ### Using ArgumentMatchers.any for Parameter Matching Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates how to use `ArgumentMatchers.any` to accept any parameter type (excluding `undefined` and `null`) for a mocked function. This requires importing the `ArgumentMatchers` class. ```javascript import {describe, expect, it, MockKit, when, ArgumentMatchers} from '@ohos/hypium'; export default function ActsAbilityTest() { describe('ActsAbilityTest', function () { ``` -------------------------------- ### SysTestKit: System Interaction and Performance Analysis Source: https://context7.com/openharmony/arkxtest/llms.txt SysTestKit provides utilities for interacting with the OpenHarmony system. Use `actionStart`/`actionEnd` for performance interval marking and `existKeyword` to verify system behavior via hilog. ```typescript import { describe, it, expect, SysTestKit } from '@ohos/hypium'; export default function sysTestKitDemo() { describe('SysTestKitDemo', () => { it('sys_actionStartEnd', 0, async (done) => { // 标记性能区间开始(输出 OHOS_REPORT_ACTIONSTART 到日志) SysTestKit.actionStart('load_homepage'); // 模拟操作... await new Promise(res => setTimeout(res, 500)); // 标记区间结束(输出 OHOS_REPORT_ACTIONEND 到日志) SysTestKit.actionEnd('load_homepage'); done(); }); it('sys_existKeyword', 0, async (done) => { // 搜索 hilog 日志中是否存在关键字 'loginSuccess',等待最多 4 秒 const found: boolean = await SysTestKit.existKeyword('loginSuccess', 4); // 预期登录流程已产生该关键字日志 expect(found).assertTrue(); done(); }); }); } ``` -------------------------------- ### 推送UI测试框架到设备 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 将编译好的UI测试框架文件推送到设备指定路径,并赋予执行权限。此操作用于在设备上部署自定义构建的框架。 ```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 ``` -------------------------------- ### 使能UI测试框架 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 通过设置系统参数来使能UI测试框架。此命令需要在设备上执行。 ```shell hdc_std shell param set persist.ace.testmode.enabled 1 ``` -------------------------------- ### Perform UiWindow Operations Source: https://context7.com/openharmony/arkxtest/llms.txt Demonstrates how to find an active window, read its properties (bundle name, title), move, resize, split into a split-screen mode, and close the window. Ensure the window supports these operations before attempting them. ```typescript import { describe, it, expect } from '@ohos/hypium'; import { BY, UiDriver, UiWindow } from '@ohos.uitest'; export default async function uiWindowDemo() { describe('UiWindowDemo', () => { it('window_operations', 0, async (done) => { const driver = await UiDriver.create(); // 1. 查找当前激活窗口 const activeWindow: UiWindow = await driver.findWindow({ actived: true }); // 2. 读取窗口属性 const bundleName: string = await activeWindow.getBundleName(); const title: string = await activeWindow.getTitle(); console.info(`当前应用包名: ${bundleName}`); console.info(`窗口标题: ${title}`); expect(bundleName).assertContain('com.example'); // 3. 移动窗口到指定位置(仅适用于支持移动的窗口) const moved: boolean = await activeWindow.moveTo(100, 200); console.info(`移动结果: ${moved}`); // 4. 调整窗口大小(向右下方向拖拽扩大) // ResizeDirection: LEFT=0, RIGHT=1, UP=2, DOWN=3, LEFT_UP=4, LEFT_DOWN=5, RIGHT_UP=6, RIGHT_DOWN=7 const resized: boolean = await activeWindow.resize(800, 600, 7); // RIGHT_DOWN console.info(`调整大小结果: ${resized}`); // 5. 切换为分屏模式 const split: boolean = await activeWindow.split(); console.info(`分屏结果: ${split}`); // 6. 关闭窗口 const closed: boolean = await activeWindow.close(); expect(closed).assertTrue(); done(); }); }); } ``` -------------------------------- ### 关闭UiWindow Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 查找当前激活的UiWindow并执行关闭操作。此方法用于结束窗口的生命周期。 ```javascript let window = await driver.findWindow({actived: true}) await window.close() ``` -------------------------------- ### Create UiDriver and Assert Component Existence Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md This snippet demonstrates how to create a UiDriver instance and assert the existence of a component with the text 'hello'. It requires importing BY, UiDriver, and UiComponent from '@ohos.uitest'. ```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() } }) }) } ``` -------------------------------- ### 构建UI测试框架 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 使用指定的构建命令来编译UI测试框架。此命令用于开发者自行构建框架。 ```shell ./build.sh --product-name rk3568 --build-target uitestkit ``` -------------------------------- ### Mocking with ArgumentMatchers.any Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates mocking a class method using ArgumentMatchers.any to match any argument. Use this when the specific argument value does not matter for the mock behavior. ```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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1函数进行mock let mockfunc = mocker.mockFunc(claser, claser.method_1); //根据自己需求进行选择参数匹配器和预期方法, when(mockfunc)(ArgumentMatchers.any).afterReturn('1'); //4.对mock后的函数进行断言,看是否符合预期,注意选择跟第4步中对应的断言方法 //执行成功的案例1,传参为字符串类型 expect(claser.method_1('test')).assertEqual('1'); //用例执行通过。 //执行成功的案例2,传参为数字类型123 expect(claser.method_1(123)).assertEqual('1');//用例执行通过。 //执行成功的案例3,传参为boolean类型true expect(claser.method_1(true)).assertEqual('1');//用例执行通过。 //执行失败的案例,传参为数字类型空 //expect(claser.method_1()).assertEqual('1');//用例执行失败。 }); }); } ``` -------------------------------- ### 断言检查UiComponent属性 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 获取UiComponent的实例后,可以使用assert*接口进行断言检查,验证控件是否存在或属性是否符合预期。 ```javascript let component = await driver.findComponent(BY.id(Id_title)) expect(component !== null).assertTrue() ``` -------------------------------- ### Mocking a Class Method with afterReturn Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates how to mock a specific method of a class instance and define a custom return value using `afterReturn`. Ensure the `MockKit` and `when` APIs are imported. The `when` function takes the mocked function and a specific argument to match. ```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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1函数进行mock let mockfunc = mocker.mockFunc(claser, claser.method_1); when(mockfunc)('test').afterReturn('1'); //4.对mock后的函数进行断言,看是否符合预期 //执行成功案例,参数为'test' expect(claser.method_1('test')).assertEqual('1'); //执行通过 //执行失败案例,参数为 'abc' //expect(claser.method_1('abc')).assertEqual('1');//执行失败 }); }); } ``` -------------------------------- ### 移动UiWindow到指定位置 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 查找当前激活的UiWindow并将其移动到屏幕上的指定坐标。此功能仅适用于支持窗口移动的窗口类型。 ```javascript let window = await driver.findWindow({actived: true}) await window.moveTo(500,500) ``` -------------------------------- ### Mocking with ArgumentMatchers.anyString Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates mocking a class method using ArgumentMatchers.anyString to match only string arguments. Use this when the mocked function should only respond to string inputs. ```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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1函数进行mock let mockfunc = mocker.mockFunc(claser, claser.method_1); //根据自己需求进行选择 when(mockfunc)(ArgumentMatchers.anyString).afterReturn('1'); //4.对mock后的函数进行断言,看是否符合预期,注意选择跟第4步中对应的断言方法 //执行成功的案例,传参为字符串类型 expect(claser.method_1('test')).assertEqual('1'); //用例执行通过。 expect(claser.method_1('abc')).assertEqual('1'); //用例执行通过。 //执行失败的案例,传参为数字类型 //expect(claser.method_1(123)).assertEqual('1');//用例执行失败。 //expect(claser.method_1(true)).assertEqual('1');//用例执行失败。 }); }); } ``` -------------------------------- ### Mocking with ArgumentMatchers.matchRegexs Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates mocking a class method using ArgumentMatchers.matchRegexs to match arguments against a regular expression. Use this when the input string must conform to a specific 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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(arg) { return '888888'; } method_2(arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1函数进行mock let mockfunc = mocker.mockFunc(claser, claser.method_1); //根据自己需求进行选择,这里假设匹配正则,且正则为/123456/ when(mockfunc)(ArgumentMatchers.matchRegexs(/123456/)).afterReturn('1'); //4.对mock后的函数进行断言,看是否符合预期,注意选择跟第4步中对应的断言方法 //执行成功的案例,传参为字符串 比如 '1234567898' expect(claser.method_1('1234567898')).assertEqual('1'); //用例执行通过。 //因为字符串 '1234567898'可以和正则/123456/匹配上 //执行失败的案例,传参为字符串'1234' //expect(claser.method_1('1234')).assertEqual('1');//用例执行失败。反之 }); }); } ``` -------------------------------- ### Mocking and Verifying Functions with MockKit Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates mocking class methods, defining their behavior using `when` and `afterReturn`, and verifying call counts with `mocker.verify`. Note that `mocker.verify` with specific arguments might fail if the exact call signature isn't matched. ```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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } method_1(...arg) { return '888888'; } method_2(...arg) { return '999999'; } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1和method_2两个函数进行mock let func_1 = mocker.mockFunc(claser, claser.method_1); let func_2 = mocker.mockFunc(claser, claser.method_2); //4.对mock后的函数的行为进行修改 when(func_1)(ArgumentMatchers.anyNumber).afterReturn('4'); when(func_2)(ArgumentMatchers.anyNumber).afterReturn('5'); //5.我们来做一些调用,如下 console.log(claser.method_1(123)); //执行结果是4,符合步骤4中的预期 console.log(claser.method_2(456)); //执行结果是5,符合步骤4中的预期 //6.现在对mock后的两个函数的其中一个函数method_1进行忽略处理(原理是就是还原) mocker.ignoreMock(claser, claser.method_1); //然后再去调用 claser.method_1函数,看执行结果 console.log(claser.method_1(123)); //执行结果是888888,发现这时结果跟步骤4中的预期不一样了,执行了claser.method_1没被mock之前的结果 //用断言测试 expect(claser.method_1(123)).assertEqual('4'); //结果为failed 符合ignoreMock预期 claser.method_2(456); //执行结果是5,因为method_2没有执行ignore忽略,所有也符合步骤4中的预期 }); }); } ``` -------------------------------- ### Importing and Setting Data for Hypium Tests Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Import the data.json configuration and set it using Hypium.setData() before executing tests with Hypium.hypiumTest(). ```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 Asynchronous Function with MockKit Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md Demonstrates mocking an asynchronous method of a class using `MockKit`. It shows how to define mock behavior using `afterReturn` with a Promise and execute the 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.创建一个mock能力的对象MockKit let mocker = new MockKit(); //2.定类ClassName,里面两个函数,然后创建一个对象claser class ClassName { constructor() { } async method_1(arg) { return new Promise((res, rej) => { //做一些异步操作 setTimeout(function () { console.log('执行'); res('数据传递'); }, 2000); }); } } let claser = new ClassName(); //3.进行mock操作,比如需要对ClassName类的method_1函数进行mock let mockfunc = mocker.mockFunc(claser, claser.method_1); //4.根据自己需求进行选择 执行完毕后的动作,比如这里我选择afterRetrun; 可以自定义返回一个promise when(mockfunc)('test').afterReturn(new Promise((res, rej) => { console.log("do something"); res('success something'); })); //5.执行mock后的函数,即对定义的promise进行后续执行 claser.method_1('test').then(function (data) { //数据处理代码... console.log('result : ' + data); }); }); }); } ``` -------------------------------- ### UiWindow API Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md UiWindow 类代表 UI 界面上的一个窗口,可以通过 findWindow 方法找到。它提供了获取窗口属性、移动窗口、调整窗口大小、关闭窗口等操作。 ```APIDOC ## UiWindow API ### Description `UiWindow`类代表了Ui界面上的一个窗口,一般是通过`UiDriver.findWindow(by)`方法查找到的。通过该类的实例,用户可以获取窗口属性,并进行窗口拖动、调整窗口大小等操作。 ### Methods - **getBundleName()**: Promise - 获取窗口所属应用包名。 - **getTitle()**: Promise - 获取窗口标题信息。 - **focus()**: Promise - 使得当前窗口获取焦点。 - **moveTo**(x: number, y: number): Promise - 将当前窗口移动到指定位置(适用于支持移动的窗口)。 - **resize**(wide: number, height: number, direction: ResizeDirection): Promise - 调整窗口大小(适用于支持调整大小的窗口)。 - **split()**: Promise - 将窗口模式切换为分屏模式(适用于支持分屏的窗口)。 - **close()**: Promise - 关闭当前窗口。 ### Examples **示例代码1**: 获取窗口属性。 ```javascript let window = await driver.findWindow({actived: true}) let bundelName = await window.getBundleName() ``` **示例代码2**: 移动窗口。 ```javascript let window = await driver.findWindow({actived: true}) await window.moveTo(500,500) ``` **示例代码3**: 关闭窗口。 ```javascript let window = await driver.findWindow({actived: true}) await window.close() ``` ``` -------------------------------- ### JsUnit 基础流程和断言示例 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 展示了JsUnit框架中describe, it, expect等基础API的使用,以及assertContain和assertEqual断言方法。适用于编写和执行基础单元测试用例。 ```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) }) }) }) } ``` -------------------------------- ### 获取UiWindow的包名 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 查找当前激活的UiWindow并获取其所属的应用包名。此操作适用于需要验证窗口归属的场景。 ```javascript let window = await driver.findWindow({actived: true}) let bundelName = await window.getBundleName() ``` -------------------------------- ### 在List控件中滑动查找子控件 Source: https://github.com/openharmony/arkxtest/blob/master/README_zh.md 在List类型的UiComponent上执行滑动操作,以查找包含特定文本的子控件。此方法适用于需要滚动才能显示的列表项。 ```javascript let list = await driver.findComponent(BY.id(Id_list)) let found = await list.scrollSearch(BY.text("Item3_3")) expect(found).assertTrue() ```