欢迎访问艾立兹站 Aliz- 专注建站教程与技术分享
您当前的位置:首页 > 鸿蒙开发

鸿蒙单元测试中使用TextDecoder异常解决办法

时间:2025-12-25 12:29:54  来源:互联网  作者:奔波霸  阅读:

使用 TextDecoder 将 Uint8Array 转换成string时,如果在单元测试中执行此方法,会报undefined is not callable;初步定位是TextDecoder不支持在单元测试中执行。

目前 鸿蒙上有两种方式可以将Uint8Array转换成string,一种是使用buffer的方式,一种是使用TextDecoder;buffer的方式单元测试中可以执行,两种方式参考代码如下

 
 
 
 
 
let uint8Array: Uint8Array = new Uint8Array([72, 101, 108, 108, 111]);
// 方式1:使用buffer转换uint8Array,单元测试可以使用
let uint8Buffer = buffer.from(uint8Array);
console.log('Str1 : ' + uint8Buffer.toString()); // Hello

// 方式2:使用TextDecoder 转换,单元测试中报undefined is not callable
let textDecoder = util.TextDecoder.create('utf-8', {
  fatal: true,
  ignoreBOM: true
})
const result = textDecoder.decodeToString(uint8Array);
console.log('Str2 : ' + result); // Hello

本文配套模板、静态源码可前往艾立兹素材库alisucai.com下载

发表评论 共有0条评论
发表评论 共有条评论
用户名: 密码:
验证码: 匿名发表
公众号二维码

扫码关注公众号
获取全套技术教程