refactor: 将Data到ViewModel的转换由App转移至Server端
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
All checks were successful
deploy to server / build-and-deploy (push) Successful in 3m15s
- 将逻辑转移到Server端后,简化前端逻辑
This commit is contained in:
66
server/utils/object.test.ts
Normal file
66
server/utils/object.test.ts
Normal file
@ -0,0 +1,66 @@
|
||||
import { expect, test, describe } from 'vitest';
|
||||
|
||||
/**
|
||||
* 单元测试: isObject
|
||||
*/
|
||||
describe('isObject', () => {
|
||||
test('identify plain object', () => {
|
||||
expect(isObject({})).toBe(true);
|
||||
expect(isObject({ key: 'value' })).toBe(true);
|
||||
});
|
||||
test('identify null as non objevt', () => {
|
||||
expect(isObject(null)).toBe(false);
|
||||
});
|
||||
test('identify non-object types', () => {
|
||||
expect(isObject(undefined)).toBe(false);
|
||||
expect(isObject(42)).toBe(false);
|
||||
expect(isObject('string')).toBe(false);
|
||||
expect(isObject(Symbol('sym'))).toBe(false);
|
||||
expect(isObject(true)).toBe(false);
|
||||
expect(isObject(() => {})).toBe(false);
|
||||
});
|
||||
test('identify arrays as objects', () => {
|
||||
expect(isObject([])).toBe(true);
|
||||
});
|
||||
test('identify narrowed object type', () => {
|
||||
const value: unknown = { id: 1 };
|
||||
if (isObject<{ id: number }>(value)) {
|
||||
expect(value.id).toBe(1);
|
||||
} else {
|
||||
throw new Error('Type narrowing failed');
|
||||
}
|
||||
});
|
||||
});
|
||||
|
||||
/**
|
||||
* 单元测试: isArrayOfObject
|
||||
*/
|
||||
describe('isArrayOfObject', () => {
|
||||
test('identify array of plain objects', () => {
|
||||
const arr = [{ id: 1 }, { name: 'Alice' }];
|
||||
expect(isArrayOfObject<{ id?: number; name?: string }>(arr)).toBe(true);
|
||||
});
|
||||
test('identify array containing non-objects', () => {
|
||||
expect(isArrayOfObject([1, 2, 3])).toBe(false);
|
||||
expect(isArrayOfObject([{ id: 1 }, null])).toBe(false);
|
||||
expect(isArrayOfObject([{ id: 1 }, 'string'])).toBe(false);
|
||||
});
|
||||
test('identify non-array types', () => {
|
||||
expect(isArrayOfObject(null)).toBe(false);
|
||||
expect(isArrayOfObject({})).toBe(false);
|
||||
expect(isArrayOfObject(42)).toBe(false);
|
||||
});
|
||||
test('identify empty array as array of objects', () => {
|
||||
expect(isArrayOfObject([])).toBe(true);
|
||||
});
|
||||
test('identify narrowed array of object type', () => {
|
||||
const data: unknown = [{ id: 1 }, { id: 2 }];
|
||||
if (isArrayOfObject<{ id: number }>(data)) {
|
||||
// TS 能识别为 { id: number }[]
|
||||
expect(data[0].id).toBe(1);
|
||||
expect(data[1].id).toBe(2);
|
||||
} else {
|
||||
throw new Error('Type guard failed');
|
||||
}
|
||||
});
|
||||
});
|
||||
Reference in New Issue
Block a user