提交 bca10f41 编写于 作者: Y yurj26

feat: add uts-tests

上级 820fb313
module.exports = {
"is-custom-runtime": false,
"compile": true,
"h5": {
"options": {
"headless": true
},
"executablePath": ""
},
"mp-weixin": {
"port": 9420,
"account": "",
"args": "",
"cwd": "",
"launch": true,
"teardown": "disconnect",
"remote": false,
"executablePath": ""
},
"app-plus": {
"android": {
"id": "emulator-5554",
"executablePath": "/Users/yuanrenjie/Desktop/HBuilderX-Alpha.app/Contents/HBuilderX/plugins/launcher/base/android_base.apk"
},
"version": "/Users/yuanrenjie/Desktop/HBuilderX-Alpha.app/Contents/HBuilderX/plugins/launcher/base/version.txt",
"ios": {
"id": "",
"executablePath": ""
}
}
}
\ No newline at end of file
const {
readFileSync,
readdirSync
} = require('fs')
const {
extname,
resolve
} = require('path')
const describeRE = /describe\(["|'](.*)["|']/
const testsRE = /test\(["|'](.*)["|']/g
function parse(content) {
const describes = content.match(describeRE)
if (!describes) {
return
}
const describe = describes[1]
const tests = []
let test
while (test = testsRE.exec(content)) {
tests.push(test[1])
}
return {
describe,
tests
}
}
function parseDescribes() {
const dir = resolve(__dirname, 'uni_modules/uts-tests/utssdk')
const describes = []
readdirSync(dir).forEach(file => {
if (extname(file) === '.uts') {
describes.push(parse(readFileSync(resolve(dir, file), 'utf8')))
}
})
return describes
};
module.exports = {
testTimeout: 10000,
reporters: [
'default'
],
globals: {
describes: parseDescribes()
},
watchPathIgnorePatterns: ['/node_modules/', '/dist/', '/.git/'],
moduleFileExtensions: ['js', 'json'],
rootDir: __dirname,
testMatch: ["<rootDir>/pages/**/*test.[jt]s?(x)"],
testPathIgnorePatterns: ['/node_modules/']
}
......@@ -161,7 +161,15 @@
"enablePullDownRefresh": false
}
}
},
{
"path" : "pages/test/index",
"style" :
{
"navigationBarTitleText": "",
"enablePullDownRefresh": false
}
}
],
......
const ERR_RE = /expected:<(.*)> but was:<(.*)>/
let result;
beforeAll(async () => {
await program.reLaunch('/pages/test/index')
page = await program.currentPage()
await page.waitFor(3000);
const data = await page.data('result');
result = data
})
function getApiFailed(describe, api) {
const failed = result[describe]?.failed?.find(item => {
return item.split(':')[0] === api
})
return failed
}
describes.forEach(d => {
d?.describe && describe(d.describe, () => {
d?.tests && d.tests.forEach(api => {
it(api, ()=>{
const failed = getApiFailed(d.describe, api)
if (failed) {
const parts = failed.split('\n')
const matches = parts[1].match(ERR_RE)
if (matches?.length) {
expect(matches[2]).toEqual(matches[1])
} else {
expect(parts[1]).toEqual('')
}
}
})
})
})
})
<template>
<view class="content">
<view v-for="(item,name) in result" :key="name" class="result">
<view>{{name}}测试结果:</view>
<view>
测试api:{{item.passed.join(', ')}}
</view>
<view>总共:{{item.total}}</view>
<view>通过:{{item.passed.length}}</view>
<view>失败:{{item.failed.length}}</view>
<view v-for="(fail,index) in item.failed" :key="index" class="failed">
<view>{{fail.split('\n')[0]}}</view>
<view>{{fail.split('\n')[1]}}</view>
</view>
</view>
</view>
</template>
<script>
import {
runTests
} from '../../uni_modules/uts-tests'
export default {
data() {
return {
result: {}
}
},
onReady() {
this.test()
},
methods: {
test() {
this.result = runTests()
console.log(this.result)
}
}
}
</script>
<style>
.content {
padding: 32rpx;
}
.passed {
color: green;
}
.failed {
color: red;
}
.result {
margin-bottom: 20rpx;
}
</style>
{
"id": "uts-tests",
"displayName": "uts-tests",
"version": "1.0.0",
"description": "uts-tests",
"keywords": [
"uts-tests"
],
"repository": "",
"engines": {
"HBuilderX": "^3.6.8"
},
"dcloudext": {
"type": "uts",
"sale": {
"regular": {
"price": "0.00"
},
"sourcecode": {
"price": "0.00"
}
},
"contact": {
"qq": ""
},
"declaration": {
"ads": "",
"data": "",
"permissions": ""
},
"npmurl": ""
},
"uni_modules": {
"dependencies": [],
"encrypt": [],
"platforms": {
"cloud": {
"tcb": "u",
"aliyun": "u"
},
"client": {
"Vue": {
"vue2": "u",
"vue3": "u"
},
"App": {
"app-android": "u",
"app-ios": "u"
},
"H5-mobile": {
"Safari": "u",
"Android Browser": "u",
"微信浏览器(Android)": "u",
"QQ浏览器(Android)": "u"
},
"H5-pc": {
"Chrome": "u",
"IE": "u",
"Edge": "u",
"Firefox": "u",
"Safari": "u"
},
"小程序": {
"微信": "u",
"阿里": "u",
"百度": "u",
"字节跳动": "u",
"QQ": "u",
"钉钉": "u",
"快手": "u",
"飞书": "u",
"京东": "u"
},
"快应用": {
"华为": "u",
"联盟": "u"
}
}
}
}
}
\ No newline at end of file
# uts-tests
### 开发文档
[UTS 语法](https://uniapp.dcloud.net.cn/tutorial/syntax-uts.html)
[UTS 原生插件](https://uniapp.dcloud.net.cn/plugin/uts-plugin.html)
[Hello UTS](https://gitcode.net/dcloud/hello-uts/-/tree/dev)
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testArray(): Result {
return describe("Array", () => {
test('length', () => {
const arr: string[] = ['shoes', 'shirts', 'socks', 'sweaters'];
expect(arr.length).toEqual(4);
expect(arr[0]).toEqual('shoes');
expect(arr[1]).toEqual('shirts');
// expect(arr[4]).toEqual(null);
const numbers: number[] = [1, 2, 3, 4, 5];
if (numbers.length > 3) {
numbers.length = 3;
}
expect(numbers.length).toEqual(3);
expect(numbers).toEqual([1, 2, 3]);
expect([].length).toEqual(0);
// 1. web: 最大长度 2^32-1
// 超出边界报错: RangeError: Invalid array length
// 2. kotlin: 最大长度 2^31-1
// 超出边界报错: Error: targetMethod error::java.lang.OutOfMemoryError: Failed to allocate a 420546432 byte allocation with 6291456 free bytes and 300MB until OOM, target footprint 295113520, growth limit 603979776
// 3. swift: 最大长度和内存有关
// 超出边界没有返回信息
})
test("concat", () => {
expect(['a', 'b', 'c'].concat(['d', 'e', 'f'])).toEqual(["a", "b", "c", "d", "e", "f"]);
expect([1, 2, 3].concat([4, 5, 6])).toEqual([1, 2, 3, 4, 5, 6]);
expect([''].concat([''])).toEqual(["", ""]);
const num1: number[] = [1, 2, 3];
const num2: number[] = [4, 5, 6];
const num3: number[] = [7, 8, 9];
const numbers = num1.concat(num2, num3);
expect(numbers).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
})
test("copyWithin", () => {
const arr: string[] = ['a', 'b', 'c', 'd', 'e'];
expect(arr.copyWithin(0, 3, 4)).toEqual(["d", "b", "c", "d", "e"]);
expect(arr.copyWithin(1, 3)).toEqual(["d", "d", "e", "d", "e"]);
const arr2: number[] = [1, 2, 3, 4, 5];
expect(arr2.copyWithin(-2)).toEqual([1, 2, 3, 1, 2]);
expect(arr2.copyWithin(-2, -3, -1)).toEqual([1, 2, 3, 3, 1]);
})
test("every", () => {
const isBelowThreshold = (currentValue:number):boolean=> currentValue < 40;
const array1: number[] = [1, 30, 39, 29, 10, 13];
const array2: number[] = [1, 30, 39, 29, 10, 13, 41];
expect(array1.every(isBelowThreshold)).toEqual(true);
expect(array2.every(isBelowThreshold)).toEqual(false);
const array3: number[] = [1, 2, 3];
array3.every((element:number, index:number, array:number[]):boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("fill", () => {
const array1: number[] = [1, 2, 3, 4];
expect(array1.fill(0, 2, 4)).toEqual([1, 2, 0, 0]);
expect(array1.fill(5, 1)).toEqual([1, 5, 5, 5]);
expect(array1.fill(6)).toEqual([6, 6, 6, 6]);
const array2: number[]= [1, 2, 3]
expect(array2.fill(4)).toEqual([4, 4, 4]);
const array3: number[]= [0, 0]
expect(array3.fill(1, null)).toEqual([1, 1]);
expect(array3.fill(1, 0, 1.5)).toEqual([1, 1]);
})
test("filter", () => {
const words: string[] = ['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present'];
const result = words.filter((word:string):boolean => word.length > 6);
expect(result).toEqual(["exuberant", "destruction", "present"]);
const array1: number[] = [-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13];
const isPrime = array1.filter((num:number):boolean => {
for (let i = 2; num > i; i++) {
// swift里,基础类型暂不支持!==,===对比
if (num % i == 0) {
return false;
}
}
return num > 1;
})
expect(isPrime).toEqual([2, 3, 5, 7, 11, 13]);
const array2: number[] = [1, 2, 3];
array2.filter((element:number, index:number, array:number[]):boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("find", () => {
const array1: number[] = [5, 12, 8, 130, 44];
const found1 = array1.find((element:number):boolean => element > 10);
expect(found1).toEqual(12);
const found2 = array1.find((element:number):boolean => element < 5);
expect(found2).toEqual(null);
const array2: number[] = [1, 2, 3];
array2.find((element:number, index:number, array:number[]):boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("findIndex", () => {
const array1: number[] = [5, 12, 8, 130, 44];
const isLargeNumber = (element:number):boolean => element > 13;
expect(array1.findIndex(isLargeNumber)).toEqual(3);
const array2: number[] = [10, 11, 12];
expect(array2.findIndex(isLargeNumber)).toEqual(-1);
const array3: number[] = [1, 2, 3];
array3.findIndex((element:number, index:number, array:number[]):boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("flat", () => {
const arr1: any[] = [0, 1, 2, [3, 4]];
expect(arr1.flat()).toEqual([0, 1, 2, 3, 4]);
const arr2: any[] = [0, 1, 2, [[[3, 4]]]];
expect(arr2.flat(2)).toEqual([0, 1, 2, [3, 4]]);
const arr3: any[] = [1, 2, [3, 4, [5, 6]]];
expect(arr3.flat(2)).toEqual([1, 2, 3, 4, 5, 6]);
})
test("forEach", () => {
const array1: string[] = ['a', 'b', 'c'];
array1.forEach((element:string, index:number) => {
expect(array1[index]).toEqual(element)
});
const items: string[] = ['item1', 'item2', 'item3'];
const copyItems: string[] = [];
items.forEach((item:string) => {
copyItems.push(item);
});
expect(copyItems).toEqual(items)
})
test("includes", () => {
const array1: number[] = [1, 2, 3];
expect(array1.includes(2)).toEqual(true);
const pets: string[] = ['cat', 'dog', 'bat'];
expect(pets.includes('cat')).toEqual(true);
expect(pets.includes('at')).toEqual(false);
const array2: string[] = ['a', 'b', 'c'];
expect(array2.includes('c', 3)).toEqual(false);
expect(array2.includes('c', 100)).toEqual(false);
})
test("indexOf", () => {
const beasts: string[] = ['ant', 'bison', 'camel', 'duck', 'bison'];
expect(beasts.indexOf('bison')).toEqual(1);
expect(beasts.indexOf('bison', 2)).toEqual(4);
expect(beasts.indexOf('giraffe')).toEqual(-1);
const indices: number[] = [];
const array: string[] = ['a', 'b', 'a', 'c', 'a', 'd'];
const element = 'a';
let idx = array.indexOf(element);
// swift里,基础类型暂不支持!==,===对比
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
expect(indices).toEqual([0, 2, 4]);
})
test("join", () => {
const elements: string[] = ['Fire', 'Air', 'Water'];
expect(elements.join()).toEqual("Fire,Air,Water");
expect(elements.join('')).toEqual("FireAirWater");
expect(elements.join('-')).toEqual("Fire-Air-Water");
})
test("lastIndexOf", () => {
const animals: string[] = ['Dodo', 'Tiger', 'Penguin', 'Dodo'];
expect(animals.lastIndexOf('Dodo')).toEqual(3);
expect(animals.lastIndexOf('Tiger')).toEqual(1);
const array: number[] = [2, 5, 9, 2];
let index = array.lastIndexOf(2);
expect(index).toEqual(3);
index = array.lastIndexOf(7);
expect(index).toEqual(-1);
index = array.lastIndexOf(2, 3);
expect(index).toEqual(3);
index = array.lastIndexOf(2, 2);
expect(index).toEqual(0);
})
test("map", () => {
const array1: number[] = [1, 4, 9, 16];
const map1 = array1.map((x:number):number => x * 2);
expect(map1).toEqual([2, 8, 18, 32]);
const numbers: number[] = [1, 4, 9];
const roots = numbers.map((num:number):number => num + 1);
expect(numbers).toEqual([1, 4, 9]);
expect(roots).toEqual([2, 5, 10]);
const array2: number[] = [1, 2, 3];
array2.map((element:number, index:number, array:number[]) => {
expect(array[index]).toEqual(element);
})
})
test("pop", () => {
const plants: string[] = ['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato'];
expect(plants.pop()).toEqual("tomato");
expect(plants).toEqual(["broccoli", "cauliflower", "cabbage", "kale"]);
plants.pop();
expect(plants).toEqual(["broccoli", "cauliflower", "cabbage"]);
})
test("push", () => {
const animals: string[] = ['pigs', 'goats', 'sheep'];
const count = animals.push('cows');
expect(count).toEqual(4);
expect(animals).toEqual(['pigs', 'goats', 'sheep', 'cows']);
animals.push('chickens', 'cats', 'dogs');
expect(animals).toEqual(["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]);
})
test("reduce", () => {
const array1: number[] = [1, 2, 3, 4];
const initialValue:number = 0;
const sumWithInitial = array1.reduce(
(previousValue:number, currentValue:number):number => previousValue + currentValue,
initialValue
);
expect(sumWithInitial).toEqual(10);
})
test("shift", () => {
const array1: number[] = [1, 2, 3];
const firstElement = array1.shift();
expect(firstElement).toEqual(1);
expect(array1).toEqual([2, 3]);
})
test("slice", () => {
const animals: string[] = ['ant', 'bison', 'camel', 'duck', 'elephant'];
expect(animals.slice(2)).toEqual(["camel", "duck", "elephant"]);
expect(animals.slice(2, 4)).toEqual(["camel", "duck"]);
expect(animals.slice(1, 5)).toEqual(["bison", "camel", "duck", "elephant"]);
expect(animals.slice(-2)).toEqual(["duck", "elephant"]);
expect(animals.slice(2, -1)).toEqual(["camel", "duck"]);
expect(animals.slice()).toEqual(["ant", "bison", "camel", "duck", "elephant"]);
})
test("some", () => {
const array: number[] = [1, 2, 3, 4, 5];
const even = (element:number):boolean=> element % 2 == 0;
expect(array.some(even)).toEqual(true);
const isBiggerThan10 = (element:number):boolean=> element > 10;
expect([2, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(false);
expect([12, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(true);
})
test("splice", () => {
const months: string[] = ['Jan', 'March', 'April', 'June'];
months.splice(1, 0, 'Feb');
expect(months).toEqual(["Jan", "Feb", "March", "April", "June"]);
months.splice(4, 1, 'May');
expect(months).toEqual(["Jan", "Feb", "March", "April", "May"]);
})
test('sort', () => {
const months = ['March', 'Jan', 'Feb', 'Dec'];
months.sort();
expect(months).toEqual(["Dec", "Feb", "Jan", "March"]);
const array1 = [1, 30, 4, 21, 100000];
array1.sort();
expect(array1).toEqual([1, 100000, 21, 30, 4]);
const array2 = [5, 1, 4, 2, 3];
array2.sort((a: number, b: number):number => a - b);
expect(array2).toEqual([1, 2, 3, 4, 5]);
// const array3 = [5, "banana", 4, "apple", 3, "cherry", 2, "date", 1];
// array3.sort();
// expect(array3).toEqual([1, 2, 3, 4, 5, "apple", "banana", "cherry", "date"]);
const array4 = [
{ name: "John", age: 24 },
{ name: "Sarah", age: 19 },
{ name: "Bob", age: 27 },
{ name: "Alice", age: 21 }
];
// 先强转类型,解决编译报错
array4.sort((a, b):number => (a['age'] as number) - (b['age'] as number));
expect(array4).toEqual([{ name: "Sarah", age: 19 }, { name: "Alice", age: 21 }, { name: "John", age: 24 }, { name: "Bob", age: 27 }]);
})
test("unshift", () => {
const array1: number[] = [1, 2, 3];
expect(array1.unshift(4, 5)).toEqual(5);
expect(array1).toEqual([4, 5, 1, 2, 3]);
})
test('reverse', () => {
// const array1: string[] = ['one', 'two', 'three'];
// const reversed1: string[] = array1.reverse();
// expect(reversed1).toEqual(["three", "two", "one"]);
// expect(array1).toEqual(["three", "·two", "one"]);
// const array2 = [1, 2, 3, 4, 5];
// const reversed2 = array2.reverse();
// expect(reversed2).toEqual([5, 4, 3, 2, 1]);
// expect(array2).toEqual([5, 4, 3, 2, 1]);
})
test("reduceRight", () => {
const array1: number[][] = [[0, 1], [2, 3], [4, 5]];
const result1 = array1.reduceRight((accumulator: number[], currentValue: number[]): number[] => accumulator.concat(currentValue));
expect(result1).toEqual([4, 5, 2, 3, 0, 1]);
const array2: number[] = [1, 2, 3, 4];
const result2 = array2.reduceRight((acc: number, cur: number, index: number, array: number[]): number => {
expect(array[index]).toEqual(cur);
return acc + cur;
});
expect(result2).toEqual(10);
const result3 = array2.reduceRight((acc: number, cur: number): number => acc + cur, 5);
expect(result3).toEqual(15);
})
test("flatMap", () => {
const arr: number[] = [1, 2, 3];
const result = arr.flatMap((x: number):number[] => [x, x * 2]);
expect(result).toEqual([1, 2, 2, 4, 3, 6]);
const arr1: number[] = [1, 2, 3, 4];
const result1 = arr1.flatMap((num: number, index: number, array: number[]): number[] => {
expect(array[index]).toEqual(num);
if (num % 2 == 0) {
return [num * 2];
}
return [];
});
expect(result1).toEqual([4, 8]);
})
test("entries", () => {
// const array1 = ['a', 'b', 'c'];
// const iterator1 = array1.entries();
// expect(iterator1.next().value).toEqual([0, "a"]);
// expect(iterator1.next().value).toEqual([1, "b"]);
// expect(iterator1.next().value).toEqual([2, "c"]);
// expect(iterator1.next().done).toEqual(true);
// const array2: any[] = [1, 2, 'hello', true, { name: 'john', age: 30 }, [4, 5]];
// let count = 0;
// for (const [index, element] of array2.entries()) {
// count++;
// expect(element).toEqual(array2[index]);
// }
// expect(count).toEqual(array2.length);
})
test("keys", () => {
// const array1 = ['a', 'b', 'c'];
// const iterator1 = array1.keys();
// expect(iterator1.next().value).toEqual(0);
// expect(iterator1.next().value).toEqual(1);
// expect(iterator1.next().value).toEqual(2);
// expect(iterator1.next().done).toEqual(true);
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testDate() : Result {
return describe("Date", () => {
test('now', () => {
const start = Date.now()
setTimeout(() => {
const millis = Date.now() - start
const secondsElapsed = Math.floor(millis / 1000)
expect(secondsElapsed).toEqual(2);
}, 2000)
})
test('getDate', () => {
const birthday = new Date('August 19, 1975 23:15:30');
const date1 = birthday.getDate();
expect(date1).toEqual(19);
// first millisecond
expect(new Date(2016, 6, 6).getDate()).toEqual(6);
// previous millisecond
expect(new Date(2016, 6, 6, 0, 0, 0, -1).getDate()).toEqual(5);
// final millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 999).getDate()).toEqual(6);
// subsequent millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 1000).getDate()).toEqual(7);
// first millisecond (month boundary)
expect(new Date(2016, 1, 29).getDate()).toEqual(29);
// previous millisecond (month boundary)
expect(new Date(2016, 1, 29, 0, 0, 0, -1).getDate()).toEqual(28);
// final millisecond (month boundary)
expect(new Date(2016, 1, 29, 23, 59, 59, 999).getDate()).toEqual(29);
// subsequent millisecond (month boundary)
expect(new Date(2016, 1, 29, 23, 59, 59, 1000).getDate()).toEqual(1);
})
test('getDay', () => {
const birthday = new Date('August 19, 1975 23:15:30');
const day1 = birthday.getDay();
expect(day1).toEqual(2);
// first millisecond
expect(new Date(2016, 6, 6).getDay()).toEqual(3);
// previous millisecond
expect(new Date(2016, 6, 6, 0, 0, 0, -1).getDay()).toEqual(2);
// final millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 999).getDay()).toEqual(3);
// subsequent millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 1000).getDay()).toEqual(4);
// first millisecond (week boundary)
expect(new Date(2016, 6, 9).getDay()).toEqual(6);
// previous millisecond (week boundary)
expect(new Date(2016, 6, 9, 0, 0, 0, -1).getDay()).toEqual(5);
// final millisecond (week boundary)
expect(new Date(2016, 6, 9, 23, 59, 59, 999).getDay()).toEqual(6);
// subsequent millisecond (week boundary)
expect(new Date(2016, 6, 9, 23, 59, 59, 1000).getDay()).toEqual(0);
})
test('getFullYear', () => {
const moonLanding = new Date('July 20, 69 00:20:18');
expect(moonLanding.getFullYear()).toEqual(1969);
// first millisecond
expect(new Date(2016, 0).getFullYear()).toEqual(2016);
// previous millisecond
expect(new Date(2016, 0, 1, 0, 0, 0, -1).getFullYear()).toEqual(2015);
// final millisecond
expect(new Date(2016, 11, 31, 23, 59, 59, 999).getFullYear()).toEqual(2016);
// subsequent millisecond
expect(new Date(2016, 11, 31, 23, 59, 59, 1000).getFullYear()).toEqual(2017);
})
test('getHours', () => {
const birthday = new Date('March 13, 08 04:20');
expect(birthday.getHours()).toEqual(4);
// first millisecond
expect(new Date(2016, 6, 6, 13).getHours()).toEqual(13);
// previous millisecond
expect(new Date(2016, 6, 6, 13, 0, 0, -1).getHours()).toEqual(12);
// final millisecond
expect(new Date(2016, 6, 6, 13, 59, 59, 999).getHours()).toEqual(13);
// subsequent millisecond
expect(new Date(2016, 6, 6, 13, 59, 59, 1000).getHours()).toEqual(14);
})
test('getMilliseconds', () => {
const moonLanding = new Date('July 20, 69 00:20:18');
moonLanding.setMilliseconds(123);
expect(moonLanding.getMilliseconds()).toEqual(123);
// first millisecond
expect(new Date(2016, 6, 6).getMilliseconds()).toEqual(0);
// previous millisecond
expect(new Date(2016, 6, 6, 0, 0, 0, -1).getMilliseconds()).toEqual(999);
// final millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 999).getMilliseconds()).toEqual(999);
// subsequent millisecond
expect(new Date(2016, 6, 6, 23, 59, 59, 1000).getMilliseconds()).toEqual(0);
})
test('getMinutes', () => {
const birthday = new Date('March 13, 08 04:20');
expect(birthday.getMinutes()).toEqual(20);
// first millisecond
expect(new Date(2016, 6, 6, 14, 6).getMinutes()).toEqual(6);
// previous millisecond
expect(new Date(2016, 6, 6, 14, 6, 0, -1).getMinutes()).toEqual(5);
// final millisecond
expect(new Date(2016, 6, 6, 14, 6, 59, 999).getMinutes()).toEqual(6);
// subsequent millisecond
expect(new Date(2016, 6, 6, 14, 6, 59, 1000).getMinutes()).toEqual(7);
})
test('getMonth', () => {
const moonLanding = new Date('July 20, 69 00:20:18');
expect(moonLanding.getMonth()).toEqual(6);
// first millisecond
expect(new Date(2016, 6).getMonth()).toEqual(6);
// previous millisecond
expect(new Date(2016, 6, 0, 0, 0, 0, -1).getMonth()).toEqual(5);
// final millisecond
expect(new Date(2016, 6, 31, 23, 59, 59, 999).getMonth()).toEqual(6);
// subsequent millisecond
expect(new Date(2016, 6, 31, 23, 59, 59, 1000).getMonth()).toEqual(7);
})
test('getSeconds', () => {
const moonLanding = new Date('July 20, 69 00:20:18');
expect(moonLanding.getSeconds()).toEqual(18);
// first millisecond
expect(new Date(2016, 6, 6, 14, 16, 30).getSeconds()).toEqual(30);
// previous millisecond
expect(new Date(2016, 6, 6, 14, 16, 30, -1).getSeconds()).toEqual(29);
// final millisecond
expect(new Date(2016, 6, 6, 14, 16, 30, 999).getSeconds()).toEqual(30);
// subsequent millisecond
expect(new Date(2016, 6, 6, 14, 16, 30, 1000).getSeconds()).toEqual(31);
})
test('getTime', () => {
const moonLanding = new Date('July 20, 69 20:17:40 GMT+00:00');
expect(moonLanding.getTime()).toEqual(-14182940000);
expect(new Date(0).getTime()).toEqual(0);
expect(new Date(1).getTime()).toEqual(1);
})
test('setDate', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setDate(24);
expect(event.getDate()).toEqual(24);
event.setDate(32);
expect(event.getDate()).toEqual(1);
// var date = new Date(2016, 6);
// let returnValue = date.setDate(6);
// let expected = new Date(2016, 6, 6).getTime();
// expect(returnValue).toEqual(expected);
})
test('setFullYear', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setFullYear(1969);
expect(event.getFullYear()).toEqual(1969);
})
test('setHours', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setHours(20);
expect(event.getHours()).toEqual(20);
})
test('setMilliseconds', () => {
const event = new Date('August 19, 1975 23:15:30');
expect(event.getMilliseconds()).toEqual(0);
event.setMilliseconds(456);
expect(event.getMilliseconds()).toEqual(456);
})
test('setMinutes', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setMinutes(45);
expect(event.getMinutes()).toEqual(45);
})
test('setMinutes', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setMonth(3);
expect(event.getMonth()).toEqual(3);
})
test('setSeconds', () => {
const event = new Date('August 19, 1975 23:15:30');
event.setSeconds(42);
expect(event.getSeconds()).toEqual(42);
})
test('setTime', () => {
const launchDate = new Date('July 1, 1999, 12:00:00');
const futureDate = new Date();
futureDate.setTime(launchDate.getTime());
expect(futureDate.getTime()).toEqual(launchDate.getTime());
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testError(): Result {
return describe("Error", () => {
test('message', () => {
try {
throw new Error('Whoops!')
} catch (e) {
expect(e.message).toEqual("Whoops!");
}
})
// test('name', () => {
// const e = new Error("Malformed input"); // e.name is 'Error'
// e.name = "ParseError";
// })
})
}
import { describe, test, expect, Result } from './tests.uts'
export function testJSON() : Result {
return describe("JSON", () => {
test('parse', () => {
const json = `{"result":true, "count":42}`;
const obj = JSON.parse(json)!;
expect(obj["count"]).toEqual(42);
expect(obj["result"]).toEqual(true);
const json1 = `{
"name": "John",
"age": 30,
"city": "New York"
}`;
const obj1 = JSON.parse(json1);
expect(obj1).toEqual({
name: 'John',
age: 30,
city: 'New York',
});
const json2 = '{"string":"Hello","number":42,"boolean":true,"nullValue":null,"array":[1,2,3],"object":{"nestedKey":"nestedValue"}}';
const obj2 = JSON.parse(json2)!;
expect(obj2).toEqual({
string: 'Hello',
number: 42,
boolean: true,
nullValue: null,
array: [1, 2, 3],
object: {
nestedKey: 'nestedValue',
},
});
expect(obj2['object']).toEqual({
nestedKey: 'nestedValue',
})
// const json3 = '["apple","banana","cherry"]';
// const obj3 = JSON.parse(json3)!;
// TODO JSON.parse 后数组的类型 无法强转
// expect(obj3).toEqual(['apple', 'banana', 'cherry']);
// const json4 = '[1, "two", true, null, {"key": "value"}, ["nested"]]';
// const obj4 = JSON.parse(json4)!;
// expect(obj4).toEqual([1, 'two', true, null, { key: 'value' }, ['nested']]);
// TODO 暂不支持多个参数
// const json5 = '{"p": 5}';
// const obj5 = JSON.parse(json5, function (k : string, v : number) : number {
// if (k === '') return v;
// return v * 2;
// })!;
// expect(obj5).toEqual({
// p: 10,
// });
expect(JSON.parse('{}')!).toEqual({});
// TODO 不支持boolean、string,js端需抹平
// expect(JSON.parse('true')!).toEqual(true);
// expect(JSON.parse('"foo"')!).toEqual("foo");
// expect(JSON.parse('null')!).toEqual(null);
})
test('stringify', () => {
const obj = { name: 'John', age: 30 };
const json = JSON.stringify(obj);
expect(json).toEqual('{"name":"John","age":30}');
const obj1 = { name: 'John', age: 30, address: { city: 'New York', country: 'USA' } };
const json1 = JSON.stringify(obj1);
expect(json1).toEqual('{"name":"John","age":30,"address":{"city":"New York","country":"USA"}}');
const obj2 = ['apple', 'banana', 'cherry'];
const json2 = JSON.stringify(obj2);
expect(json2).toEqual('["apple","banana","cherry"]');
// TODO 暂不支持多个参数
// const obj3 = { name: 'John', age: '30' };
// const replacer = (key : string, value : string) : string => (key === 'name' ? value.toUpperCase() : value);
// const json3 = JSON.stringify(obj3, replacer);
// expect(json3).toEqual('{"name":"JOHN","age":"30"}');
// const obj4 = { name: 'John', age: 30 };
// const json4 = JSON.stringify(obj4, null, 4);
// expect(json4).toEqual(`{
// "name": "John",
// "age": 30
// }`);
expect(JSON.stringify({ x: 5, y: 6 })).toEqual(`{"x":5,"y":6}`);
expect(JSON.stringify([3, 'false', false])).toEqual(`[3,"false",false]`);
expect(JSON.stringify({})).toEqual('{}');
expect(JSON.stringify(true)).toEqual('true');
expect(JSON.stringify('foo')).toEqual('foo');
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testMap(): Result {
return describe("Map", () => {
test('size', () => {
const map1: Map<string,string> = new Map();
map1.set('a', 'alpha');
map1.set('b', 'beta');
map1.set('g', 'gamma');
expect(map1.size).toEqual(3);
map1.clear()
expect(map1.size).toEqual(0);
})
test('clear', () => {
const map1 = new Map<string,string>();
map1.set('bar', 'baz');
map1.set("1", 'foo');
expect(map1.size).toEqual(2);
map1.clear();
expect(map1.size).toEqual(0);
})
test('delete', () => {
const map1 = new Map<string,string>();
map1.set('bar', 'foo');
expect(map1.delete('bar')).toEqual(true);
expect(map1.has('bar')).toEqual(false);
})
test('get', () => {
const map1 = new Map<string,string>();
map1.set('bar', 'foo');
expect(map1.get('bar')).toEqual("foo");
// js端输出undefined需要抹平差异
expect(map1.get('baz')).toEqual(null);
})
test('has', () => {
const map1 = new Map<string,string>();
map1.set('bar', 'foo');
expect(map1.has('bar')).toEqual(true);
expect(map1.has('baz')).toEqual(false);
})
test('set', () => {
const map1 = new Map<string,string>();
map1.set('bar', 'foo');
expect(map1.get('bar')).toEqual("foo");
const map2 = new Map<string,string>();
// ios平台不支持any作为key
map2.set('bar', 'foo');
expect(map2.get('bar')).toEqual('foo');
map2.set('bar', 'baz');
expect(map2.get('bar')).toEqual('baz');
const map3 = new Map<number,number>();
map3.set(111, 111);
map3.set(222, 222);
map3.set(333, 333);
expect(map3.get(111)).toEqual(111);
expect(map3.get(222)).toEqual(222);
expect(map3.get(333)).toEqual(333);
// ios不支持链式调用
// myMap.set(1, 'foobar').set(2, 'baz');
const map4 = new Map<UTSJSONObject,string>();
const key1 = {}, key2 = {};
map4.set(key1, '1')
map4.set(key2, '2')
expect(map4.get(key1)).toEqual('1');
expect(map4.get(key2)).toEqual('2');
const map5 = new Map<string,string>([['key1', 'value1'], ['key2', 'value2']]);
expect(map5.get('key1')).toEqual('value1');
expect(map5.get('key2')).toEqual('value2');
})
test('forEach', () => {
const map1 = new Map<string,string>();
map1.set('key1', 'value1');
map1.set('key2', 'value2');
map1.set('key3', 'value3');
map1.forEach((value:string, key:string, map: Map<string,string>) => {
expect(value).toEqual(map.get(key)!);
})
map1.forEach((value, key) => {
expect(value).toEqual(map1.get(key)!);
})
})
test("entries", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.entries();
// expect(mapIter.next().value).toEqual(["0", "foo"]);
// expect(mapIter.next().value).toEqual(["1", "bar"]);
// expect(mapIter.next().value).toEqual(["2", "baz"]);
// expect(mapIter.next().done).toEqual(true);
})
test("keys", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.keys();
// expect(mapIter.next().value).toEqual("0");
// expect(mapIter.next().value).toEqual("1");
// expect(mapIter.next().value).toEqual("2");
// expect(mapIter.next().done).toEqual(true);
})
test("values", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.values();
// expect(mapIter.next().value).toEqual("foo");
// expect(mapIter.next().value).toEqual("bar");
// expect(mapIter.next().value).toEqual("baz");
// expect(mapIter.next().done).toEqual(true);
})
})
}
export class Matchers<T> {
private actual: T
constructor(actual: T) {
this.actual = actual
}
toEqual(expected: T) {
if (JSON.stringify(expected) == JSON.stringify(this.actual)) {
return
}
// #ifndef APP-IOS
throw new Error(format(expected, this.actual))
// #endif
// #ifdef APP-IOS
NSException(name = NSExceptionName.internalInconsistencyException, reason = format(expected, this.actual)).raise()
// #endif
}
}
function format(expected: any | null, actual: any | null): string {
return `expected:<${expected}> but was:<${actual}>`
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testMath(): Result {
return describe("Math", () => {
test('E', () => {
function getNapier():number {
return Math.E
}
expect(getNapier()).toEqual(2.718281828459045);
})
test('LN10', () => {
function getNatLog10():number {
return Math.LN10;
}
expect(getNatLog10()).toEqual(2.302585092994046);
})
test('LN2', () => {
function getNatLog2():number {
return Math.LN2;
}
expect(getNatLog2()).toEqual(0.6931471805599453);
})
test('LOG10E', () => {
function getLog10e():number {
return Math.LOG10E;
}
expect(getLog10e()).toEqual(0.4342944819032518);
})
test('LOG2E', () => {
function getLog2e():number {
return Math.LOG2E;
}
expect(getLog2e()).toEqual(1.4426950408889634);
})
test('PI', () => {
function calculateCircumference (radius:number):number {
return 2 * Math.PI * radius;
}
expect(calculateCircumference(1)).toEqual(6.283185307179586);
})
test('SQRT1_2', () => {
function getRoot1_2():number {
return Math.SQRT1_2;
}
expect(getRoot1_2()).toEqual(0.7071067811865476);
})
test('SQRT2', () => {
function getRoot2():number {
return Math.SQRT2;
}
expect(getRoot2()).toEqual(1.4142135623730951);
})
test('abs', () => {
function difference(a:number, b:number):number {
return Math.abs(a - b);
}
expect(difference(3, 5)).toEqual(2);
expect(difference(5, 3)).toEqual(2);
expect(difference(1.23456, 7.89012)).toEqual(6.6555599999999995);
})
test('acos', () => {
expect(Math.acos(-1)).toEqual(3.141592653589793);
expect(Math.acos(0)).toEqual(1.5707963267948966);
// 解决精度问题
expect(Math.acos(1)).toEqual(0.0);
})
test('acosh', () => {
// 解决精度问题
expect(Math.acosh(1)).toEqual(0.0);
expect(Math.acosh(2)).toEqual(1.3169578969248166);
expect(Math.acosh(2.5)).toEqual(1.566799236972411);
})
test('asin', () => {
expect(Math.asin(-1)).toEqual(-1.5707963267948966);
// 解决精度问题
expect(Math.asin(0)).toEqual(0.0);
expect(Math.asin(0.5)).toEqual(0.5235987755982989);
expect(Math.asin(1)).toEqual(1.5707963267948966);
})
test('asinh', () => {
expect(Math.asinh(1)).toEqual(0.881373587019543);
expect(Math.asinh(0)).toEqual(0);
expect(Math.asinh(-1)).toEqual(-0.881373587019543);
expect(Math.asinh(2)).toEqual(1.4436354751788103);
})
test('atan', () => {
expect(Math.atan(1)).toEqual(0.7853981633974483);
// 解决精度问题
expect(Math.atan(0)).toEqual(0.0);
})
test('atan2', () => {
expect(Math.atan2(90, 15)).toEqual(1.4056476493802699);
expect(Math.atan2(15, 90)).toEqual(0.16514867741462683);
})
test('atanh', () => {
// 解决精度问题
expect(Math.atanh(0)).toEqual(0.0);
expect(Math.atanh(0.5)).toEqual(0.5493061443340548);
})
test('cbrt', () => {
// expect(Math.cbrt(-1)).toEqual(-1);
// expect(Math.cbrt(0)).toEqual(0);
// expect(Math.cbrt(1)).toEqual(1);
// expect(Math.cbrt(2)).toEqual(1.2599210498948732);
})
test('ceil', () => {
expect(Math.ceil(0.95)).toEqual(1);
expect(Math.ceil(4)).toEqual(4);
expect(Math.ceil(7.004)).toEqual(8);
expect(Math.ceil(-7.004)).toEqual(-7);
})
test('clz32', () => {
expect(Math.clz32(1)).toEqual(31);
expect(Math.clz32(1000)).toEqual(22);
expect(Math.clz32()).toEqual(32);
expect(Math.clz32(3.5)).toEqual(30);
})
test('cos', () => {
expect(Math.cos(0)).toEqual(1.0);
expect(Math.cos(1)).toEqual(0.5403023058681398);
})
test('cosh', () => {
// 解决精度问题
expect(Math.cosh(0)).toEqual(1.0);
expect(Math.cosh(1)).toEqual(1.5430806348152437);
expect(Math.cosh(-1)).toEqual(1.5430806348152437);
})
test('exp', () => {
expect(Math.exp(-1)).toEqual(0.36787944117144233);
// 解决精度问题
expect(Math.exp(0)).toEqual(1.0);
expect(Math.exp(1)).toEqual(2.718281828459045);
})
test('expm1', () => {
expect(Math.expm1(1)).toEqual(1.718281828459045);
expect(Math.expm1(-38)).toEqual(-1);
})
test('floor', () => {
expect(Math.floor(5.95)).toEqual(5);
expect(Math.floor(5.05)).toEqual(5);
expect(Math.floor(5)).toEqual(5);
expect(Math.floor(-5.05)).toEqual(-6);
})
test('fround', () => {
expect(Math.fround(1.5)).toEqual(1.5);
expect(Math.fround(1.337)).toEqual(1.3370000123977661);
})
// test('hypot', () => {
// expect(Math.hypot(3, 4)).toEqual(5);
// expect(Math.hypot(5, 12)).toEqual(13);
// expect(Math.hypot(3, 4, 5)).toEqual(7.0710678118654755);
// expect(Math.hypot(-5)).toEqual(5);
// })
// test('imul', () => {
// expect(Math.imul(3, 4)).toEqual(12);
// expect(Math.imul(-5, 12)).toEqual(-60);
// })
test('log', () => {
// 解决精度问题
expect(Math.log(1)).toEqual(0.0);
expect(Math.log(10)).toEqual(2.302585092994046);
})
test('log10', () => {
// 解决精度问题
expect(Math.log10(10)).toEqual(1.0);
expect(Math.log10(100)).toEqual(2.0);
expect(Math.log10(1)).toEqual(0.0);
})
test('log1p', () => {
// 解决精度问题
expect(Math.log1p(Math.E - 1)).toEqual(1.0);
expect(Math.log1p(0)).toEqual(0.0);
})
test('log2', () => {
// 解决精度问题
expect(Math.log2(2)).toEqual(1.0);
expect(Math.log2(1024)).toEqual(10.0);
expect(Math.log2(1)).toEqual(0.0);
})
test('max', () => {
expect(Math.max(1, 3, 2)).toEqual(3);
expect(Math.max(-1, -3, -2)).toEqual(-1);
})
test('min', () => {
expect(Math.min(2, 3, 1)).toEqual(1);
expect(Math.min(-2, -3, -1)).toEqual(-3);
})
test('pow', () => {
expect(Math.pow(7, 3)).toEqual(343);
expect(Math.pow(4, 0.5)).toEqual(2);
})
test('random', () => {
function getRandomInt(max:number):number {
return Math.floor(Math.random() * max);
}
expect(getRandomInt(getRandomInt(1))).toEqual(0);
})
test('sign', () => {
expect(Math.sign(3)).toEqual(1);
expect(Math.sign(-3)).toEqual(-1);
expect(Math.sign(0)).toEqual(0);
})
test('sin', () => {
// 解决精度问题
expect(Math.sin(0)).toEqual(0.0);
expect(Math.sin(1)).toEqual(0.8414709848078965);
})
test('sinh', () => {
// 解决精度问题
expect(Math.sinh(0)).toEqual(0.0);
expect(Math.sinh(1)).toEqual(1.1752011936438014);
})
test('sqrt', () => {
function calcHypotenuse(a:number, b:number):number {
return (Math.sqrt((a * a) + (b * b)));
}
// 解决精度问题
expect(calcHypotenuse(3, 4)).toEqual(5.0);
expect(calcHypotenuse(5, 12)).toEqual(13.0);
expect(calcHypotenuse(0, 0)).toEqual(0.0);
})
test('tan', () => {
// 解决精度问题
expect(Math.tan(0)).toEqual(0.0);
expect(Math.tan(1)).toEqual(1.5574077246549023);
})
test('tanh', () => {
expect(Math.tanh(-1)).toEqual(-0.7615941559557649);
// 解决精度问题
expect(Math.tanh(0)).toEqual(0.0);
expect(Math.tanh(1)).toEqual(0.7615941559557649);
})
test('trunc', () => {
expect(Math.trunc(13.37)).toEqual(13);
expect(Math.trunc(42.84)).toEqual(42);
expect(Math.trunc(0.123)).toEqual(0);
})
})
}
import { describe, test, expect, Result } from './tests.uts'
export function testNumber(): Result {
return describe("Number", () => {
test('toFixed', () => {
function financial(x: Number): String {
return x.toFixed(2);
}
expect(financial(123.456)).toEqual('123.46');
expect(financial(0.004)).toEqual("0.00");
expect(financial(0)).toEqual("0.00");
expect(financial(1)).toEqual("1.00");
})
})
}
import { describe, test, expect, Result } from './tests.uts'
export function testOperators(): Result {
return describe("Operators", () => {
test('+', () => {
expect('hello ' + 'everyone').toEqual("hello everyone");
function add(a: number, b: number): number {
return a + b
}
expect(add(0, 0)).toEqual(0);
expect(add(2, 2)).toEqual(4);
expect(add(-2, -3)).toEqual(-5);
expect(add(100, -100)).toEqual(0);
expect(add(100, -0.00001)).toEqual(99.99999);
expect(add(100, 0.00001)).toEqual(100.00001);
expect(add(123456789, 987654321)).toEqual(1111111110);
expect(add(1000000, 2000000)).toEqual(3000000);
expect(add(-1000000, -2000000)).toEqual(-3000000);
// kotlin 最大值 9223372036854775807,最小值 -9223372036854775808
// 超出边界报错 error: The value is out of range‌
// swift 最大值 9223372036854775807,最小值 -9223372036854775808
// 超出边界报错 error: integer literal 'xxx' overflows when stored into 'Int'
// web 最大值 1.7976931348623157e+308,最小值-1.7976931348623157e+308
// 超出边界返回 Infinity
// todo 统一处理
// const max = 9223372036854775807
// expect(add(max, max)).toEqual();
})
test('+=', () => {
let a: number = 2;
a += 3;
expect(a).toEqual(5);
let b: string = 'hello';
b += ' world';
expect(b).toEqual("hello world");
})
test('=', () => {
let x: number = 2;
const y: number = 3;
expect(x).toEqual(2);
x = y + 1;
expect(x).toEqual(4);
x = x * y
expect(x).toEqual(12);
})
test('&', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 3; // 00000000000000000000000000000011
expect(a & b).toEqual(1); // 00000000000000000000000000000001
})
test('&=', () => {
let a = 5; // 00000000000000000000000000000101
a &= 3; // 00000000000000000000000000000011
expect(a).toEqual(1); // 00000000000000000000000000000001
})
test('~', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = -3; // 11111111111111111111111111111101
expect(~a).toEqual(-6); // 11111111111111111111111111111010
expect(~b).toEqual(2); // 00000000000000000000000000000010
})
test('|', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 3; // 00000000000000000000000000000011
expect(a | b).toEqual(7); // 00000000000000000000000000000111
})
test('|=', () => {
let a = 5; // 00000000000000000000000000000101
a |= 3; // 00000000000000000000000000000011
expect(a).toEqual(7); // 00000000000000000000000000000111
})
test('^', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 3; // 00000000000000000000000000000011
expect(a ^ b).toEqual(6); // 00000000000000000000000000000110
})
test('^=', () => {
let a = 5; // 00000000000000000000000000000101
a ^= 3; // 00000000000000000000000000000011
expect(a).toEqual(6); // 00000000000000000000000000000110
})
test('--', () => {
let x = 3;
const y = x--;
expect(`x:${x}, y:${y}`).toEqual("x:2, y:3");
let a = 3;
const b = --a;
expect(`a:${a}, b:${b}`).toEqual("a:2, b:2");
})
test('/', () => {
function divide (a: number, b: number): number {
return a / b
}
expect(divide(10, 5)).toEqual(2);
expect(divide(-10, -5)).toEqual(2);
expect(divide(10, -5)).toEqual(-2);
expect(divide(-10, 5)).toEqual(-2);
expect(divide(0.1, 0.3)).toEqual(0.33333333333333337);
expect(divide(0.3, 0.1)).toEqual(2.9999999999999996);
expect(divide(1.5, 0.5)).toEqual(3);
expect(divide(3, 2)).toEqual(1.5);
// 暂不支持字面量
// expect(3 / 2).toEqual(1.5);
expect(divide(10, 3)).toEqual(3.3333333333333335);
expect(divide(3, 10)).toEqual(0.3);
expect(divide(1, 3)).toEqual(0.3333333333333333);
expect(divide(1000000, 2000000)).toEqual(0.5);
// kotlin java.lang.ArithmeticException: divide by zero
// swift 返回 inf
// web 返回 Infinity
// todo 统一处理
// expect(divide(1, 0)).toEqual();
})
test('/=', () => {
let a:Number = 3;
a /= 2;
expect(a).toEqual(1.5);
})
test('==', () => {
expect(1 == 1).toEqual(true);
expect('hello' == 'hello').toEqual(true);
})
test('>', () => {
expect(5 > 3).toEqual(true);
expect(3 > 3).toEqual(false);
expect('ab' > 'aa').toEqual(true);
})
test('++', () => {
let x = 3;
const y = x++;
expect(`x:${x}, y:${y}`).toEqual("x:4, y:3");
let a = 3;
const b = ++a;
expect(`a:${a}, b:${b}`).toEqual("a:4, b:4");
})
test('!=', () => {
expect(1 != 1).toEqual(false);
expect('hello' != 'hello').toEqual(false);
})
test('<<', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 2; // 00000000000000000000000000000010
expect(a << b).toEqual(20); // 00000000000000000000000000010100
})
test('<<=', () => {
let a = 5; // 00000000000000000000000000000101
a <<= 2; // 00000000000000000000000000010100
expect(a).toEqual(20); // 00000000000000000000000000010100
})
test('<', () => {
expect(5 < 3).toEqual(false);
expect(3 < 3).toEqual(false);
expect('aa' < 'ab').toEqual(true);
})
test('<=', () => {
expect(5 <= 3).toEqual(false);
expect(3 <= 3).toEqual(true);
expect('aa' <= 'ab').toEqual(true);
})
test('&&', () => {
const a: number = 3;
const b: number = -2;
expect(a > 0 && b > 0).toEqual(false);
})
// test('&&=', () => {
// let a:Int = 1;
// let b = 0;
// a &&= 2;
// expect(a).toEqual(2);
// b &&= 2;
// expect(b).toEqual(0);
// })
test('!', () => {
const a: number = 3;
const b: number = -2;
expect(!(a > 0 || b > 0)).toEqual(false);
})
// test('??=', () => {
// const a = { duration: 50 };
// a.duration ??= 10;
// expect(a.duration).toEqual(50);
// a.speed ??= 25;
// expect(a.duration).toEqual(25);
// })
test('||', () => {
const a: number = 3;
const b: number = -2;
expect(a > 0 || b > 0).toEqual(true);
})
// test('||=', () => {
// const a = { duration: 50, title: '' };
// a.duration ||= 10;
// expect(a.duration).toEqual(50);
// a.title ||= 'title is empty.';
// expect(a.title).toEqual("title is empty");
// })
test('*', () => {
function multiply(a: number, b: number): number {
return a * b
}
expect(multiply(10, 0)).toEqual(0);
expect(multiply(-10, 0)).toEqual(0);
expect(multiply(10, 1)).toEqual(10);
expect(multiply(1, 10)).toEqual(10);
expect(multiply(1, -10)).toEqual(-10);
expect(multiply(2, 3)).toEqual(6);
expect(multiply(0.2, 0.3)).toEqual(0.06);
expect(multiply(1.5, 6)).toEqual(9);
expect(multiply(1000, 0.001)).toEqual(1);
expect(multiply(1000, -0.001)).toEqual(-1);
expect(multiply(1000, -0.001)).toEqual(-1);
expect(multiply(9999, 9999)).toEqual(99980001);
expect(multiply(100000000, 10)).toEqual(1000000000);
})
test('*=', () => {
let a = 2;
a *= 3;
expect(a).toEqual(6);
})
// test('??', () => {
// const foo = null ?? 'default string';
// expect(foo).toEqual("default string");
// const baz = 0 ?? 42;
// expect(baz).toEqual(0);
// })
// test('?.', () => {
// const adventurer = {
// name: 'Alice',
// cat: {
// name: 'Dinah'
// }
// };
// const dogName = adventurer.cat?.name;
// console.log(dogName);
// expect(dogName).toEqual(undefined);
// })
test('%', () => {
expect(13 % 5).toEqual(3);
expect(-13 % 5).toEqual(-3);
expect(4 % 2).toEqual(0);
expect(-4 % 2).toEqual(-0);
})
test('%=', () => {
let a = 3;
a %= 2;
expect(a).toEqual(1);
})
test('>>', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 2; // 00000000000000000000000000000010
const c: number = -5; // 11111111111111111111111111111011
expect(a >> b).toEqual(1); // 00000000000000000000000000000001
expect(c >> b).toEqual(-2); // 11111111111111111111111111111110
})
test('>>=', () => {
let a = 5; // 00000000000000000000000000000101
a >>= 2; // 00000000000000000000000000000001
expect(a).toEqual(1);
let b = -5; // 11111111111111111111111111111011
b >>= 2; // 11111111111111111111111111111110
expect(b).toEqual(-2);
})
test('===', () => {
// swift里,基础类型暂不支持!==,===对比
expect(1 == 1).toEqual(true);
expect('hello' == 'hello').toEqual(true);
})
test('!==', () => {
// swift里,基础类型暂不支持!==,===对比
expect(1 != 1).toEqual(false);
expect('hello' != 'hello').toEqual(false);
})
test('-', () => {
function subtract(a: number, b: number): number {
return a - b
}
expect(subtract(3, 3)).toEqual(0);
expect(subtract(5, 3)).toEqual(2);
expect(subtract(-5, -3)).toEqual(-2);
expect(subtract(-5, 3)).toEqual(-8);
expect(subtract(5, -3)).toEqual(8);
expect(subtract(5, 0)).toEqual(5);
expect(subtract(1.5, 0.5)).toEqual(1);
expect(subtract(5.5, 2)).toEqual(3.5);
expect(subtract(5.5, 2)).toEqual(3.5);
expect(subtract(2.22, 1.11)).toEqual(1.11);
expect(subtract(10000000000, 1)).toEqual(9999999999);
expect(subtract(-10000000000, 1)).toEqual(-10000000001);
})
test('-=', () => {
let a = 2;
a -= 3
expect(a).toEqual(-1);
})
test('>>>', () => {
const a: number = 5; // 00000000000000000000000000000101
const b: number = 2; // 00000000000000000000000000000010
const c: number = -5; // 11111111111111111111111111111011
expect(a >>> b).toEqual(1); // 00000000000000000000000000000001
expect(c >>> b).toEqual(1073741822); // 00111111111111111111111111111110
})
test('>>>=', () => {
let a = 5; // 00000000000000000000000000000101
a >>>= 2; // 00000000000000000000000000000001
expect(a).toEqual(1);
let b = -5; // -00000000000000000000000000000101
b >>>= 2; // 00111111111111111111111111111110
expect(b).toEqual(1073741822);
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
import { UTSReactiveArray } from 'io.dcloud.uts.vue.reactivity'
export function testReactiveArray() : Result {
return describe("Array", () => {
test('length', () => {
const arr : string[] = new UTSReactiveArray(['shoes', 'shirts', 'socks', 'sweaters']);
expect(arr.length).toEqual(4);
expect(arr[0]).toEqual('shoes');
expect(arr[1]).toEqual('shirts');
// expect(arr[4]).toEqual(null);
const numbers: number[] = new UTSReactiveArray([1, 2, 3, 4, 5]);
if (numbers.length > 3) {
numbers.length = 3;
}
expect(numbers.length).toEqual(3);
expect(numbers).toEqual([1, 2, 3]);
expect(new UTSReactiveArray([] as number[]).length).toEqual(0);
// 1. web: 最大长度 2^32-1
// 超出边界报错: RangeError: Invalid array length
// 2. kotlin: 最大长度 2^31-1
// 超出边界报错: Error: targetMethod error::java.lang.OutOfMemoryError: Failed to allocate a 420546432 byte allocation with 6291456 free bytes and 300MB until OOM, target footprint 295113520, growth limit 603979776
// 3. swift: 最大长度和内存有关
// 超出边界没有返回信息
})
test("concat", () => {
expect(new UTSReactiveArray(['a', 'b', 'c']).concat(['d', 'e', 'f'])).toEqual(["a", "b", "c", "d", "e", "f"]);
expect(new UTSReactiveArray([1, 2, 3]).concat([4, 5, 6])).toEqual([1, 2, 3, 4, 5, 6]);
expect(new UTSReactiveArray(['']).concat([''])).toEqual(["", ""]);
const num1 : number[] = new UTSReactiveArray([1, 2, 3]);
const num2 : number[] = new UTSReactiveArray([4, 5, 6]);
const num3 : number[] = new UTSReactiveArray([7, 8, 9]);
const numbers = num1.concat(num2, num3);
expect(numbers).toEqual([1, 2, 3, 4, 5, 6, 7, 8, 9]);
})
test("copyWithin", () => {
const arr : string[] = new UTSReactiveArray(['a', 'b', 'c', 'd', 'e']);
expect(arr.copyWithin(0, 3, 4)).toEqual(["d", "b", "c", "d", "e"]);
expect(arr.copyWithin(1, 3)).toEqual(["d", "d", "e", "d", "e"]);
const arr2 : number[] = new UTSReactiveArray([1, 2, 3, 4, 5]);
expect(arr2.copyWithin(-2)).toEqual([1, 2, 3, 1, 2]);
expect(arr2.copyWithin(-2, -3, -1)).toEqual([1, 2, 3, 3, 1]);
})
test("every", () => {
const isBelowThreshold = (currentValue : number) : boolean => currentValue < 40;
const array1 : number[] = new UTSReactiveArray([1, 30, 39, 29, 10, 13]);
const array2 : number[] = new UTSReactiveArray([1, 30, 39, 29, 10, 13, 41]);
expect(array1.every(isBelowThreshold)).toEqual(true);
expect(array2.every(isBelowThreshold)).toEqual(false);
const array3 : number[] = new UTSReactiveArray([1, 2, 3]);
array3.every((element : number, index : number, array : number[]) : boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("fill", () => {
const array1 : number[] = new UTSReactiveArray([1, 2, 3, 4]);
expect(array1.fill(0, 2, 4)).toEqual([1, 2, 0, 0]);
expect(array1.fill(5, 1)).toEqual([1, 5, 5, 5]);
expect(array1.fill(6)).toEqual([6, 6, 6, 6]);
const array2 : number[] = new UTSReactiveArray([1, 2, 3])
expect(array2.fill(4)).toEqual([4, 4, 4]);
const array3 : number[] = new UTSReactiveArray([0, 0])
expect(array3.fill(1, null)).toEqual([1, 1]);
expect(array3.fill(1, 0, 1.5)).toEqual([1, 1]);
})
test("filter", () => {
const words : string[] = new UTSReactiveArray(['spray', 'limit', 'elite', 'exuberant', 'destruction', 'present']);
const result = words.filter((word : string) : boolean => word.length > 6);
expect(result).toEqual(["exuberant", "destruction", "present"]);
const array1 : number[] = new UTSReactiveArray([-3, -2, -1, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]);
const isPrime = array1.filter((num : number) : boolean => {
for (let i = 2; num > i; i++) {
// swift里,基础类型暂不支持!==,===对比
if (num % i == 0) {
return false;
}
}
return num > 1;
})
expect(isPrime).toEqual([2, 3, 5, 7, 11, 13]);
const array2 : number[] = new UTSReactiveArray([1, 2, 3]);
array2.filter((element : number, index : number, array : number[]) : boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("find", () => {
const array1 : number[] = new UTSReactiveArray([5, 12, 8, 130, 44]);
const found1 = array1.find((element : number) : boolean => element > 10);
expect(found1).toEqual(12);
const found2 = array1.find((element : number) : boolean => element < 5);
expect(found2).toEqual(null);
const array2 : number[] = new UTSReactiveArray([1, 2, 3]);
array2.find((element : number, index : number, array : number[]) : boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("findIndex", () => {
const array1 : number[] = new UTSReactiveArray([5, 12, 8, 130, 44]);
const isLargeNumber = (element : number) : boolean => element > 13;
expect(array1.findIndex(isLargeNumber)).toEqual(3);
const array2 : number[] = new UTSReactiveArray([10, 11, 12]);
expect(array2.findIndex(isLargeNumber)).toEqual(-1);
const array3 : number[] = new UTSReactiveArray([1, 2, 3]);
array3.findIndex((element : number, index : number, array : number[]) : boolean => {
expect(array[index]).toEqual(element);
return true;
})
})
test("flat", () => {
const arr1 : any[] = new UTSReactiveArray([0, 1, 2, [3, 4]]);
expect(arr1.flat()).toEqual([0, 1, 2, 3, 4]);
const arr2 : any[] = new UTSReactiveArray([0, 1, 2, [[[3, 4]]]]);
expect(arr2.flat(2)).toEqual([0, 1, 2, [3, 4]]);
const arr3 : any[] = new UTSReactiveArray([1, 2, [3, 4, [5, 6]]]);
expect(arr3.flat(2)).toEqual([1, 2, 3, 4, 5, 6]);
})
test("forEach", () => {
const array1 : string[] = new UTSReactiveArray(['a', 'b', 'c']);
array1.forEach((element : string, index : number) => {
expect(array1[index]).toEqual(element)
});
const items : string[] = new UTSReactiveArray(['item1', 'item2', 'item3']);
const copyItems : string[] = new UTSReactiveArray([]);
items.forEach((item : string) => {
copyItems.push(item);
});
expect(copyItems).toEqual(items)
})
test("includes", () => {
const array1 : number[] = new UTSReactiveArray([1, 2, 3]);
expect(array1.includes(2)).toEqual(true);
const pets : string[] = new UTSReactiveArray(['cat', 'dog', 'bat']);
expect(pets.includes('cat')).toEqual(true);
expect(pets.includes('at')).toEqual(false);
const array2 : string[] = new UTSReactiveArray(['a', 'b', 'c']);
expect(array2.includes('c', 3)).toEqual(false);
expect(array2.includes('c', 100)).toEqual(false);
})
test("indexOf", () => {
const beasts : string[] = new UTSReactiveArray(['ant', 'bison', 'camel', 'duck', 'bison']);
expect(beasts.indexOf('bison')).toEqual(1);
expect(beasts.indexOf('bison', 2)).toEqual(4);
expect(beasts.indexOf('giraffe')).toEqual(-1);
const indices : number[] = new UTSReactiveArray([]);
const array : string[] = new UTSReactiveArray(['a', 'b', 'a', 'c', 'a', 'd']);
const element = 'a';
let idx = array.indexOf(element);
// swift里,基础类型暂不支持!==,===对比
while (idx != -1) {
indices.push(idx);
idx = array.indexOf(element, idx + 1);
}
expect(indices).toEqual([0, 2, 4]);
})
test("join", () => {
const elements : string[] = new UTSReactiveArray(['Fire', 'Air', 'Water']);
expect(elements.join()).toEqual("Fire,Air,Water");
expect(elements.join('')).toEqual("FireAirWater");
expect(elements.join('-')).toEqual("Fire-Air-Water");
})
test("lastIndexOf", () => {
const animals : string[] = new UTSReactiveArray(['Dodo', 'Tiger', 'Penguin', 'Dodo']);
expect(animals.lastIndexOf('Dodo')).toEqual(3);
expect(animals.lastIndexOf('Tiger')).toEqual(1);
const array : number[] = new UTSReactiveArray([2, 5, 9, 2]);
let index = array.lastIndexOf(2);
expect(index).toEqual(3);
index = array.lastIndexOf(7);
expect(index).toEqual(-1);
index = array.lastIndexOf(2, 3);
expect(index).toEqual(3);
index = array.lastIndexOf(2, 2);
expect(index).toEqual(0);
})
test("map", () => {
const array1 : number[] = new UTSReactiveArray([1, 4, 9, 16]);
const map1 = array1.map((x : number) : number => x * 2);
expect(map1).toEqual([2, 8, 18, 32]);
const numbers : number[] = new UTSReactiveArray([1, 4, 9]);
const roots = numbers.map((num : number) : number => num + 1);
expect(numbers).toEqual([1, 4, 9]);
expect(roots).toEqual([2, 5, 10]);
const array2 : number[] = new UTSReactiveArray([1, 2, 3]);
array2.map((element : number, index : number, array : number[]) => {
expect(array[index]).toEqual(element);
})
})
test("pop", () => {
const plants : string[] = new UTSReactiveArray(['broccoli', 'cauliflower', 'cabbage', 'kale', 'tomato']);
expect(plants.pop()).toEqual("tomato");
expect(plants).toEqual(["broccoli", "cauliflower", "cabbage", "kale"]);
plants.pop();
expect(plants).toEqual(["broccoli", "cauliflower", "cabbage"]);
})
test("push", () => {
const animals : string[] = new UTSReactiveArray(['pigs', 'goats', 'sheep']);
const count = animals.push('cows');
expect(count).toEqual(4);
expect(animals).toEqual(['pigs', 'goats', 'sheep', 'cows']);
animals.push('chickens', 'cats', 'dogs');
expect(animals).toEqual(["pigs", "goats", "sheep", "cows", "chickens", "cats", "dogs"]);
})
test("reduce", () => {
const array1 : number[] = new UTSReactiveArray([1, 2, 3, 4]);
const initialValue : number = 0;
const sumWithInitial = array1.reduce(
(previousValue : number, currentValue : number) : number => previousValue + currentValue,
initialValue
);
expect(sumWithInitial).toEqual(10);
})
test("shift", () => {
const array1 : number[] = new UTSReactiveArray([1, 2, 3]);
const firstElement = array1.shift();
expect(firstElement).toEqual(1);
expect(array1).toEqual([2, 3]);
})
test("slice", () => {
const animals : string[] = new UTSReactiveArray(['ant', 'bison', 'camel', 'duck', 'elephant']);
expect(animals.slice(2)).toEqual(["camel", "duck", "elephant"]);
expect(animals.slice(2, 4)).toEqual(["camel", "duck"]);
expect(animals.slice(1, 5)).toEqual(["bison", "camel", "duck", "elephant"]);
expect(animals.slice(-2)).toEqual(["duck", "elephant"]);
expect(animals.slice(2, -1)).toEqual(["camel", "duck"]);
expect(animals.slice()).toEqual(["ant", "bison", "camel", "duck", "elephant"]);
})
test("some", () => {
const array : number[] = new UTSReactiveArray([1, 2, 3, 4, 5]);
const even = (element : number) : boolean => element % 2 == 0;
expect(array.some(even)).toEqual(true);
const isBiggerThan10 = (element : number) : boolean => element > 10;
expect([2, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(false);
expect([12, 5, 8, 1, 4].some(isBiggerThan10)).toEqual(true);
})
test("splice", () => {
const months : string[] = new UTSReactiveArray(['Jan', 'March', 'April', 'June']);
months.splice(1, 0, 'Feb');
expect(months).toEqual(["Jan", "Feb", "March", "April", "June"]);
months.splice(4, 1, 'May');
expect(months).toEqual(["Jan", "Feb", "March", "April", "May"]);
})
test('sort', () => {
const months : string[] = new UTSReactiveArray(['March', 'Jan', 'Feb', 'Dec']);
months.sort();
expect(months).toEqual(["Dec", "Feb", "Jan", "March"]);
const array1 : number[] = new UTSReactiveArray([1, 30, 4, 21, 100000]);
array1.sort();
expect(array1).toEqual([1, 100000, 21, 30, 4]);
const array2 : number[] = new UTSReactiveArray([5, 1, 4, 2, 3]);
array2.sort((a : number, b : number) : number => a - b);
expect(array2).toEqual([1, 2, 3, 4, 5]);
const array3 : any[] = new UTSReactiveArray([5, "banana", 4, "apple", 3, "cherry", 2, "date", 1]);
array3.sort();
expect(array3).toEqual([1, 2, 3, 4, 5, "apple", "banana", "cherry", "date"]);
const array4 : UTSJSONObject[] = new UTSReactiveArray([
{ name: "John", age: 24 },
{ name: "Sarah", age: 19 },
{ name: "Bob", age: 27 },
{ name: "Alice", age: 21 }
]);
// 先强转类型,解决编译报错
array4.sort((a, b) : number => (a['age'] as number) - (b['age'] as number));
expect(array4).toEqual([{ name: "Sarah", age: 19 }, { name: "Alice", age: 21 }, { name: "John", age: 24 }, { name: "Bob", age: 27 }]);
})
test("unshift", () => {
const array1 : number[] = new UTSReactiveArray([1, 2, 3]);
expect(array1.unshift(4, 5)).toEqual(5);
expect(array1).toEqual([4, 5, 1, 2, 3]);
})
test('reverse', () => {
// const array1: string[] = ['one', 'two', 'three'];
// const reversed1: string[] = array1.reverse();
// expect(reversed1).toEqual(["three", "two", "one"]);
// expect(array1).toEqual(["three", "·two", "one"]);
// const array2 = [1, 2, 3, 4, 5];
// const reversed2 = array2.reverse();
// expect(reversed2).toEqual([5, 4, 3, 2, 1]);
// expect(array2).toEqual([5, 4, 3, 2, 1]);
})
test("reduceRight", () => {
const array1 : number[][] = new UTSReactiveArray([[0, 1], [2, 3], [4, 5]]);
const result1 = array1.reduceRight((accumulator : number[], currentValue : number[]) : number[] => accumulator.concat(currentValue));
expect(result1).toEqual([4, 5, 2, 3, 0, 1]);
const array2 : number[] = new UTSReactiveArray([1, 2, 3, 4]);
const result2 = array2.reduceRight((acc : number, cur : number, index : number, array : number[]) : number => {
expect(array[index]).toEqual(cur);
return acc + cur;
});
expect(result2).toEqual(10);
const result3 = array2.reduceRight((acc : number, cur : number) : number => acc + cur, 5);
expect(result3).toEqual(15);
})
test("flatMap", () => {
const arr : number[] = new UTSReactiveArray([1, 2, 3]);
const result = arr.flatMap((x : number) : number[] => [x, x * 2]);
expect(result).toEqual([1, 2, 2, 4, 3, 6]);
const arr1 : number[] = new UTSReactiveArray([1, 2, 3, 4]);
const result1 = arr1.flatMap((num : number, index : number, array : number[]) : number[] => {
expect(array[index]).toEqual(num);
if (num % 2 == 0) {
return [num * 2];
}
return [];
});
expect(result1).toEqual([4, 8]);
})
test("entries", () => {
// const array1 = ['a', 'b', 'c'];
// const iterator1 = array1.entries();
// expect(iterator1.next().value).toEqual([0, "a"]);
// expect(iterator1.next().value).toEqual([1, "b"]);
// expect(iterator1.next().value).toEqual([2, "c"]);
// expect(iterator1.next().done).toEqual(true);
// const array2: any[] = [1, 2, 'hello', true, { name: 'john', age: 30 }, [4, 5]];
// let count = 0;
// for (const [index, element] of array2.entries()) {
// count++;
// expect(element).toEqual(array2[index]);
// }
// expect(count).toEqual(array2.length);
})
test("keys", () => {
// const array1 = ['a', 'b', 'c'];
// const iterator1 = array1.keys();
// expect(iterator1.next().value).toEqual(0);
// expect(iterator1.next().value).toEqual(1);
// expect(iterator1.next().value).toEqual(2);
// expect(iterator1.next().done).toEqual(true);
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
import { UTSReactiveMap } from 'io.dcloud.uts.vue.reactivity'
export function testReactiveMap() : Result {
return describe("Map", () => {
test('size', () => {
const map1 : Map<string, string> = new UTSReactiveMap(new Map());
map1.set('a', 'alpha');
map1.set('b', 'beta');
map1.set('g', 'gamma');
expect(map1.size).toEqual(3);
map1.clear()
expect(map1.size).toEqual(0);
})
test('clear', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('bar', 'baz');
map1.set("1", 'foo');
expect(map1.size).toEqual(2);
map1.clear();
expect(map1.size).toEqual(0);
})
test('delete', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('bar', 'foo');
expect(map1.delete('bar')).toEqual(true);
expect(map1.has('bar')).toEqual(false);
})
test('get', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('bar', 'foo');
expect(map1.get('bar')).toEqual("foo");
// js端输出undefined需要抹平差异
expect(map1.get('baz')).toEqual(null);
})
test('has', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('bar', 'foo');
expect(map1.has('bar')).toEqual(true);
expect(map1.has('baz')).toEqual(false);
})
test('set', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('bar', 'foo');
expect(map1.get('bar')).toEqual("foo");
const map2 = new UTSReactiveMap(new Map<string, string>());
// ios平台不支持any作为key
map2.set('bar', 'foo');
expect(map2.get('bar')).toEqual('foo');
map2.set('bar', 'baz');
expect(map2.get('bar')).toEqual('baz');
const map3 = new UTSReactiveMap(new Map<number, number>());
map3.set(111, 111);
map3.set(222, 222);
map3.set(333, 333);
expect(map3.get(111)).toEqual(111);
expect(map3.get(222)).toEqual(222);
expect(map3.get(333)).toEqual(333);
// ios不支持链式调用
// myMap.set(1, 'foobar').set(2, 'baz');
const map4 = new UTSReactiveMap(new Map<UTSJSONObject, string>());
const key1 = {}, key2 = {};
map4.set(key1, '1')
map4.set(key2, '2')
expect(map4.get(key1)).toEqual('1');
expect(map4.get(key2)).toEqual('2');
const map5 = new UTSReactiveMap(new Map<string, string>([['key1', 'value1'], ['key2', 'value2']]));
expect(map5.get('key1')).toEqual('value1');
expect(map5.get('key2')).toEqual('value2');
})
test('forEach', () => {
const map1 = new UTSReactiveMap(new Map<string, string>());
map1.set('key1', 'value1');
map1.set('key2', 'value2');
map1.set('key3', 'value3');
map1.forEach((value : string, key : string, map : Map<string, string>) => {
expect(value).toEqual(map.get(key)!);
})
map1.forEach((value, key) => {
expect(value).toEqual(map1.get(key)!);
})
})
test("entries", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.entries();
// expect(mapIter.next().value).toEqual(["0", "foo"]);
// expect(mapIter.next().value).toEqual(["1", "bar"]);
// expect(mapIter.next().value).toEqual(["2", "baz"]);
// expect(mapIter.next().done).toEqual(true);
})
test("keys", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.keys();
// expect(mapIter.next().value).toEqual("0");
// expect(mapIter.next().value).toEqual("1");
// expect(mapIter.next().value).toEqual("2");
// expect(mapIter.next().done).toEqual(true);
})
test("values", () => {
// const myMap = new Map<string, string>();
// myMap.set("0", "foo");
// myMap.set("1", "bar");
// myMap.set("2", "baz");
// const mapIter = myMap.values();
// expect(mapIter.next().value).toEqual("foo");
// expect(mapIter.next().value).toEqual("bar");
// expect(mapIter.next().value).toEqual("baz");
// expect(mapIter.next().done).toEqual(true);
})
})
}
\ No newline at end of file
import { describe, test, expect, Result } from './tests.uts'
export function testRegExp(): Result {
return describe("RegExp", () => {
test("dotAll", () => {
const regex1 = new RegExp('foo', 's');
expect(regex1.dotAll).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.dotAll).toEqual(false);
})
test("flags", () => {
const regex1 = new RegExp('foo', 'ig');
expect(regex1.flags).toEqual("gi");
const regex2 = new RegExp('bar', 'myu');
expect(regex2.flags).toEqual("muy");
const regex3 = new RegExp('bar');
expect(regex3.flags).toEqual("");
})
test("global", () => {
const regex1 = new RegExp('foo', 'g');
expect(regex1.global).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.global).toEqual(false);
})
test("hasIndices", () => {
const regex1 = new RegExp('foo', 'd');
expect(regex1.hasIndices).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.hasIndices).toEqual(false);
})
test("ignoreCase", () => {
const regex1 = new RegExp('foo', 'i');
expect(regex1.ignoreCase).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.ignoreCase).toEqual(false);
})
test("lastIndex", () => {
const regex = /ab/g;
const str = 'ab ab ab';
const result1 = regex.exec(str)!;
expect(result1.index).toEqual(0);
expect(regex.lastIndex).toEqual(2);
const result2 = regex.exec(str)!;
expect(result2.index).toEqual(3);
expect(regex.lastIndex).toEqual(5);
const result3 = regex.exec(str)!;
expect(result3.index).toEqual(6);
expect(regex.lastIndex).toEqual(8);
})
test("multiline", () => {
const regex1 = new RegExp('foo', 'm');
expect(regex1.multiline).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.multiline).toEqual(false);
})
test("source", () => {
const regex1 = new RegExp('foo', 'ig');
expect(regex1.source).toEqual("foo");
const regex2 = new RegExp('bar');
expect(regex2.source).toEqual("bar");
const regex3 = /\w+/gi;
expect(regex3.source).toEqual("\\w+");
const regex4 = new RegExp('\\d+', 'ig');;
expect(regex4.source).toEqual("\\d+");
})
test("sticky", () => {
const str1 = 'table football';
const regex1 = new RegExp('foo', 'y');
regex1.lastIndex = 6;
expect(regex1.sticky).toEqual(true);
expect(regex1.test(str1)).toEqual(true);
expect(regex1.test(str1)).toEqual(false);
})
test("unicode", () => {
const regex1 = new RegExp('foo', 'u');
expect(regex1.unicode).toEqual(true);
const regex2 = new RegExp('bar');
expect(regex2.unicode).toEqual(false);
})
test('test', () => {
const str = 'table football';
const regex = new RegExp('foo*');
const globalRegex = new RegExp('foo*', 'g');
expect(regex.test(str)).toEqual(true);
expect(globalRegex.lastIndex).toEqual(0);
expect(globalRegex.test(str)).toEqual(true);
expect(globalRegex.lastIndex).toEqual(9);
expect(globalRegex.test(str)).toEqual(false);
const re = new RegExp('hello', 'g');
const str1 = 'hello world';
const str2 = 'hello there';
expect(re.test(str1)).toEqual(true);
expect(re.lastIndex).toEqual(5);
expect(re.test(str2)).toEqual(false);
expect(re.lastIndex).toEqual(0);
const re1 = new RegExp('(\\d{3})-(\\d{2})-(\\d{4})');
expect(re1.test('123-45-6789')).toEqual(true);
expect(re1.test('123-45-678')).toEqual(false);
const re2 = /^(http|https):\/\/[\w\-]+(\.[\w\-]+)*(:\d+)?(\/[\w\-./?%&=]*)?$/;
expect(re2.test('https://www.example.com')).toEqual(true);
expect(re2.test('http://127.0.0.1:8080')).toEqual(true);
expect(re2.test('www.example.com')).toEqual(false);
expect(re2.test('https:/www.example.com')).toEqual(false);
expect(re2.test('https:/www.example.com@foo')).toEqual(false);
expect(re2.test('123')).toEqual(false);
const re3 = /^1[3-9]\d{9}$/;
expect(re3.test('13912345678')).toEqual(true);
expect(re3.test('15812345678')).toEqual(true);
expect(re3.test('12912345678')).toEqual(false);
expect(re3.test('1391234')).toEqual(false);
expect(re3.test('1581234567a')).toEqual(false);
const re4 = /[\u4E00-\u9FA5]/;
expect(re4.test('测试')).toEqual(true);
expect(re4.test('123')).toEqual(false);
expect(re4.test('abc')).toEqual(false);
const re5 = /^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;
expect(re5.test('#b8b8b8')).toEqual(true);
expect(re5.test('#b8b')).toEqual(true);
expect(re5.test('#b8b8b81')).toEqual(false);
expect(re5.test('#b8b8b')).toEqual(false);
expect(re5.test('b8b8b')).toEqual(false);
const re6 = new RegExp('hello', 'i');
expect(re6.test('Hello')).toEqual(true);
const re7 = new RegExp('^Hello', 'm');
expect(re7.test('Hello\nWorld')).toEqual(true);
// const re8 = new RegExp('\\u{1F602}', 'u');
// expect(re8.test('😂')).toEqual(true);
// expect(re8.test('😊')).toEqual(false);
const re9 = new RegExp('a\\d', 'y');
expect(re9.test('a1a2a3')).toEqual(true);
expect(re9.test('a1a2a3')).toEqual(true);
expect(re9.test('a1a2a3')).toEqual(true);
expect(re9.test('a1a2a3')).toEqual(false);
const re10 = new RegExp('^foo.bar$', 's');
expect(re10.test('foo\nbar')).toEqual(true);
const re11 = /(?=a)?b/;
expect(re11.test("b")).toEqual(true);
const isValidIdentifierName = (str: string): boolean => {
const reg =
/^(?!(?:break|case|catch)$)[$_\p{ID_Start}][$\u200c\u200d\p{ID_Continue}]*$/u;
return reg.test(str);
}
expect(isValidIdentifierName("break")).toEqual(false);
expect(isValidIdentifierName("foo")).toEqual(true);
expect(isValidIdentifierName("cases")).toEqual(true);
const isASCIIIDPart = (char: string): boolean => {
return /^(?=\p{ASCII}$)\p{ID_Start}$/u.test(char);
}
expect(isASCIIIDPart("a")).toEqual(true);
expect(isASCIIIDPart("α")).toEqual(false);
expect(isASCIIIDPart(":")).toEqual(false);
})
test('exec', () => {
const pattern = new RegExp('hello');
const result = pattern.exec('hi there');
expect(result).toEqual(null);
const pattern1 = new RegExp('hello');
const result1 = pattern1.exec('hello world')!;
expect(result1[0]).toEqual('hello');
expect(result1.index).toEqual(0);
expect(result1.input).toEqual("hello world");
const pattern2 = /quick\s(?<color>brown).+?(jumps)/igd;
const result2 = pattern2.exec('The Quick Brown Fox Jumps Over The Lazy Dog')!;
expect(result2[0]).toEqual("Quick Brown Fox Jumps");
expect(result2[1]).toEqual("Brown");
expect(result2[2]).toEqual("Jumps");
expect(result2.index).toEqual(4);
expect(result2.input).toEqual("The Quick Brown Fox Jumps Over The Lazy Dog");
// expect(result2.groups).toEqual({color: "Brown"});
const pattern3 = /(\d{4})-(\d{2})-(\d{2})/g;
const result3 = pattern3.exec("2023-02-01")!;
expect(result3[0]).toEqual("2023-02-01");
expect(result3[1]).toEqual("2023");
expect(result3[2]).toEqual("02");
expect(result3[3]).toEqual("01");
expect(result3.index).toEqual(0);
expect(result3.input).toEqual("2023-02-01");
const pattern4 = /(?=(a+))a*b\1/;
const result4 = pattern4.exec("baabac")!;
expect(result4[0]).toEqual("aba");
expect(result4[1]).toEqual("a");
expect(result4.index).toEqual(2);
expect(result4.input).toEqual("baabac");
const pattern5 = /(.*?)a(?!(a+)b\1c)\1(.*)/;
const result5 = pattern5.exec("baaabaac")!;
expect(result5[0]).toEqual("baaabaac");
expect(result5[1]).toEqual("baa");
expect(result5[3]).toEqual("c");
expect(result5.index).toEqual(0);
const pattern6 = /^.*?(?=[,.])/;
const result6 = pattern6.exec("Hello, world!")!;
expect(result6[0]).toEqual("Hello");
const pattern7 = /\d{4}-(?=\d{2}-\d{2})\d{2}-\d{2}/;
const result7 = pattern7.exec('2023/05-26');
expect(result7).toEqual(null);
const pattern8 = /https:\/\/(?!\w+\.(com|net))\w+\.\w+/;
const result8 = pattern8.exec('https://example.org')!;
expect(result8[0]).toEqual('https://example.org');
const pattern9 = /(?<=@)\w+/;
const result9 = pattern9.exec('Email: john@example.com')!;
expect(result9[0]).toEqual('example');
const pattern10 = /(?<!@)\w+/;
const result10 = pattern10.exec('Username: john')!;
expect(result10[0]).toEqual('Username');
})
})
}
import { describe, test, expect, Result } from './tests.uts'
export function testSet(): Result {
return describe("Set", () => {
test('size', () => {
const set1 = new Set<Any>();
const object1 = {};
set1.add(42);
set1.add('forty two');
set1.add('forty two');
set1.add(object1);
expect(set1.size).toEqual(3);
})
test('add', () => {
const set1 = new Set<number>();
set1.add(42);
set1.add(42);
set1.add(13);
set1.forEach((item)=>{
expect(set1.has(item)).toEqual(true);
})
})
test('clear', () => {
const set1 = new Set<any>();
set1.add(1);
set1.add('foo');
expect(set1.size).toEqual(2);
set1.clear();
expect(set1.size).toEqual(0);
})
test('delete', () => {
const set1 = new Set<any>();
set1.add(10);
set1.add(20);
set1.delete(10);
expect(set1.size).toEqual(1);
})
test('has', () => {
const set1 = new Set<number>([1, 2, 3, 4, 5]);
expect(set1.has(1)).toEqual(true);
expect(set1.has(5)).toEqual(true);
expect(set1.has(6)).toEqual(false);
})
test('forEach', () => {
const set1 = new Set<any>(['foo', 'bar'])
const logSetElements = (value:any) => {
expect(set1.has(value)).toEqual(true);
}
set1.forEach(logSetElements);
})
test("entries", () => {
// const mySet = new Set<string>();
// mySet.add("foo");
// mySet.add("bar");
// mySet.add("baz");
// const setIter = mySet.entries();
// expect(setIter.next().value).toEqual(["foo", "foo"]);
// expect(setIter.next().value).toEqual(["bar", "bar"]);
// expect(setIter.next().value).toEqual(["baz", "baz"]);
// expect(setIter.next().done).toEqual(true);
})
test("keys", () => {
// const mySet = new Set<string>();
// mySet.add("foo");
// mySet.add("bar");
// mySet.add("baz");
// const setIter = mySet.keys();
// expect(setIter.next().value).toEqual("foo");
// expect(setIter.next().value).toEqual("bar");
// expect(setIter.next().value).toEqual("baz");
// expect(setIter.next().done).toEqual(true);
})
test("values", () => {
// const mySet = new Set<string>();
// mySet.add("foo");
// mySet.add("bar");
// mySet.add("baz");
// const setIter = mySet.values();
// expect(setIter.next().value).toEqual("foo");
// expect(setIter.next().value).toEqual("bar");
// expect(setIter.next().value).toEqual("baz");
// expect(setIter.next().done).toEqual(true);
})
})
}
import { describe, test, expect, Result } from './tests.uts'
export function testString(): Result {
return describe("String", () => {
test('length', () => {
const x = "Mozilla";
expect(x.length).toEqual(7);
// expect(x[0]).toEqual('M');
const empty = "";
expect(empty.length).toEqual(0);
const adlam = "𞤲𞥋𞤣𞤫";
expect(adlam.length).toEqual(8);
const formula = "∀𝑥∈ℝ,𝑥²≥0";
expect(formula.length).toEqual(11);
// 1. web: 最大长度和js引擎有关,在v8中为 2^29 - 24
// 超出边界报错: RangeError: Invalid string length
// 2. kotlin: 最大长度 2^31-1
// 超出边界报错: Error: targetMethod error::java.lang.OutOfMemoryError: char[] of length
// 3. swift: 最大长度和内存有关
// 超出边界没有返回信息
// const length = Math.pow(2, 29) - 24
// const str = 'x'.repeat(length);
// expect(str.length).toEqual(11);
})
test('at', () => {
const sentence = 'The quick brown fox jumps over the lazy dog.';
let index = 5;
expect(sentence.at(index)).toEqual("u");
index = -4;
expect(sentence.at(index)).toEqual("d");
expect(sentence.at(999)).toEqual(null);
let invoiceRef = 'myinvoice01';
expect(invoiceRef.at(-1)).toEqual("1");
invoiceRef = 'myinvoice02';
expect(invoiceRef.at(-1)).toEqual("2");
expect(invoiceRef.at(-999)).toEqual(null);
const empty = "";
expect(empty.at(0)).toEqual(null);
})
test('charAt', () => {
const anyString = "Brave new world";
expect(anyString.charAt(0)).toEqual("B");
expect(anyString.charAt(1)).toEqual("r");
expect(anyString.charAt(2)).toEqual("a");
expect(anyString.charAt(3)).toEqual("v");
expect(anyString.charAt(4)).toEqual("e");
expect(anyString.charAt(999)).toEqual("");
expect(anyString.charAt(-1)).toEqual("");
expect(anyString.charAt(-2)).toEqual("");
expect(anyString.charAt(-999)).toEqual("");
const empty = "";
expect(empty.charAt(0)).toEqual("");
})
test('charCodeAt', () => {
const sentence = 'The quick brown fox jumps over the lazy dog.';
const index = 4;
expect(sentence.charCodeAt(index)).toEqual(113);
expect("ABC".charCodeAt(0)).toEqual(65);
expect("ABC".charCodeAt(1)).toEqual(66);
expect("ABC".charCodeAt(2)).toEqual(67);
expect("ABC".charCodeAt(3)).toEqual(null);
const empty = "";
expect(empty.charCodeAt(0)).toEqual(null);
})
test('concat', () => {
let hello = 'Hello, '
expect(hello.concat('Kevin', '. Have a nice day.')).toEqual("Hello, Kevin. Have a nice day.");
expect("".concat('abc')).toEqual("abc");
})
test('endsWith', () => {
const str1 = 'Cats are the best!';
expect(str1.endsWith('best!')).toEqual(true);
expect(str1.endsWith('best', 17)).toEqual(true);
const str2 = 'Is this a question?';
expect(str2.endsWith('question')).toEqual(false);
expect("".includes("test")).toEqual(false);
})
test('includes', () => {
const sentence = 'The quick brown fox jumps over the lazy dog.';
const word = 'fox';
expect(sentence.includes(word)).toEqual(true);
expect("Blue Whale".includes("blue")).toEqual(false);
expect("Blue Whale".toLowerCase().includes("blue")).toEqual(true);
expect("".includes("test")).toEqual(false);
})
test('indexOf', () => {
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const searchTerm = 'dog';
const indexOfFirst = paragraph.indexOf(searchTerm);
expect(indexOfFirst).toEqual(40);
expect(paragraph.indexOf(searchTerm, (indexOfFirst + 1))).toEqual(52);
expect('Blue Whale'.indexOf('Blue')).toEqual(0);
expect('Blue Whale'.indexOf('Blute')).toEqual(-1);
expect('Blue Whale'.indexOf('Whale', 0)).toEqual(5);
expect('Blue Whale'.indexOf('Whale', 5)).toEqual(5);
expect('Blue Whale'.indexOf('Whale', 7)).toEqual(-1);
expect("".indexOf("test")).toEqual(-1);
})
test('match', () => {
// const str = 'The quick brown fox jumps over the lazy dog. It barked.';
// const result = str.match(new RegExp('[A-Z]', 'g'));
// expect(result).toEqual(["T", "I"]);
// const str1 = 'For more information, see Chapter 3.4.5.1';
// const result1 = str1.match(/see (chapter \d+(\.\d)*)/i);
// expect(result1[0]).toEqual("see Chapter 3.4.5.1");
// expect(result1[1]).toEqual("Chapter 3.4.5.1");
// expect(result1[2]).toEqual(".1");
// expect(result1.index).toEqual(22);
// expect(result1.input).toEqual(str1);
// const str2 = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz';
// const result2 = str2.match(/[A-E]/gi);
// expect(result2).toEqual(['A', 'B', 'C', 'D', 'E', 'a', 'b', 'c', 'd', 'e']);
// const str3 = 'Nothing will come of nothing.';
// const result3 = str3.match();
// expect(result3).toEqual([""]);
})
test('padEnd', () => {
const str1 = 'Breaded Mushrooms';
expect(str1.padEnd(25, '.')).toEqual("Breaded Mushrooms........");
const str2 = '200';
expect(str2.padEnd(5)).toEqual("200 ");
expect('abc'.padEnd(10)).toEqual("abc ");
expect('abc'.padEnd(10, "foo")).toEqual("abcfoofoof");
expect('abc'.padEnd(6, "123456")).toEqual("abc123");
expect('abc'.padEnd(1)).toEqual("abc");
})
test('padStart', () => {
const str1 = '5';
expect(str1.padStart(2, '0')).toEqual("05");
expect('abc'.padStart(10)).toEqual(" abc");
expect('abc'.padStart(10, "foo")).toEqual("foofoofabc");
expect('abc'.padStart(6, "123456")).toEqual("123abc");
expect('abc'.padStart(8, "0")).toEqual("00000abc");
expect('abc'.padStart(1)).toEqual("abc");
})
test('repeat', () => {
const str1 = 'abc';
expect(str1.repeat(0)).toEqual("");
expect(str1.repeat(1)).toEqual("abc");
expect(str1.repeat(2)).toEqual("abcabc");
expect(str1.repeat(3.5)).toEqual("abcabcabc");
expect("".repeat(1)).toEqual("");
})
test('replace', () => {
const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
expect(p.replace('dog', 'monkey')).toEqual("The quick brown fox jumps over the lazy monkey. If the dog reacted, was it really lazy?");
const regex = /Dog/i;
expect(p.replace(regex, 'ferret')).toEqual("The quick brown fox jumps over the lazy ferret. If the dog reacted, was it really lazy?");
const str = 'abc12345#$*%';
const replacer = (match:string, p1:string, p2:string, p3:string, offset:number, string:string): string => {
// p1 is nondigits, p2 digits, and p3 non-alphanumerics
expect(offset).toEqual(0);
expect(match).toEqual(str);
expect(string).toEqual(str);
return [p1, p2, p3].join(' - ');
}
var newString = str.replace(/([^\d]*)(\d*)([^\w]*)/, replacer);
expect(newString).toEqual("abc - 12345 - #$*%");
const str1 = 'hello, world';
// const newString1 = str1.replace(/world/, (match: string, offset:number):string => `JavaScript (${offset})`);
// expect(newString1).toEqual('hello, JavaScript (7)');
})
test('search', () => {
const paragraph = 'The quick brown fox jumps over the lazy dog. If the dog barked, was it really lazy?';
const regex = /[^\w\s]/g;
expect(paragraph.search(regex)).toEqual(43);
var str = "hey JudE";
var re = /[A-Z]/g;
var re2 = /[.]/g;
expect(str.search(re)).toEqual(4);
expect(str.search(re2)).toEqual(-1);
expect("".search(re2)).toEqual(-1);
})
test('slice', () => {
const str = 'The quick brown fox jumps over the lazy dog.';
expect(str.slice(31)).toEqual("the lazy dog.");
let str1 = 'The morning is upon us.', // str1 的长度 length 是 23。
str2 = str1.slice(1, 8),
str3 = str1.slice(4, -2),
str4 = str1.slice(12),
str5 = str1.slice(30),
str6 = str1.slice();
expect(str2).toEqual("he morn");
expect(str3).toEqual("morning is upon u");
expect(str4).toEqual("is upon us.");
expect(str5).toEqual("");
expect(str6).toEqual("The morning is upon us.");
expect("".slice()).toEqual("");
})
test('split', () => {
const str = 'The quick brown fox jumps over the lazy dog.';
const words = str.split(' ');
expect(words[3]).toEqual("fox");
const chars = str.split('');
expect(chars[8]).toEqual("k");
var myString = "Hello World. How are you doing?";
var splits = myString.split(" ", 3);
var splits1 = myString.split(" ", 10);
expect(splits).toEqual(["Hello", "World.", "How"]);
expect(splits1).toEqual(['Hello', 'World.', 'How', 'are', 'you', 'doing?']);
expect(''.split('')).toEqual([])
expect('abc'.split('b')).toEqual(["a", "c"])
expect('abc'.split('d')).toEqual(["abc"])
var str1 = "Harry Trump ;Fred Barney; Helen Rigby ; Bill Abel ;Chris Hand ";
var re1 = /\s*(?:;|$)\s*/;
expect(str1.split(re1)).toEqual([ "Harry Trump", "Fred Barney", "Helen Rigby", "Bill Abel", "Chris Hand", "" ])
var str2 = "a, b, c, d, e";
var re2 = /,\s*/g;
expect(str2.split(re2)).toEqual(["a", "b", "c", "d", "e"]);
var str3 = "foo-bar_baz(qux-quux)_corge";
var re3 = new RegExp("[_-](?![^(]*\\))", "g");
expect(str3.split(re3)).toEqual(["foo", "bar", "baz(qux-quux)", "corge"]);
var str4 = "a, b, {c, d, e}, f, g, h";
var re4 = /,(?![^{]*\})/;
expect(str4.split(re4)).toEqual(["a", " b", " {c, d, e}", " f", " g", " h"]);
})
test('toLowerCase', () => {
const str1 = '中文简体 zh-CN || zh-Hans';
expect(str1.toLowerCase()).toEqual("中文简体 zh-cn || zh-hans");
const str2 = 'ALPHABET';
expect(str2.toLowerCase()).toEqual("alphabet");
})
test('toUpperCase', () => {
const sentence = 'The quick brown fox jumps over the lazy dog.';
expect(sentence.toUpperCase()).toEqual("THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG.");
})
test("lastIndexOf", () => {
expect('canal'.lastIndexOf('a')).toEqual(3);
expect('canal'.lastIndexOf('a', 2)).toEqual(1);
expect('canal'.lastIndexOf('a', 0)).toEqual(-1);
expect('canal'.lastIndexOf('')).toEqual(5);
expect('canal'.lastIndexOf('', 2)).toEqual(2);
expect("Blue Whale, Killer Whale".lastIndexOf("Whale")).toEqual(19);
expect("Blue Whale, Killer Whale".lastIndexOf("blue")).toEqual(-1);
})
test("substring", () => {
var str1 = "Mozilla";
expect(str1.substring(0, 3)).toEqual("Moz");
expect(str1.substring(3, 0)).toEqual("Moz");
expect(str1.substring(3, -3)).toEqual("Moz");
var str2 = "hello world";
// expect(str2.substring()).toEqual("hello world");
expect(str2.substring(6)).toEqual("world");
expect(str2.substring(0)).toEqual("hello world");
expect(str2.substring(0, 5)).toEqual("hello");
expect(str2.substring(6, 11)).toEqual("world");
expect(str2.substring(3, 8)).toEqual("lo wo");
expect(str2.substring(0, -1)).toEqual("");
expect(str2.substring(0, 20)).toEqual("hello world");
})
test("trim", () => {
const greeting = ' Hello world! ';
expect(greeting).toEqual(" Hello world! ");
expect(greeting.trim()).toEqual("Hello world!");
const orig:string = ' foo ';
expect(orig.trim()).toEqual("foo");
const str = '\t\t\tworld\t\t\t';
expect(str.trim()).toEqual('world');
const str1 = '\n\n\nhello\n\n\n';
expect(str1.trim()).toEqual('hello');
const str2 = '';
expect(str2.trim()).toEqual('');
})
test("trimStart", () => {
const str = ' Hello World ';
expect(str.trimStart()).toEqual('Hello World ');
const str1 = 'Hello World';
expect(str1.trimStart()).toEqual(str1);
const str2 = ' \t \n ';
expect(str2.trimStart()).toEqual('');
})
test("trimEnd", () => {
const str = ' Hello World ';
expect(str.trimEnd()).toEqual(' Hello World');
const str1 = 'Hello World';
expect(str1.trimEnd()).toEqual(str1);
const str2 = ' \t \n ';
expect(str2.trimEnd()).toEqual('');
})
test("startsWith", () => {
const str = 'hello world';
expect(str.startsWith('hello')).toEqual(true);
expect(str.startsWith('h')).toEqual(true);
expect(str.startsWith('HELLO')).toEqual(false);
expect(str.startsWith('o')).toEqual(false);
const str1:string = "To be, or not to be, that is the question.";
expect(str1.startsWith("To be")).toEqual(true);
expect(str1.startsWith("not to be")).toEqual(false);
expect(str1.startsWith("not to be", 10)).toEqual(true);
expect(str1.startsWith("not to be", 8)).toEqual(false);
})
test("matchAll", () => {
// const reg = /t(e)(st(\d?))/g;
// const str = 'test1test2';
// const result = [...str.matchAll(reg)];
// expect(result[0]).toEqual(["test1", "e", "st1", "1"]);
// expect(result[1]).toEqual(["test2", "e", "st2", "2"]);
// const reg1 = /[A-Z]/g;
// const str1 = 'The quick brown fox jumps over the lazy dog';
// const result1 = [...str1.matchAll(reg1)];
// expect(result1[0]).toEqual(["T"]);
})
test("replaceAll", () => {
// const p = 'The quick brown fox jumps over the lazy dog. If the dog reacted, was it really lazy?';
// expect(p.replaceAll('dog', 'monkey')).toEqual("The quick brown fox jumps over the lazy monkey. If the monkey reacted, was it really lazy?");
// const regex = /Dog/ig;
// expect(p.replaceAll(regex, 'ferret')).toEqual( "The quick brown fox jumps over the lazy ferret. If the ferret reacted, was it really lazy?");
// const reg = /[aeiou]/g;
// const str = 'The quick brown fox jumps over the lazy dog';
// const result = str.replaceAll(reg, '!');
// expect(result).toEqual("Th! q!!ck br!wn f!x j!mps !v!r th! l!zy d!g");
// const reg1 = /o/g;
// const str1 = 'Hello World!';
// const result1 = str1.replaceAll(reg1, (match, offset, original) => {
// expect(match).toEqual('o');
// expect(original[offset]).toEqual('o');
// expect(original).toEqual(str1);
// return `x`;
// });
// expect(result1).toEqual("Hellx Wxrld!");
})
})
}
import { testArray } from './Array.uts'
import { testDate } from './Date.uts'
import { testString } from './String.uts'
import { testError } from './Error.uts'
import { testJSON } from './JSON.uts'
import { testNumber } from './Number.uts'
import { testMap } from './Map.uts'
import { testSet } from './Set.uts'
import { testOperators } from './Operators.uts'
import { testMath } from './Math.uts'
import { testRegExp } from './RegExp.uts'
// #ifdef APP-ANDROID
// import { testReactiveArray } from './reactiveArray.uts'
// import { testReactiveMap } from './ReactiveMap.uts'
// #endif
// export { Result } from './tests.uts'
// Promise、Proxy、Reflect、Weakmap、WeakSet 不支持
export function runTests() : UTSJSONObject {
const ArrayRes = testArray();
const DateRes = testDate();
const StringRes = testString();
const ErrorRes = testError();
const JsonRes = testJSON();
const NumberRes = testNumber();
const MapRes = testMap();
const SetRes = testSet();
const OperatorsRes = testOperators();
const MathRes = testMath();
const RegExpRes = testRegExp();
// #ifdef APP-ANDROID
// const ReactiveArrayRes = testReactiveArray();
// const ReactiveMapRes = testReactiveMap();
// #endif
return {
Array: ArrayRes,
// #ifdef APP-ANDROID
// ReactiveArray: ReactiveArrayRes,
// #endif
Date: DateRes,
String: StringRes,
Error: ErrorRes,
Json: JsonRes,
Number: NumberRes,
Map: MapRes,
// #ifdef APP-ANDROID
// ReactiveMap: ReactiveMapRes,
// #endif
Set: SetRes,
Operators: OperatorsRes,
Math: MathRes,
RegExp: RegExpRes,
}
}
\ No newline at end of file
import { Matchers } from './Matchers.uts'
export const describes = new Map<string, Result>()
export class Result {
total = 0
passed: string[] = []
failed: string[] = []
}
let result: Result = new Result()
export function describe(name: string, fn: () => void): Result {
result = new Result()
describes.set(name, result)
fn()
return result
}
export function test(name: string, fn: () => void) {
try {
fn()
// console.log('push....',name)
result.passed.push(name)
// console.log('push....',result.passed.length)
} catch (e) {
result.failed.push(`${name}:\n${e.message}`)
}
result.total++
}
export function expect<T>(value: T): Matchers<T> {
return new Matchers(value);
}
Markdown is supported
0% .
You are about to add 0 people to the discussion. Proceed with caution.
先完成此消息的编辑!
想要评论请 注册