实现单元测试与UI测试鸿蒙示例代码

鸿蒙场景化示例代码技术工程师
发布于 2025-4-15 11:19
浏览
0收藏

本文原创发布在华为开发者社区

介绍

本示例将介绍如何使用@kit.TestKit编写单元测试脚本,实现单元测试与UI测试。

实现单元测试与UI测试源码链接

效果预览

实现单元测试与UI测试鸿蒙示例代码-鸿蒙开发者社区

使用说明

实现思路

  1. 使用describe定义一个测试套,it定义一条测试用例,expect支持bool类型判断等多种断言方法。
//Promise回调示例
describe('Promise_Done', () => {
  it('Promise_Done', 0, (done: Function) => {
    method_1().then((result: string) => {
      try {
        expect(result).assertEqual('method_1_call');
      } catch (e) {
      } finally {
        // 调用done函数,用例执行完成,必须手动调用done函数,否则出现超时错误。
        done()
      }
    })
  })
})
  1. 断言功能列表、异步代码测试、hamock/hypium插件包的mock接口与import mock。
describe('expectTest', () => {
   it('assertBeClose_success', 0, () => {
     let a: number = 100;
     let b: number = 0.1;
     expect(a).assertClose(99, b);
   })
   it('assertInstanceOf_success', 0, () => {
     let a: string = 'strTest';
     expect(a).assertInstanceOf('String');
   })
   it('assertNaN_success', 0, () => {
     expect(Number.NaN).assertNaN(); // true
   })
   it('assertNegUnlimited_success', 0, () => {
     expect(Number.NEGATIVE_INFINITY).assertNegUnlimited(); // true
   })
   ......
})
  1. 使用Driver、On、Component进行UI测试。
let driver: Driver = Driver.create();
//验证Text1前是否有按钮
const button = await driver.findComponent(ON.text('Text1'));
expect(button !== null).assertTrue();
//click button
await button.click();
//验证是否有Text1
await driver.delayMs(1000);
await driver.pressBack();
......

分类
收藏
回复
举报
回复
    相关推荐