UTSJSONObject.uts 8.0 KB
Newer Older
1
import { describe, test, expect, expectNumber, Result } from './tests.uts'
2
import { mockData } from './data.uts'
3 4 5 6


export function testUTSJSONObject() : Result {
  return describe("utsjsonobject", () => {
7

8
    test('keys', () => {
9 10 11 12 13 14 15 16 17 18 19 20 21
      // #TEST UTSJSONObject.keys
      let obj = {
        name: "zhangsan",
        age: 11
      }

      let ret1 = UTSJSONObject.keys(obj).length
      console.log(ret1) //2
      // #END

      expect(ret1).toEqual(2);
      expect(UTSJSONObject.keys(mockData).length).toEqual(2);

22
    })
23

杜庆泉's avatar
杜庆泉 已提交
24 25
    test('toJSONObject', () => {
      // #ifdef APP-ANDROID
26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45
      let result = {}
      result["opt"] = "xxxx"

      let subArray = [] as Array<UTSJSONObject>
      let subModel = {}
      subModel["name"] = "xxx"
      subModel["type"] = 0
      subArray.push(subModel)

      let service = {}
      service["name"] = "0xxxb34fb"
      service["type"] = 0

      //这个数据返回为空对象数组
      service["array"] = subArray

      result["service"] = service

      expect(result.toJSONObject().toJSONString()).toEqual('{"opt":"xxxx","service":{"array":[{"name":"xxx","type":0}],"name":"0xxxb34fb","type":0}}');

46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61

      type TestData = {
      	num:number;
      	num2:number;
      	str:string;
      }
      
      let data1:TestData = {
      	num:1,
      	num2:2.369,
      	str:'test'
      }
      let data2 = JSON.parse<UTSJSONObject>(JSON.stringify(data1))
      
      expect(data2!.toJSONString()).toEqual('{"str":"test","num":1.0,"num2":2.369}')
      
杜庆泉's avatar
杜庆泉 已提交
62
      class TestData2 implements IJSONStringify{
63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95
      	toJSON():any|null{
      		return "122"
      	}
      }
      
      let testData2 = TestData2()
      let dataClass = UTSAndroid.getJavaClass(data2)
      let data3 = {
      	strA:"stringA",
      	dataClass:dataClass,
      	booleanB:false,
      	testData:testData2
      }
      
      expect(data3!.toJSONString()).toEqual('{"testData":"122","strA":"stringA","dataClass":"io.dcloud.uts.UTSJSONObject","booleanB":false}')
      
      
      type TestData4 = {
      	name:string,
      	data:any,
      }
      
      let data4 : TestData4 = {
      	name:"张三",
      	data:data1
      }
      
      let data5 = {
      	data4 :data4
      }
      
      expect(data5!.toJSONString()).toEqual('{"data4":{"data":{"num":1,"num2":2.369,"str":"test"},"name":"张三"}}')
      
杜庆泉's avatar
杜庆泉 已提交
96 97 98 99 100 101 102 103 104 105 106
      // class TestData6 implements IJsonStringify{
      // 	toJSON():any|null{
      // 		return JSON.parse("22")
      // 	}
      // }
      // let testData6 = TestData6()
      // let data6 = {
      // 	data:testData6,
      // 	array:[1,"22",false],
      // 	name:"data6"
      // }
107
      
杜庆泉's avatar
杜庆泉 已提交
108 109
      // expect(data6!.toJSONString()).toEqual('{"data":22.0,"array":[1,"22",false],"name":"data6"}')
      // console.log(data6.toJSONString())
110
      
杜庆泉's avatar
杜庆泉 已提交
111 112
      // #endif
    })
113

114 115
    test('assign-notype', () => {
      // #ifdef APP-ANDROID
116 117 118 119
      // #TEST UTSJSONObject.assign
      let target = { a: 1, b: 2 };
      let source = { b: 4, c: 5 };
      // 得到一个UTSJSONObject对象
120
      let returnedTarget = UTSJSONObject.assign(target, source);
121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137
      // #END

      expect(returnedTarget.toMap().size).toEqual(3);

      type A = {
        username : string
        age : number
      }
      type C = {
        work : number
      }

      let b = UTSJSONObject.assign({
        username: "张三",
        age: 12
      } as A,
        { b: 2 },
138
        {
139
          work: 0.002
140
        } as C)
141 142 143 144 145 146 147 148
      expect(b['age']).toEqual(12);
      expect(b['username']).toEqual("张三");
      expect(b['b']).toEqual(2);
      expect(b['work']).toEqual(0.002);

      // #TEST UTSJSONObject.assign_1
      let target1 = { a: 1, b: 2 };
      let source1 = { b: 4, c: 5 };
149 150 151
      // 得到一个UTSJSONObject对象
      let returned= UTSJSONObject.assign<UTSJSONObject>(target1, source1);
      console.log(returned)
152 153
      // #END

154 155
      // #endif
    })
156

157 158 159 160 161 162 163 164 165 166
    test('get-no-exist-value', () => {
      // #ifdef APP-ANDROID
      let test = {
      	qq:[11,22]
      }
      expect(test.getNumber("qq[2]")).toEqual(null);
      expect(test.getNumber("qq[2]",999)).toEqual(999);
      
      // #endif
    })
167
    test('setvalue-after-get', () => {
lizhongyi_'s avatar
lizhongyi_ 已提交
168
      // #ifdef APP-ANDROID
169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185
      // #TEST UTSJSONObject.getJSON,UTSJSONObject.getArray
      let obj = {
        "cars": [
          {
            name: "car1",
            value: 100
          }
        ]
      }

      let cars = obj.getArray<UTSJSONObject>("cars")
      cars![0].set("value", 20)
      let firstCar = obj.getJSON("cars[0]")
      console.log(firstCar!['value'])//20
      // #END
      expect(firstCar!['value']).toEqual(20);
      // #endif
186
    })
187 188


杜庆泉's avatar
杜庆泉 已提交
189 190
    test('get-speed', () => {
      // #ifdef APP-ANDROID
191 192 193 194 195 196 197 198 199 200 201 202 203
      // #TEST UTSJSONObject.getString
      const utsObj : UTSJSONObject = {} as any as UTSJSONObject
      for (let i = 0; i < 100; i++) {
        utsObj.set('' + i, '' + i)
      }

      console.log('--start--')
      let startTime = Date.now()
      for (let i = 0; i < 10000; i++) {
        utsObj.getString('0')
      }
      // #END
      let spendTime = Date.now() - startTime
杜庆泉's avatar
杜庆泉 已提交
204
      expect(spendTime < 800).toEqual(true);
205
      // #endif
杜庆泉's avatar
杜庆泉 已提交
206
    })
207

208 209
    test('assign-withtype', () => {
      // #ifdef APP-ANDROID
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244
      type User = {
        a : number
        b : number
      }
      const target = { a: 1, b: 2 };
      const source = { b: 4, c: 5 };
      const returnedTarget = UTSJSONObject.assign<User>(target, source);

      expect(returnedTarget!.a).toEqual(1);
      console.log(returnedTarget)
      // #endif
    })
    test('getArray_1', () => {
      // #ifdef APP-ANDROID
      // #TEST UTSJSONObject.getArray_1
      //这个方法用来获取指定元素类型的数组
      let obj = JSON.parseObject('{"name":"tom","tag":["student","user"]}')

      // 这里得到是 Array<*>
      let noGenericArray = obj!.getArray("tag")
      console.log(noGenericArray)

      // 这里得到是 Array<string>
      let genericArray = obj!.getArray<string>("tag")
      console.log(genericArray)
      // #END
      // #endif
    })

    test('sample', () => {
      // #TEST UTSJSONObject.sample_create,UTSJSONObject.get,UTSJSONObject.set
      const person : UTSJSONObject = {
        name: 'Tom',
        printName: () => {
          // ...
245
        }
246 247
      }
      //返回指定键对应的值,如果对象中不存在此键则返回 null。
248
      let name : string = person["name"] as String
249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280
      //get 方法可以简化为使用下标运算符 `[]` 访问
      name = person['name'] as string
      //增加或更新指定键对应的值。
      person.set('name', 'Tom1')
      //set 方法可以简化为使用下标运算符 `[]` 赋值
      person['name'] = 'Tom2'
      // #END

      // #TEST UTSJSONObject.sample_create1

      // 写法1 推荐
      let person1 : UTSJSONObject = JSON.parseObject('{"name":"Tom"}')!

      // 写法2 推荐
      const person2 : UTSJSONObject = JSON.parse<UTSJSONObject>('{"name":"Tom"}')!


      // 写法3  如果 as 转换的实际类型不匹配 会导致 crash,建议先通过 `instanceof` 判断类型再进行as转换。
      const parseRet3 = JSON.parse('{"name":"Tom"}')
      if (parseRet3 instanceof UTSJSONObject) {
        const person = parseRet3 as UTSJSONObject
      }

      // #END
      // #TEST UTSJSONObject.toMap
      person1 = JSON.parseObject('{"name":"Tom"}')!
      person1.toMap().forEach((value, key) => {
        console.log(key)
        console.log(value)
      })
      // #END

281

282 283 284 285 286 287 288 289 290 291
       // #TEST UTSJSONObject.convert
      type User = {
        name : string,
        age : number
      }
      let jsonObj = {
        name: "张三",
        age: 12
      }
      // UTSJSONObject => 自定义type
292
      let userA = JSON.parse<User>(JSON.stringify(jsonObj)!)
293 294
      console.log(userA!.name)
      // 自定义type => UTSJSONObject
295
      let utsJsonA = JSON.parseObject(JSON.stringify(userA)!)
296 297
      console.log(utsJsonA)
       // #END
298

299
    })
雪洛's avatar
雪洛 已提交
300 301 302 303 304 305 306 307 308
    
    test('useless-as', () => {
      const obj = {
        a: { b: { c: 'c' } }
      };
      ((obj["a"] as UTSJSONObject)["b"] as UTSJSONObject)["c"] = "c1"
      expect(obj.getString("a.b.c")).toEqual('c1')
      
    })
309 310
  })
}