chore: import upstream snapshot with attribution
CI / build (push) Has been cancelled

This commit is contained in:
wehub-resource-sync
2026-07-13 13:09:51 +08:00
commit 0232b4e2bb
3528 changed files with 291404 additions and 0 deletions
@@ -0,0 +1,214 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from 'vitest';
import { FieldModel } from '@/core/field-model';
import { FieldArrayModel } from '@/core/field-array-model';
import { createForm } from '@/core/create-form';
describe('createForm', () => {
it('should create form with auto initialization by default', () => {
const { form, control } = createForm();
expect(form).toBeDefined();
expect(control).toBeDefined();
expect(control._formModel.initialized).toBe(true);
});
it('should disableAutoInit work', async () => {
const { control } = createForm({ disableAutoInit: true });
expect(control._formModel.initialized).toBe(false);
control.init();
expect(control._formModel.initialized).toBe(true);
});
it('should create form with initial values', () => {
const initialValues = {
username: 'John',
email: 'john@example.com',
age: 30,
};
const { form } = createForm({ initialValues });
expect(form.initialValues).toEqual(initialValues);
expect(form.values).toEqual(initialValues);
});
it('should create form with validation', async () => {
const { form } = createForm({
initialValues: { username: '' },
});
// Validation should be callable
const errors = await form.validate();
// Without explicit validators, errors should be empty or undefined
expect(errors === undefined || Object.keys(errors).length === 0).toBe(true);
});
it('should create form with empty options', () => {
const { form, control } = createForm({});
expect(form).toBeDefined();
expect(control).toBeDefined();
expect(control._formModel.initialized).toBe(true);
});
it('should create form without options', () => {
const { form, control } = createForm();
expect(form).toBeDefined();
expect(control).toBeDefined();
expect(control._formModel.initialized).toBe(true);
});
describe('control.getField', () => {
it('should get field by name', () => {
const { form, control } = createForm({
initialValues: {
username: 'John',
},
});
// Create field first
control._formModel.createField('username');
const field = control.getField('username');
expect(field).toBeDefined();
expect(field!.name).toBe('username');
expect(field!.value).toBe('John');
});
it('should return undefined for non-existent field', () => {
const { control } = createForm();
const field = control.getField('nonexistent');
expect(field).toBeUndefined();
});
it('should get FieldArray when field is array', () => {
const { control } = createForm({
initialValues: {
users: [{ name: 'Alice' }, { name: 'Bob' }],
},
});
// Create field array
control._formModel.createFieldArray('users');
const fieldArray = control.getField('users');
expect(fieldArray).toBeDefined();
expect(fieldArray!.name).toBe('users');
expect(Array.isArray(fieldArray!.value)).toBe(true);
});
it('should return Field for regular field', () => {
const { control } = createForm({
initialValues: {
username: 'John',
},
});
control._formModel.createField('username');
const field = control.getField('username');
expect(field).toBeDefined();
expect(field!.name).toBe('username');
expect((field as any).onChange).toBeDefined();
});
it('should return FieldArray for array field with array methods', () => {
const { control } = createForm({
initialValues: {
users: [{ name: 'Alice' }],
},
});
control._formModel.createFieldArray('users');
const fieldArrayModel = control._formModel.getField('users');
expect(fieldArrayModel).toBeInstanceOf(FieldArrayModel);
const fieldArray = control.getField('users');
expect(fieldArray).toBeDefined();
expect((fieldArray as any).append).toBeDefined();
expect((fieldArray as any).remove).toBeDefined();
expect((fieldArray as any).swap).toBeDefined();
expect((fieldArray as any).move).toBeDefined();
});
it('should handle nested field names', () => {
const { control } = createForm({
initialValues: {
user: {
profile: {
name: 'Alice',
},
},
},
});
control._formModel.createField('user.profile.name');
const field = control.getField('user.profile.name');
expect(field).toBeDefined();
expect(field!.name).toBe('user.profile.name');
expect(field!.value).toBe('Alice');
});
it('should handle array index in field names', () => {
const { control } = createForm({
initialValues: {
users: [{ name: 'Alice' }, { name: 'Bob' }],
},
});
control._formModel.createField('users.0.name');
const field = control.getField('users.0.name');
expect(field).toBeDefined();
expect(field!.name).toBe('users.0.name');
expect(field!.value).toBe('Alice');
});
});
describe('control.init', () => {
it('should initialize form with new options', () => {
const { control } = createForm({ disableAutoInit: true });
expect(control._formModel.initialized).toBe(false);
control.init();
expect(control._formModel.initialized).toBe(true);
});
it('should reinitialize form', () => {
const { control } = createForm({
initialValues: { username: 'John' },
});
expect(control._formModel.initialized).toBe(true);
expect(control._formModel.initialValues).toEqual({ username: 'John' });
control._formModel.dispose();
control.init();
expect(control._formModel.initialized).toBe(true);
});
});
it('should expose _formModel on control', () => {
const { control } = createForm();
expect(control._formModel).toBeDefined();
expect(control._formModel.init).toBeDefined();
expect(control._formModel.createField).toBeDefined();
});
});
@@ -0,0 +1,931 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Errors, ValidateTrigger, Warnings } from '@/types';
import { FormModel } from '@/core/form-model';
import { type FieldArrayModel } from '@/core/field-array-model';
import { FeedbackLevel } from '../src/types';
describe('FormArrayModel', () => {
let formModel = new FormModel();
describe('children', () => {
let arrayField: FieldArrayModel;
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
// 创建数组
formModel.createFieldArray('arr');
const field = formModel.getField<FieldArrayModel>('arr');
field!.append('a');
field!.append('b');
field!.append('c');
arrayField = field!;
});
it('can get children', () => {
expect(arrayField.children.length).toBe(3);
});
});
describe('append & delete', () => {
let arrayField: FieldArrayModel;
let arrEffect = vi.fn();
let aEffect = vi.fn();
let bEffect = vi.fn();
let cEffect = vi.fn();
let appendEffect = vi.fn();
let deleteEffect = vi.fn();
let aValidate = vi.fn();
let bValidate = vi.fn();
let cValidate = vi.fn();
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
arrEffect = vi.fn();
aEffect = vi.fn();
bEffect = vi.fn();
cEffect = vi.fn();
appendEffect = vi.fn();
deleteEffect = vi.fn();
aValidate = vi.fn();
bValidate = vi.fn();
cValidate = vi.fn();
formModel.init({
validateTrigger: ValidateTrigger.onChange,
validate: {
['arr.0']: aValidate,
['arr.1']: bValidate,
['arr.2']: cValidate,
},
});
// 创建其他field, 用于测试其他元素不会被影响
formModel.createField('other');
// 创建数组
formModel.createFieldArray('arr');
const field = formModel.getField<FieldArrayModel>('arr');
const a = field!.append('a');
const b = field!.append('b');
const c = field!.append('c');
arrayField = field!;
arrayField.onValueChange(arrEffect);
arrayField.onAppend(appendEffect);
arrayField.onDelete(deleteEffect);
a.onValueChange(aEffect);
b.onValueChange(bEffect);
c.onValueChange(cEffect);
});
it('append', async () => {
vi.spyOn(arrayField, 'validate');
arrayField.append('d');
expect(arrayField.children.length).toBe(4);
expect(formModel.getField('other')).toBeDefined();
expect(arrEffect).toHaveBeenCalledTimes(1);
expect(appendEffect).toHaveBeenCalledTimes(1);
expect(arrayField.validate).toHaveBeenCalledTimes(1);
});
it('should fire OnFormValueChange event for arr when append', () => {
vi.spyOn(formModel.onFormValuesInitEmitter, 'fire');
vi.spyOn(formModel.onFormValuesChangeEmitter, 'fire');
arrayField.append('d');
expect(formModel.onFormValuesChangeEmitter.fire).toHaveBeenCalledWith({
values: {
arr: ['a', 'b', 'c', 'd'],
},
prevValues: {
arr: ['a', 'b', 'c'],
},
name: 'arr',
options: {
action: 'array-append',
indexes: [3],
},
});
expect(formModel.onFormValuesInitEmitter.fire).toHaveBeenCalledWith({
values: {
arr: ['a', 'b', 'c', 'd'],
},
prevValues: {
arr: ['a', 'b', 'c'],
},
name: 'arr.3',
});
});
it('delete first element', () => {
vi.spyOn(formModel.onFormValuesChangeEmitter, 'fire');
vi.spyOn(arrayField, 'validate');
vi.spyOn(arrayField.onValueChangeEmitter, 'fire');
arrayField.delete(0);
// assert value
expect(arrayField.children.length).toBe(2);
expect(arrayField.children[0].value).toBe('b');
expect(arrayField.children[1].value).toBe('c');
expect(formModel.getField('other')).toBeDefined();
// assert change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).toHaveBeenCalledTimes(1);
expect(bEffect).toHaveBeenCalledTimes(1);
expect(cEffect).toHaveBeenCalledTimes(1);
expect(deleteEffect).toHaveBeenCalledTimes(1);
expect(formModel.onFormValuesChangeEmitter.fire).toHaveBeenCalledWith({
values: {
arr: ['b', 'c'],
},
prevValues: {
arr: ['a', 'b', 'c'],
},
name: 'arr',
options: {
action: 'array-splice',
indexes: [0],
},
});
expect(formModel.onFormValuesChangeEmitter.fire).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(arrayField.validate).toHaveBeenCalledTimes(1);
expect(aValidate).not.toHaveBeenCalled();
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
});
it('delete middle element', () => {
vi.spyOn(arrayField, 'validate');
vi.spyOn(arrayField.onValueChangeEmitter, 'fire');
arrayField.delete(1);
// assert values
expect(arrayField.children.length).toBe(2);
expect(arrayField.children[0].value).toBe('a');
expect(arrayField.children[1].value).toBe('c');
expect(formModel.getField('other')).toBeDefined();
// assert change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).not.toHaveBeenCalled();
expect(bEffect).toHaveBeenCalledTimes(1);
expect(cEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
expect(arrayField.validate).toHaveBeenCalledTimes(1);
});
it('delete last element', () => {
arrayField.delete(2);
expect(arrayField.children.length).toBe(2);
expect(arrayField.children[0].value).toBe('a');
expect(arrayField.children[1].value).toBe('b');
expect(formModel.getField('other')).toBeDefined();
expect(arrEffect).toHaveBeenCalled();
expect(cEffect).toHaveBeenCalled();
});
it('delete element which has nested field', () => {
vi.spyOn(arrayField, 'validate');
const axField = formModel.createField('arr.0.x');
const bxField = formModel.createField('arr.1.x');
vi.spyOn(axField, 'validate');
vi.spyOn(bxField, 'validate');
formModel.setValueIn('arr.0', { x: 1 });
formModel.setValueIn('arr.1', { x: 2 });
expect(arrayField.value).toEqual([{ x: 1 }, { x: 2 }, 'c']);
arrayField.delete(0);
expect(arrayField.value).toEqual([{ x: 2 }, 'c']);
// assert change events
expect(aEffect).toHaveBeenCalledTimes(2); // setValueIn 触发一次, delete 触发一次
expect(bEffect).toHaveBeenCalledTimes(2); // setValueIn 触发一次, delete 触发一次
expect(cEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(aValidate).toHaveBeenCalledTimes(1); // setValueIn 触发一次, delete 不会触发
expect(bValidate).toHaveBeenCalledTimes(1); // setValueIn 触发一次, delete 不会触发
expect(cValidate).not.toHaveBeenCalled();
expect(axField.validate).toHaveBeenCalledTimes(1); // setValueIn 触发一次, delete 不会触发
expect(bxField.validate).toHaveBeenCalledTimes(1); // setValueIn 触发一次, delete 不会触发
});
it('more elements delete', () => {
/**
* 数组为 [a,b,c,d]
* 删除 b
* 希望数组值为 [a,c,d]
* 希望formModel中的field也正确对应
*/
arrayField.append('d');
vi.spyOn(arrayField, 'validate');
arrayField.delete(1);
// assert values
expect(arrayField.children.length).toBe(3);
expect(arrayField.children[0].value).toBe('a');
expect(arrayField.children[1].value).toBe('c');
expect(arrayField.children[2].value).toBe('d');
expect(formModel.getField('arr.2')?.value).toBe('d');
expect(formModel.getField('other')).toBeDefined();
// assert value change events
expect(arrEffect).toHaveBeenCalled();
expect(bEffect).toHaveBeenCalled();
expect(cEffect).toHaveBeenCalled();
expect(arrayField.validate).toHaveBeenCalledTimes(1);
});
});
describe('_splice', () => {
let arrayField: FieldArrayModel;
let aEffect = vi.fn();
let bEffect = vi.fn();
let cEffect = vi.fn();
let dEffect = vi.fn();
let eEffect = vi.fn();
let aValidate = vi.fn();
let bValidate = vi.fn();
let cValidate = vi.fn();
let dValidate = vi.fn();
let eValidate = vi.fn();
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
aEffect = vi.fn();
bEffect = vi.fn();
cEffect = vi.fn();
dEffect = vi.fn();
eEffect = vi.fn();
aValidate = vi.fn();
bValidate = vi.fn();
cValidate = vi.fn();
dValidate = vi.fn();
eValidate = vi.fn();
formModel.createFieldArray('arr');
formModel.init({
validateTrigger: ValidateTrigger.onChange,
validate: {
['arr.0']: aValidate,
['arr.1']: bValidate,
['arr.2']: cValidate,
['arr.3']: dValidate,
['arr.4']: eValidate,
},
});
const field = formModel.getField<FieldArrayModel>('arr');
const aField = field!.append('a');
const bField = field!.append('b');
const cField = field!.append('c');
const dField = field!.append('d');
const eField = field!.append('e');
aField.onValueChange(aEffect);
bField.onValueChange(bEffect);
cField.onValueChange(cEffect);
dField.onValueChange(dEffect);
eField.onValueChange(eEffect);
arrayField = field!;
vi.spyOn(arrayField, 'validate');
vi.spyOn(arrayField.onValueChangeEmitter, 'fire');
});
it('should throw error when delete count exceeds array length', () => {
expect(() => {
arrayField._splice(0, 6);
}).toThrowError();
});
it('should throw error when delete in empty array', () => {
arrayField._splice(0, 5);
expect(() => {
arrayField._splice(0);
}).toThrowError();
});
it('splice first 2', () => {
arrayField._splice(0, 2);
// assert values
expect(arrayField.children.length).toBe(3);
expect(arrayField.children[0].value).toBe('c');
expect(arrayField.children[1].value).toBe('d');
expect(arrayField.children[2].value).toBe('e');
// assert value change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).toHaveBeenCalledTimes(1);
expect(bEffect).toHaveBeenCalledTimes(1);
expect(cEffect).toHaveBeenCalledTimes(1);
expect(dEffect).toHaveBeenCalledTimes(1);
expect(eEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(arrayField.validate).toHaveBeenCalledTimes(1);
expect(aValidate).not.toHaveBeenCalled();
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
expect(dValidate).not.toHaveBeenCalled();
expect(eValidate).not.toHaveBeenCalled();
});
it('splice last 2', () => {
arrayField._splice(3, 2);
// assert values
expect(arrayField.children.length).toBe(3);
expect(arrayField.children[0].value).toBe('a');
expect(arrayField.children[1].value).toBe('b');
expect(arrayField.children[2].value).toBe('c');
// assert value change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).not.toHaveBeenCalled();
expect(bEffect).not.toHaveBeenCalled();
expect(cEffect).not.toHaveBeenCalled();
expect(dEffect).toHaveBeenCalledTimes(1);
expect(eEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(arrayField.validate).toHaveBeenCalledTimes(1);
expect(aValidate).not.toHaveBeenCalled();
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
expect(dValidate).not.toHaveBeenCalled();
expect(eValidate).not.toHaveBeenCalled();
});
it('splice middle elements', () => {
arrayField._splice(1, 2);
// assert values
expect(arrayField.children.length).toBe(3);
expect(arrayField.children[0].value).toBe('a');
expect(arrayField.children[1].value).toBe('d');
expect(arrayField.children[2].value).toBe('e');
// assert value change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).not.toHaveBeenCalled();
expect(bEffect).toHaveBeenCalledTimes(1);
expect(cEffect).toHaveBeenCalledTimes(1);
expect(dEffect).toHaveBeenCalledTimes(1);
expect(eEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(arrayField.validate).toHaveBeenCalledTimes(1);
expect(aValidate).not.toHaveBeenCalled();
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
expect(dValidate).not.toHaveBeenCalled();
expect(eValidate).not.toHaveBeenCalled();
});
it('splice all elements', () => {
arrayField._splice(0, 5);
expect(arrayField.children.length).toBe(0);
expect(arrayField.value).toEqual([]);
// assert value change events
expect(arrayField.onValueChangeEmitter.fire).toHaveBeenCalledTimes(1);
expect(aEffect).toHaveBeenCalledTimes(1);
expect(bEffect).toHaveBeenCalledTimes(1);
expect(cEffect).toHaveBeenCalledTimes(1);
expect(dEffect).toHaveBeenCalledTimes(1);
expect(eEffect).toHaveBeenCalledTimes(1);
// assert validate trigger
expect(arrayField.validate).toHaveBeenCalledTimes(1);
expect(aValidate).not.toHaveBeenCalled();
expect(bValidate).not.toHaveBeenCalled();
expect(cValidate).not.toHaveBeenCalled();
expect(dValidate).not.toHaveBeenCalled();
expect(eValidate).not.toHaveBeenCalled();
});
});
describe('State check when _splice', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('should keep state of rest fields after delete a prev field', () => {
const arrayField = formModel.createFieldArray('arr');
formModel.init({
validateTrigger: ValidateTrigger.onChange,
});
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
// 设置第1项的state
const aFieldModel = formModel.getField('arr.1');
aFieldModel!.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'error' }],
} as unknown as Errors;
aFieldModel!.state.warnings = {
'arr.1': [{ name: 'arr.1', message: 'warning' }],
} as unknown as Warnings;
// 删除第0项
arrayField._splice(0);
// 原第一项变为第0项且他的state 被保留了, 且errors 中的路径标识也更新了
expect(formModel.getField('arr.0')!.state.errors).toEqual({
'arr.0': [{ name: 'arr.0', message: 'error' }],
});
expect(formModel.getField('arr.0')!.state.warnings).toEqual({
'arr.0': [{ name: 'arr.0', message: 'warning' }],
});
expect(formModel.getField('arr.2')).toBeUndefined();
});
it('should keep state of rest fields after delete a prev field, when nested field', () => {
const arrayField = formModel.createFieldArray('arr');
formModel.init({
validateTrigger: ValidateTrigger.onChange,
initialValues: {
arr: [
{ x: 1, y: 2 },
{ x: 0, y: 0 },
{ x: 0, y: 0 },
],
},
});
formModel.createField('arr.0');
formModel.createField('arr.0.x');
formModel.createField('arr.0.y');
formModel.createField('arr.1');
formModel.createField('arr.1.x');
formModel.createField('arr.1.y');
formModel.createField('arr.2');
formModel.createField('arr.2.x');
formModel.createField('arr.2.y');
// 设置第1项的state
const aFieldModel = formModel.getField('arr.1.x');
aFieldModel!.state.errors = {
'arr.1.x': [{ name: 'arr.1.x', message: 'error' }],
} as unknown as Errors;
// 删除第0项
arrayField._splice(0);
// 原第一项变为第0项且他的state errors 被保留了, 且errors 中的路径标识也更新了
expect(formModel.getField('arr.0')!.state.errors).toEqual({
'arr.0.x': [{ name: 'arr.0.x', message: 'error' }],
});
expect(formModel.getField('arr.0.x')!.state.errors).toEqual({
'arr.0.x': [{ name: 'arr.0.x', message: 'error' }],
});
expect(formModel.getField('arr.2')).toBeUndefined();
expect(formModel.getField('arr.2.x')).toBeUndefined();
expect(formModel.getField('arr.2.y')).toBeUndefined();
});
it('should align errors and warnings state with existing field in fieldMap ', () => {
const arrayField = formModel.createFieldArray('arr');
formModel.init({
validateTrigger: ValidateTrigger.onChange,
initialValues: {
arr: [
{ x: 1, y: 2 },
{ x: 0, y: 0 },
{ x: 0, y: 0 },
],
},
});
const field0 = formModel.createField('arr.0');
const field0x = formModel.createField('arr.0.x');
const field0y = formModel.createField('arr.0.y');
const field1 = formModel.createField('arr.1');
const field1x = formModel.createField('arr.1.x');
const field1y = formModel.createField('arr.1.y');
const field2 = formModel.createField('arr.2');
const field2x = formModel.createField('arr.2.x');
const field2y = formModel.createField('arr.2.y');
field0x.state.errors = {
'arr.0.x': [{ name: 'arr.0.x', message: 'error' }],
} as unknown as Errors;
field0x.bubbleState();
field1x.state.errors = {
'arr.1.x': [{ name: 'arr.1.x', message: 'error' }],
} as unknown as Errors;
field1x.bubbleState();
field2x.state.errors = {
'arr.2.x': [{ name: 'arr.2.x', message: 'error' }],
} as unknown as Errors;
// 删除第0项
arrayField._splice(0);
expect(formModel.state.errors['arr.0.x']).toEqual([{ name: 'arr.0.x', message: 'error' }]);
expect(formModel.state.errors['arr.1.x']).toEqual([{ name: 'arr.1.x', message: 'error' }]);
expect(formModel.state.errors['arr.2.x']).toBeUndefined();
expect(field0.state.errors['arr.0.x']).toEqual([{ name: 'arr.0.x', message: 'error' }]);
expect(field1.state.errors['arr.1.x']).toEqual([{ name: 'arr.1.x', message: 'error' }]);
expect(arrayField.state.errors['arr.0.x']).toEqual([{ name: 'arr.0.x', message: 'error' }]);
expect(arrayField.state.errors['arr.1.x']).toEqual([{ name: 'arr.1.x', message: 'error' }]);
expect(arrayField.state.errors['arr.2.x']).toBeUndefined();
});
it('should not keep previous error state when delete first elem in array then add back ', () => {
const arrayField = formModel.createFieldArray('arr');
formModel.init({
validateTrigger: ValidateTrigger.onChange,
initialValues: {
arr: [{ x: 1, y: 2 }],
},
});
const field0 = formModel.createField('arr.0');
const field0x = formModel.createField('arr.0.x');
const field0y = formModel.createField('arr.0.y');
field0x.state.errors = {
'arr.0.x': [{ name: 'arr.0.x', message: 'error' }],
} as unknown as Errors;
field0x.bubbleState();
// 删除第0项
arrayField._splice(0);
expect(formModel.state.errors['arr.0.x']).toBeUndefined();
expect(arrayField.state.errors['arr.0.x']).toBeUndefined();
expect(formModel._fieldMap.get('arr.0')).toBeUndefined();
arrayField.append({ x: 1, y: 2 });
formModel.createField('arr.0.x');
expect(formModel._fieldMap.get('arr.0')).toBeDefined();
expect(formModel.state.errors['arr.0.x']).toBeUndefined();
expect(formModel._fieldMap.get('arr.0.x').state.errors).toBeUndefined();
});
});
describe('swap', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('can swap from 0 to middle index', () => {
const arrayField = formModel.createFieldArray('arr');
const a = arrayField!.append('a');
const b = arrayField!.append('b');
const c = arrayField!.append('c');
formModel.init({});
a.state.errors = {
'arr.0': [{ name: 'arr.0', message: 'err0', level: FeedbackLevel.Error }],
};
b.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'err1', level: FeedbackLevel.Error }],
};
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.swap(0, 1);
expect(formModel.values).toEqual({ arr: ['b', 'a', 'c'] });
expect(formModel.getField('arr.0').state.errors).toEqual({
'arr.0': [{ name: 'arr.0', message: 'err1', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.1').state.errors).toEqual({
'arr.1': [{ name: 'arr.1', message: 'err0', level: FeedbackLevel.Error }],
});
});
it('can chained swap', () => {
const arrayField = formModel.createFieldArray('x.arr');
const a = arrayField!.append('a');
const b = arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
a.state.errors = {
'arr.0': [{ name: 'arr.0', message: 'err0', level: FeedbackLevel.Error }],
};
b.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'err1', level: FeedbackLevel.Error }],
};
expect(a.name).toBe('x.arr.0');
expect(b.name).toBe('x.arr.1');
expect(formModel.values.x).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.swap(1, 0);
expect(a.name).toBe('x.arr.1');
expect(b.name).toBe('x.arr.0');
expect(formModel.values.x).toEqual({ arr: ['b', 'a', 'c'] });
arrayField.swap(1, 0);
expect(a.name).toBe('x.arr.0');
expect(formModel.fieldMap.get('x.arr.0').name).toBe('x.arr.0');
expect(b.name).toBe('x.arr.1');
expect(formModel.fieldMap.get('x.arr.1').name).toBe('x.arr.1');
expect(formModel.values.x).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.swap(1, 0);
expect(a.name).toBe('x.arr.1');
expect(formModel.fieldMap.get('x.arr.1').name).toBe('x.arr.1');
expect(b.name).toBe('x.arr.0');
expect(formModel.fieldMap.get('x.arr.0').name).toBe('x.arr.0');
expect(formModel.values.x).toEqual({ arr: ['b', 'a', 'c'] });
});
it('can swap from 0 to last index', () => {
const arrayField = formModel.createFieldArray('arr');
const a = arrayField!.append('a');
const b = arrayField!.append('b');
const c = arrayField!.append('c');
formModel.init({});
a.state.errors = {
'arr.0': [{ name: 'arr.0', message: 'err0', level: FeedbackLevel.Error }],
};
c.state.errors = {
'arr.2': [{ name: 'arr.2', message: 'err2', level: FeedbackLevel.Error }],
};
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.swap(0, 2);
expect(formModel.values).toEqual({ arr: ['c', 'b', 'a'] });
expect(formModel.getField('arr.0').state.errors).toEqual({
'arr.0': [{ name: 'arr.0', message: 'err2', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.2').state.errors).toEqual({
'arr.2': [{ name: 'arr.2', message: 'err0', level: FeedbackLevel.Error }],
});
});
it('can swap from middle index to last index', () => {
const arrayField = formModel.createFieldArray('arr');
const a = arrayField!.append('a');
const b = arrayField!.append('b');
const c = arrayField!.append('c');
formModel.init({});
b.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'err1', level: FeedbackLevel.Error }],
};
c.state.errors = {
'arr.2': [{ name: 'arr.2', message: 'err2', level: FeedbackLevel.Error }],
};
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.swap(1, 2);
expect(formModel.values).toEqual({ arr: ['a', 'c', 'b'] });
expect(formModel.getField('arr.1').state.errors).toEqual({
'arr.1': [{ name: 'arr.1', message: 'err2', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.2').state.errors).toEqual({
'arr.2': [{ name: 'arr.2', message: 'err1', level: FeedbackLevel.Error }],
});
});
it('can swap from middle index to another middle index', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
const b = arrayField!.append('b');
const c = arrayField!.append('c');
arrayField!.append('d');
formModel.init({});
b.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'err1', level: FeedbackLevel.Error }],
};
c.state.errors = {
'arr.2': [{ name: 'arr.2', message: 'err2', level: FeedbackLevel.Error }],
};
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c', 'd'] });
arrayField.swap(1, 2);
expect(formModel.values).toEqual({ arr: ['a', 'c', 'b', 'd'] });
expect(formModel.getField('arr.1').state.errors).toEqual({
'arr.1': [{ name: 'arr.1', message: 'err2', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.2').state.errors).toEqual({
'arr.2': [{ name: 'arr.2', message: 'err1', level: FeedbackLevel.Error }],
});
});
it('can swap for nested array', () => {
const arrayField = formModel.createFieldArray('arr');
const a = arrayField!.append({ x: 'x0', y: 'y0' });
const b = arrayField!.append({ x: 'x1', y: 'y1' });
const ax = formModel.createField('arr.0.x');
const ay = formModel.createField('arr.0.y');
const bx = formModel.createField('arr.1.x');
const by = formModel.createField('arr.1.y');
formModel.init({});
ax.state.errors = {
'arr.0.x': [{ name: 'arr.0.x', message: 'err0x', level: FeedbackLevel.Error }],
};
bx.state.errors = {
'arr.1.x': [{ name: 'arr.1.x', message: 'err1x', level: FeedbackLevel.Error }],
};
expect(formModel.values).toEqual({
arr: [
{ x: 'x0', y: 'y0' },
{ x: 'x1', y: 'y1' },
],
});
arrayField.swap(0, 1);
expect(formModel.values).toEqual({
arr: [
{ x: 'x1', y: 'y1' },
{ x: 'x0', y: 'y0' },
],
});
expect(formModel.getField('arr.0.x').state.errors).toEqual({
'arr.0.x': [{ name: 'arr.0.x', message: 'err1x', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.1.x').state.errors).toEqual({
'arr.1.x': [{ name: 'arr.1.x', message: 'err0x', level: FeedbackLevel.Error }],
});
// assert form.state.errors
expect(formModel.state.errors['arr.0.x']).toEqual([
{ name: 'arr.0.x', message: 'err1x', level: FeedbackLevel.Error },
]);
expect(formModel.state.errors['arr.1.x']).toEqual([
{ name: 'arr.1.x', message: 'err0x', level: FeedbackLevel.Error },
]);
});
it('should have correct form.state.errors after swapping invalid field with valid field', () => {
const arrayField = formModel.createFieldArray('arr');
const a = arrayField!.append('a');
const b = arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
b.state.errors = {
'arr.1': [{ name: 'arr.1', message: 'err1', level: FeedbackLevel.Error }],
};
arrayField.swap(0, 1);
expect(formModel.getField('arr.0').state.errors).toEqual({
'arr.0': [{ name: 'arr.0', message: 'err1', level: FeedbackLevel.Error }],
});
expect(formModel.getField('arr.1').state.errors).toEqual(undefined);
});
it('should trigger array effect and child effect', () => {
const arrayField = formModel.createFieldArray('arr');
const fieldA = arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
const arrayEffect = vi.fn();
arrayField.onValueChange(arrayEffect);
const fieldAEffect = vi.fn();
fieldA.onValueChange(fieldAEffect);
formModel.init({});
arrayField.swap(1, 2);
expect(arrayEffect).toHaveBeenCalledOnce();
expect(fieldAEffect).toHaveBeenCalledOnce();
});
});
describe('move', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('should throw error when from or to exceeds bound', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
expect(() => arrayField.move(-1, 1)).toThrowError();
expect(() => arrayField.move(1, -1)).toThrowError();
expect(() => arrayField.move(1, 3)).toThrowError();
expect(() => arrayField.move(3, 1)).toThrowError();
});
it('can move from 0 to middle index', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.move(0, 1);
expect(formModel.values).toEqual({ arr: ['b', 'a', 'c'] });
});
it('can move from 0 to last index', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.move(0, 2);
expect(formModel.values).toEqual({ arr: ['b', 'c', 'a'] });
});
it('can move from middle index to last index', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c'] });
arrayField.move(1, 2);
expect(formModel.values).toEqual({ arr: ['a', 'c', 'b'] });
});
it('can move from middle index to another middle index', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
arrayField!.append('d');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c', 'd'] });
arrayField.move(1, 2);
expect(formModel.values).toEqual({ arr: ['a', 'c', 'b', 'd'] });
});
it('can move from middle index to another middle index with more elements', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
arrayField!.append('d');
arrayField!.append('e');
arrayField!.append('f');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c', 'd', 'e', 'f'] });
arrayField.move(1, 4);
expect(formModel.values).toEqual({ arr: ['a', 'c', 'd', 'e', 'b', 'f'] });
});
it('can move from middle index to another middle index with more elements when to is greater than from', () => {
const arrayField = formModel.createFieldArray('arr');
arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
arrayField!.append('d');
arrayField!.append('e');
arrayField!.append('f');
formModel.init({});
expect(formModel.values).toEqual({ arr: ['a', 'b', 'c', 'd', 'e', 'f'] });
arrayField.move(4, 1);
expect(formModel.values).toEqual({ arr: ['a', 'e', 'b', 'c', 'd', 'f'] });
});
it('should trigger array effect and child effect', () => {
const arrayField = formModel.createFieldArray('arr');
const fieldA = arrayField!.append('a');
arrayField!.append('b');
arrayField!.append('c');
const arrayEffect = vi.fn();
arrayField.onValueChange(arrayEffect);
const fieldAEffect = vi.fn();
fieldA.onValueChange(fieldAEffect);
formModel.init({});
arrayField.move(1, 2);
expect(arrayEffect).toHaveBeenCalledOnce();
expect(fieldAEffect).toHaveBeenCalledOnce();
});
});
});
@@ -0,0 +1,443 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { Errors, FeedbackLevel, ValidateTrigger } from '@/types';
import { FormModel } from '@/core/form-model';
describe('FieldModel', () => {
let formModel = new FormModel();
describe('state', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('can bubble', () => {
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
const parentField = formModel.getField('parent')!;
childField.value = 1;
expect(childField.state.isTouched).toBe(true);
expect(parentField.state.isTouched).toBe(true);
expect(formModel.state.isTouched).toBe(true);
});
it('can bubble with array', () => {
formModel.createField('parent');
formModel.createField('parent.arr');
formModel.createField('parent.arr.1');
const arrChild = formModel.getField('parent.arr.1')!;
const arrField = formModel.getField('parent.arr')!;
const parentField = formModel.getField('parent')!;
arrChild.value = 1;
expect(arrChild.state.isTouched).toBe(true);
expect(arrField.state.isTouched).toBe(true);
expect(parentField.state.isTouched).toBe(true);
expect(formModel.state.isTouched).toBe(true);
});
it('do not set isTouched for init value set', () => {
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
const parentField = formModel.getField('parent')!;
expect(childField.state.isTouched).toBe(false);
expect(parentField.state.isTouched).toBe(false);
expect(formModel.state.isTouched).toBe(false);
});
});
describe('validate', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('when validate func return only a message', async () => {
formModel.init({ validate: { 'parent.*': () => 'some message' } });
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
expect(childField.state.errors).toBeUndefined();
await childField.validate();
expect(childField.state.errors?.['parent.child'][0].message).toBe('some message');
expect(childField.state.errors?.['parent.child'][0].level).toBe(FeedbackLevel.Error);
});
it('when validate func return a FieldWarning', async () => {
formModel.init({
validate: {
'parent.*': () => ({
level: FeedbackLevel.Warning,
message: 'some message',
}),
},
});
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
expect(childField.state.errors).toBeUndefined();
await childField.validate();
expect(childField.state.warnings?.['parent.child'][0].message).toBe('some message');
expect(childField.state.warnings?.['parent.child'][0].level).toBe(FeedbackLevel.Warning);
});
it('when validate return a FormError', async () => {
formModel.init({
validate: {
'parent.*': () => ({
level: FeedbackLevel.Error,
message: 'some message',
}),
},
});
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
expect(childField.state.errors?.length).toBeUndefined();
await childField.validate();
expect(childField.state.errors?.['parent.child'][0].message).toBe('some message');
expect(childField.state.errors?.['parent.child'][0].level).toBe(FeedbackLevel.Error);
});
it('should bubble errors to parent field', async () => {
formModel.init({
validate: {
'parent.*': () => ({
level: FeedbackLevel.Error,
message: 'some message',
}),
},
});
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
const parentField = formModel.getField('parent')!;
await childField.validate();
expect(parentField.state.errors?.['parent.child'][0].message).toBe('some message');
expect(parentField.state.errors?.['parent.child'][0].level).toBe(FeedbackLevel.Error);
});
it('should bubble errors to form', async () => {
formModel.init({
validate: {
'parent.*': () => ({
level: FeedbackLevel.Error,
message: 'some message',
}),
},
});
formModel.createField('parent');
formModel.createField('parent.child');
const childField = formModel.getField('parent.child')!;
await childField.validate();
expect(formModel.state.errors?.['parent.child'][0].message).toBe('some message');
expect(formModel.state.errors?.['parent.child'][0].level).toBe(FeedbackLevel.Error);
});
it('should correctly set and bubble invalid', async () => {
formModel.init({
validate: {
'parent.*': () => ({
level: FeedbackLevel.Error,
message: 'some message',
}),
},
});
const parent = formModel.createField('parent');
const child = formModel.createField('parent.child');
await child.validate();
expect(child.state.invalid).toBe(true);
expect(parent.state.invalid).toBe(true);
expect(formModel.state.invalid).toBe(true);
});
it('should validate self ancestors and child', async () => {
formModel.init({
validateTrigger: ValidateTrigger.onChange,
});
const root = formModel.createField('root');
const l1 = formModel.createField('root.l1');
const l2 = formModel.createField('root.l1.l2');
const l3 = formModel.createField('root.l1.l2.l3');
const l4 = formModel.createField('root.l1.l2.l3.l4');
const other = formModel.createField('root.other');
vi.spyOn(root, 'validate');
vi.spyOn(l1, 'validate');
vi.spyOn(l2, 'validate');
vi.spyOn(l3, 'validate');
vi.spyOn(l4, 'validate');
vi.spyOn(other, 'validate');
formModel.setValueIn('root.l1.l2', 1);
expect(root.validate).toHaveBeenCalledTimes(1);
expect(l1.validate).toHaveBeenCalledTimes(1);
expect(l2.validate).toHaveBeenCalledTimes(1);
expect(l3.validate).toHaveBeenCalledTimes(1);
expect(l4.validate).toHaveBeenCalledTimes(1);
expect(other.validate).toHaveBeenCalledTimes(0);
});
it('should validate when multiple pattern match ', async () => {
const validate1 = vi.fn();
const validate2 = vi.fn();
formModel.init({
validateTrigger: ValidateTrigger.onChange,
validate: {
'a.*.input': validate1,
'a.1.input': validate2,
},
initialValues: {
a: [{ input: '0' }, { input: '1' }],
},
});
const root = formModel.createField('a');
const i0 = formModel.createField('a.0.input');
const i1 = formModel.createField('a.1.input');
formModel.setValueIn('a.1.input', 'xxx');
expect(validate1).toHaveBeenCalledTimes(1);
expect(validate2).toHaveBeenCalledTimes(1);
});
// 暂时注释了从 parent 触发validate 的能力,所以注释这个单测
// it('can trigger validate from parent', async () => {
// formModel.init({
// validate: {
// 'parent.child1': () => ({
// level: FeedbackLevel.Error,
// message: 'error',
// }),
// 'parent.child2': () => ({
// level: FeedbackLevel.Warning,
// message: 'warning',
// }),
// },
// });
// const parent = formModel.createField('parent');
// formModel.createField('parent.child1');
// formModel.createField('parent.child2');
//
// await parent.validate();
//
// expect(formModel.state.errors?.['parent.child1'][0].message).toBe('error');
// expect(formModel.state.warnings?.['parent.child2'][0].level).toBe('warning');
// });
});
describe('onValueChange', () => {
let formEffect = vi.fn();
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
formEffect = vi.fn();
formModel.onFormValuesChange(formEffect);
});
it('should bubble value change', () => {
const parent = formModel.createField('parent');
const child1 = formModel.createField('parent.child1');
const childOnChange = vi.fn();
const parentOnChange = vi.fn();
child1.onValueChange(childOnChange);
parent.onValueChange(parentOnChange);
child1.value = 1;
expect(parentOnChange).toHaveBeenCalledTimes(1);
expect(childOnChange).toHaveBeenCalledTimes(1);
expect(formEffect).toHaveBeenCalledTimes(1);
});
it('should bubble value change in array when delete', () => {
const parent = formModel.createField('parent');
const arr = formModel.createFieldArray('parent.arr');
const item1 = formModel.createField('parent.arr.0');
const parentOnChange = vi.fn();
const arrOnChange = vi.fn();
const item1OnChange = vi.fn();
parent.onValueChange(parentOnChange);
arr.onValueChange(arrOnChange);
item1.onValueChange(item1OnChange);
formModel.setValueIn('parent.arr.0', 1);
arr.delete(0);
expect(item1OnChange).toHaveBeenCalledTimes(2);
expect(arrOnChange).toHaveBeenCalledTimes(2);
expect(parentOnChange).toHaveBeenCalledTimes(2);
});
it('should bubble value change in array when append', () => {
const parent = formModel.createField('parent');
const arr = formModel.createFieldArray('parent.arr');
const parentOnChange = vi.fn();
const arrOnChange = vi.fn();
parent.onValueChange(parentOnChange);
arr.onValueChange(arrOnChange);
arr.append('1');
expect(arrOnChange).toHaveBeenCalledTimes(1);
expect(parentOnChange).toHaveBeenCalledTimes(1);
expect(formEffect).toHaveBeenCalledTimes(1);
});
it('should not trigger child field change when array append', () => {
formModel.createField('parent');
const arr = formModel.createFieldArray('parent.arr');
const item0 = formModel.createField('parent.arr.0');
const item0x = formModel.createField('parent.arr.0.x');
const item0OnChange = vi.fn();
const item0xOnChange = vi.fn();
item0.onValueChange(item0OnChange);
item0x.onValueChange(item0xOnChange);
arr.append('1');
expect(item0OnChange).toHaveBeenCalledTimes(0);
expect(item0xOnChange).toHaveBeenCalledTimes(0);
});
it('should clear and fire change', () => {
const parent = formModel.createField('parent');
const child1 = formModel.createField('parent.child1');
const child1OnChange = vi.fn();
const parentOnChange = vi.fn();
child1.onValueChange(child1OnChange);
parent.onValueChange(parentOnChange);
formModel.setValueIn('parent.child1', 1);
child1.clear();
expect(child1OnChange).toHaveBeenCalledTimes(2);
expect(parentOnChange).toHaveBeenCalledTimes(2);
expect(formEffect).toHaveBeenCalledTimes(2);
});
it('should bubble change in array delete', () => {
const arr = formModel.createFieldArray('arr');
const child1 = formModel.createField('arr.0');
const childOnChange = vi.fn();
const arrOnChange = vi.fn();
child1.onValueChange(childOnChange);
arr.onValueChange(arrOnChange);
formModel.setValueIn('arr.0', 1);
arr.delete(0);
expect(childOnChange).toHaveBeenCalledTimes(2);
expect(arrOnChange).toHaveBeenCalledTimes(2);
// formModel.setValueIn 一次,arr.delete 中 arr 本身触发一次
expect(formEffect).toHaveBeenCalledTimes(2);
});
it('should bubble change in array append', () => {
const arr = formModel.createFieldArray('arr');
const item0 = formModel.createField('arr.0');
const item0OnChange = vi.fn();
const arrOnChange = vi.fn();
item0.onValueChange(item0OnChange);
arr.onValueChange(arrOnChange);
formModel.setValueIn('arr.0', 'a');
arr.append('b');
expect(item0OnChange).toHaveBeenCalledTimes(1);
});
it('should ignore unchanged items when array delete', () => {
const other = formModel.createField('other');
const parent = formModel.createField('parent');
const arr = formModel.createFieldArray('parent.arr');
const item0 = formModel.createField('parent.arr.0');
const item1 = formModel.createField('parent.arr.1');
const item2 = formModel.createField('parent.arr.2');
formModel.setValueIn('parent.arr', [1, 2, 3]);
const item0OnChange = vi.fn();
const item1OnChange = vi.fn();
const item2OnChange = vi.fn();
const arrOnChange = vi.fn();
const parentOnChange = vi.fn();
const otherOnChange = vi.fn();
item0.onValueChange(item0OnChange);
item1.onValueChange(item1OnChange);
item2.onValueChange(item2OnChange);
arr.onValueChange(arrOnChange);
parent.onValueChange(parentOnChange);
other.onValueChange(otherOnChange);
arr.delete(1);
expect(arrOnChange).toHaveBeenCalledTimes(1);
expect(parentOnChange).toHaveBeenCalledTimes(1);
expect(item0OnChange).not.toHaveBeenCalled();
expect(item1OnChange).toHaveBeenCalledTimes(1);
expect(item2OnChange).toHaveBeenCalledTimes(1);
expect(otherOnChange).not.toHaveBeenCalled();
});
});
describe('dispose', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('should correctly cleanup when field dispose', () => {
const parent = formModel.createField('parent');
const child1 = formModel.createField('parent.child1');
child1.state.errors = { 'parent.child1': 'errors' } as unknown as Errors;
child1.bubbleState();
expect(formModel.state.errors?.['parent.child1']).toEqual('errors');
expect(parent.state.errors?.['parent.child1']).toEqual('errors');
parent.dispose();
// Ref 'dispose' method in field-model.ts
// 1. expect state has been cleared
// expect(child1.state.errors).toBeUndefined();
// expect(parent.state.errors?.['parent.child1']).toBeUndefined();
// 2. expect field model has been cleared
expect(formModel.fieldMap.get('parent')).toBeUndefined();
expect(formModel.fieldMap.get('parent.child1')).toBeUndefined();
});
});
});
@@ -0,0 +1,309 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { mapValues } from 'lodash-es';
import { ValidateTrigger } from '@/types';
import { FormModel } from '@/core/form-model';
describe('FormModel', () => {
let formModel = new FormModel();
describe('validate trigger', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('do not validate when value change if validateTrigger is onBlur', async () => {
formModel.init({ validateTrigger: ValidateTrigger.onBlur });
const field = formModel.createField('x');
field.originalValidate = vi.fn();
vi.spyOn(field, 'originalValidate');
field.value = 'some value';
expect(field.originalValidate).not.toHaveBeenCalledOnce();
});
describe('delete field', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('validate onChange', async () => {
formModel.init({ initialValues: { parent: { child1: 1 } } });
formModel.createField('parent');
formModel.createField('parent.child1');
expect(formModel.values.parent?.child1).toBe(1);
formModel.deleteField('parent');
expect(formModel.values.parent?.child1).toBeUndefined();
expect(formModel.getField('parent')).toBeUndefined();
expect(formModel.getField('parent.child1')).toBeUndefined();
});
});
});
describe('FormModel.validate', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
});
it('should run validate on all matched names', async () => {
formModel.init({
validate: {
'a.b.*': () => 'error',
},
});
const bField = formModel.createField('a.b');
const xField = formModel.createField('a.b.x');
formModel.setValueIn('a.b', { x: 1, y: 2 });
const results = await formModel.validate();
// 1. assert validate has been executed correctly
expect(results.length).toEqual(2);
expect(results[0].message).toEqual('error');
expect(results[0].name).toEqual('a.b.x');
expect(results[1].message).toEqual('error');
expect(results[1].name).toEqual('a.b.y');
// 2. assert form state has been set correctly
expect(formModel.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
// 3. assert field state has been set correctly
expect(xField.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
// 4. assert field state has been bubbled to its parent
expect(bField.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
});
it('should run validate if multiple patterns match', async () => {
const mockValidate1 = vi.fn();
const mockValidate2 = vi.fn();
formModel.init({
validate: {
'a.b.*': mockValidate1,
'a.b.x': mockValidate2,
},
});
const bField = formModel.createField('a.b');
const xField = formModel.createField('a.b.x');
formModel.setValueIn('a.b', { x: 1, y: 2 });
formModel.validate();
expect(mockValidate1).toHaveBeenCalledTimes(2);
expect(mockValidate2).toHaveBeenCalledTimes(1);
});
it('should run validate correctly if multiple patterns match but multiple layer empty value exist', async () => {
const mockValidate1 = vi.fn();
const mockValidate2 = vi.fn();
formModel.init({
validate: {
'a.*.x': mockValidate1,
'a.b.x': mockValidate2,
},
});
const bField = formModel.createField('a.b');
const xField = formModel.createField('a.b.x');
formModel.setValueIn('a', {});
formModel.validate();
expect(mockValidate1).toHaveBeenCalledTimes(0);
expect(mockValidate2).toHaveBeenCalledTimes(1);
});
it('should correctly set form errors state when field does not exist', async () => {
formModel.init({
validate: {
'a.b.*': () => 'error',
},
});
formModel.setValueIn('a.b', { x: 1, y: 2 });
await formModel.validate();
expect(formModel.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
});
it('should set form and field state correctly when run validate twice', async () => {
formModel.init({
validate: {
'a.b.*': ({ value }) => (typeof value === 'string' ? undefined : 'error'),
},
});
const bField = formModel.createField('a.b');
const xField = formModel.createField('a.b.x');
formModel.setValueIn('a.b', { x: 1, y: 2 });
let results = await formModel.validate();
// both x y is string, so 2 errors
expect(results.length).toEqual(2);
expect(formModel.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
expect(formModel.state?.errors?.['a.b.y']?.[0].message).toEqual('error');
expect(xField.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
expect(bField.state?.errors?.['a.b.x']?.[0].message).toEqual('error');
formModel.setValueIn('a.b', { x: '1', y: '2' });
results = await formModel.validate();
expect(results.length).toEqual(0);
expect(formModel.state?.errors?.['a.b.x']).toEqual([]);
expect(formModel.state?.errors?.['a.b.y']).toEqual([]);
});
it('validate as dynamic function', async () => {
formModel.init({
initialValues: { a: 3, b: 'str' },
validate: (v, ctx) => {
expect(ctx).toEqual('context');
return mapValues(v, (value) => {
if (typeof value === 'string') {
return () => 'string error';
}
return () => 'num error';
});
},
context: 'context',
});
const fieldResult = await formModel.validateIn('a');
expect(fieldResult).toEqual(['num error']);
const results = await formModel.validate();
expect(results).toEqual([
{ name: 'a', message: 'num error', level: 'error' },
{ name: 'b', message: 'string error', level: 'error' },
]);
});
});
describe('FormModel set/get values', () => {
beforeEach(() => {
formModel.dispose();
formModel = new FormModel();
vi.spyOn(formModel.onFormValuesInitEmitter, 'fire');
vi.spyOn(formModel.onFormValuesChangeEmitter, 'fire');
vi.spyOn(formModel.onFormValuesUpdatedEmitter, 'fire');
});
it('should set value for root path', () => {
formModel.init({
initialValues: {
a: 1,
},
});
formModel.values = { a: 2 };
expect(formModel.values).toEqual({ a: 2 });
});
it('should set initialValues and fire init and updated events', async () => {
formModel.init({
initialValues: {
a: 1,
},
});
expect(formModel.values).toEqual({ a: 1 });
expect(formModel.onFormValuesInitEmitter.fire).toHaveBeenCalledWith({
values: {
a: 1,
},
name: '',
});
expect(formModel.onFormValuesUpdatedEmitter.fire).toHaveBeenCalledWith({
values: {
a: 1,
},
name: '',
});
});
it('should set initialValues in certain path and fire change', async () => {
formModel.init({
initialValues: {
a: 1,
},
});
formModel.setInitValueIn('b', 2);
expect(formModel.values).toEqual({ a: 1, b: 2 });
expect(formModel.onFormValuesInitEmitter.fire).toHaveBeenCalledWith({
values: {
a: 1,
b: 2,
},
prevValues: {
a: 1,
},
name: 'b',
});
expect(formModel.onFormValuesUpdatedEmitter.fire).toHaveBeenCalledWith({
values: {
a: 1,
b: 2,
},
prevValues: {
a: 1,
},
name: 'b',
});
});
it('should not set initialValues in certain path if value exists', async () => {
formModel.init({
initialValues: {
a: 1,
},
});
formModel.setInitValueIn('a', 2);
expect(formModel.values).toEqual({ a: 1 });
// 仅在初始化时调用一次,setInitValueIn 没有调用
expect(formModel.onFormValuesInitEmitter.fire).toHaveBeenCalledTimes(1);
expect(formModel.onFormValuesUpdatedEmitter.fire).toHaveBeenCalledTimes(1);
});
it('should set values in certain path and fire change and updated events', async () => {
formModel.init({
initialValues: {
a: 1,
},
});
formModel.setValueIn('a', 2);
expect(formModel.values).toEqual({ a: 2 });
// 仅在初始化时调用一次,setInitValueIn 没有调用
expect(formModel.onFormValuesChangeEmitter.fire).toHaveBeenCalledTimes(1);
// 初始化一次,变更值一次,所以是两次
expect(formModel.onFormValuesUpdatedEmitter.fire).toHaveBeenCalledTimes(2);
expect(formModel.onFormValuesChangeEmitter.fire).toHaveBeenCalledWith({
values: {
a: 2,
},
prevValues: {
a: 1,
},
name: 'a',
});
expect(formModel.onFormValuesUpdatedEmitter.fire).toHaveBeenCalledWith({
values: {
a: 2,
},
prevValues: {
a: 1,
},
name: 'a',
});
});
});
});
@@ -0,0 +1,456 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
// test src/glob.ts
import { describe, expect, it } from 'vitest';
import { Glob } from '../src/utils/glob';
describe('glob', () => {
describe('isMatch', () => {
it('* at the end', () => {
expect(Glob.isMatch('a.b.*', 'a.b.c')).toBe(true);
expect(Glob.isMatch('a.b.*', 'a.k.c')).toBe(false);
});
it('* at the start', () => {
expect(Glob.isMatch('*.b.c', 'a.b.c')).toBe(true);
expect(Glob.isMatch('*.b.c', 'a.b.x')).toBe(false);
});
it('multiple *', () => {
expect(Glob.isMatch('*.b.*', 'a.b.c')).toBe(true);
expect(Glob.isMatch('a.b.*', 'a.k.c')).toBe(false);
});
it('no *', () => {
expect(Glob.isMatch('a.b.c', 'a.b.c')).toBe(true);
});
it('length not match', () => {
expect(Glob.isMatch('a.b.*', 'a.b.c.c')).toBe(false);
});
});
describe('isMatchOrParent', () => {
it('* at the end', () => {
expect(Glob.isMatchOrParent('a.b.*', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('a.b.*', 'a.k.c')).toBe(false);
});
it('* at the start', () => {
expect(Glob.isMatchOrParent('*.b.c', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('*.b.c', 'a.b.x')).toBe(false);
expect(Glob.isMatchOrParent('*.b', 'a.b.x')).toBe(true);
});
it('multiple *', () => {
expect(Glob.isMatchOrParent('*.b.*', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('*.b.*', 'a.k.c')).toBe(false);
});
it('no *', () => {
expect(Glob.isMatchOrParent('a.b.c', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('a.b', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('a', 'a.b.c')).toBe(true);
expect(Glob.isMatchOrParent('', 'a.b.c.')).toBe(true);
});
it('length not match', () => {
expect(Glob.isMatchOrParent('a.b.*', 'a.b.c.c')).toBe(true);
expect(Glob.isMatchOrParent('a.b.c.d', 'a.b.c.')).toBe(false);
});
});
describe('getParentPathByPattern', () => {
it('should get parent path correctly', () => {
expect(Glob.getParentPathByPattern('a.b.*', 'a.b.c')).toBe('a.b.c');
expect(Glob.getParentPathByPattern('a.b.*', 'a.b.c.d')).toBe('a.b.c');
expect(Glob.getParentPathByPattern('a.b', 'a.b.c.d')).toBe('a.b');
expect(Glob.getParentPathByPattern('a.*.c', 'a.b.c.d')).toBe('a.b.c');
});
});
describe('findMatchPaths', () => {
it('return original path array if no *', () => {
const obj = { a: { b: { c: 1 } } };
expect(Glob.findMatchPaths(obj, 'a.b.c')).toEqual(['a.b.c']);
});
it('object: when * is in middle of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPaths(obj, 'a.*.c')).toEqual(['a.b.c']);
});
it('object:when * is at the end of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPaths(obj, 'a.*')).toEqual(['a.b']);
});
// 暂时不支持该场景,见glob.ts 中 143行说明
it('object: * 后面数据异构', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPaths(obj, '*.y')).toEqual(['x.y']);
});
it('object:when * is at the start and end of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPaths(obj, '*.y.*')).toEqual(['x.y.z']);
});
it('array: when * is at the end of the path', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
],
};
expect(Glob.findMatchPaths(obj, 'arr.*')).toEqual(['arr.0', 'arr.1']);
});
it('array: when * is at the start of the path', () => {
const arr = [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
];
expect(Glob.findMatchPaths(arr, '*')).toEqual(['0', '1']);
});
it('array: when * is in the middle of the path', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
],
};
expect(Glob.findMatchPaths(obj, 'arr.*.y')).toEqual(['arr.0.y', 'arr.1.y']);
});
it('array in array: when double * ', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: ['1', '2'],
},
],
};
expect(Glob.findMatchPaths(obj, 'arr.*.y.*')).toEqual(['arr.0.y.0', 'arr.0.y.1']);
});
it('array in object: when double * ', () => {
const obj = {
x: 100,
y: {
arr: [1, 2],
},
};
expect(Glob.findMatchPaths(obj, 'y.*.*')).toEqual(['y.arr.0', 'y.arr.1']);
});
it('array in object: when double * start ', () => {
const obj = {
x: 100,
y: {
arr: [{ a: 1, b: 2 }],
},
};
expect(Glob.findMatchPaths(obj, '*.arr.*')).toEqual(['y.arr.0']);
});
it('when value after * is empty string ', () => {
const obj = {
$$input_decorator$$: {
inputParameters: [{ name: '', input: 2 }],
},
};
expect(Glob.findMatchPaths(obj, '$$input_decorator$$.inputParameters.*.name')).toEqual([
'$$input_decorator$$.inputParameters.0.name',
]);
});
it('when value after * is undefined ', () => {
const obj = {
x: {
arr: [{ name: undefined, input: 2 }],
},
};
expect(Glob.findMatchPaths(obj, 'x.arr.*.name')).toEqual(['x.arr.0.name']);
});
it('when value not directly after * is undefined ', () => {
const obj = {
x: {
arr: [{ name: { a: undefined }, input: 2 }],
},
};
expect(Glob.findMatchPaths(obj, 'x.arr.*.name.a')).toEqual(['x.arr.0.name.a']);
});
});
describe('splitPattern', () => {
it('should splict pattern correctly', () => {
expect(Glob.splitPattern('a.b.*.c.*.d')).toEqual(['a.b', '*', 'c', '*', 'd']);
expect(Glob.splitPattern('a.b.*.c.*')).toEqual(['a.b', '*', 'c', '*']);
expect(Glob.splitPattern('a.b.*.*.*.d')).toEqual(['a.b', '*', '*', '*', 'd']);
expect(Glob.splitPattern('*.*.c.*.d')).toEqual(['*', '*', 'c', '*', 'd']);
});
});
describe('getSubPaths', () => {
it('should get sub paths for valid object', () => {
const obj = {
a: {
b: {
x1: {
y1: 1,
},
x2: {
y2: 2,
},
},
},
};
expect(Glob.getSubPaths(['a.b'], obj)).toEqual(['a.b.x1', 'a.b.x2']);
expect(Glob.getSubPaths(['a.b', 'a.b.x1'], obj)).toEqual(['a.b.x1', 'a.b.x2', 'a.b.x1.y1']);
});
it('should get sub paths for array', () => {
const obj = {
a: {
b: {
x1: [1, 2],
},
},
};
expect(Glob.getSubPaths(['a.b.x1'], obj)).toEqual(['a.b.x1.0', 'a.b.x1.1']);
});
it('should get sub paths when root obj is array', () => {
const obj = [
{
x1: [1, 2],
},
{
x2: [1, 2],
},
];
expect(Glob.getSubPaths(['0.x1'], obj)).toEqual(['0.x1.0', '0.x1.1']);
});
it('should return empty array when obj is not object nor array', () => {
expect(Glob.getSubPaths(['x.y'], 1)).toEqual([]);
expect(Glob.getSubPaths(['x.y'], 'x')).toEqual([]);
expect(Glob.getSubPaths(['x.y'], undefined)).toEqual([]);
});
it('should return empty array when obj has no value for given path', () => {
const obj = {
a: {
b: {
x1: [1, 2],
},
},
};
expect(Glob.getSubPaths(['a.b.c'], obj)).toEqual([]);
});
});
describe('findMatchPathsWithEmptyValue', () => {
it('return original path array if no *', () => {
const obj = { a: { b: { c: 1 } } };
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.b.c')).toEqual(['a.b.c']);
});
it('return original path array if no * and value is empty on multiple layers', () => {
const obj = { a: {} };
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.b.c')).toEqual(['a.b.c']);
});
it('return original path array if no * and value is empty on multiple layers', () => {
const obj = { a: { b: {} } };
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.x.y')).toEqual(['a.x.y']);
});
it('return array with original path even if path does not exists, but the original path does not contain * ', () => {
const obj = { a: { b: { c: 1 } } };
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.b.c.d')).toEqual(['a.b.c.d']);
});
it('return original path array if no * and path related value is undefined in object', () => {
const obj = { a: { b: { c: {} } } };
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.b.c.d')).toEqual(['a.b.c.d']);
});
it('object: when * is in middle of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.*.c')).toEqual(['a.b.c']);
});
it('object:when * is at the end of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'a.*')).toEqual(['a.b']);
});
// 暂时不支持该场景,见glob.ts 中 143行说明
it('object: * 后面数据异构', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPathsWithEmptyValue(obj, '*.y')).toEqual(['a.y', 'x.y']);
});
it('object:when * is at the start and end of the path', () => {
const obj = {
a: { b: { c: 1 } },
x: { y: { z: 2 } },
};
expect(Glob.findMatchPathsWithEmptyValue(obj, '*.y.*')).toEqual(['x.y.z']);
});
it('array: when * is at the end of the path', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
],
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'arr.*')).toEqual(['arr.0', 'arr.1']);
});
it('array: when * is at the start of the path', () => {
const arr = [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
];
expect(Glob.findMatchPathsWithEmptyValue(arr, '*')).toEqual(['0', '1']);
});
it('array: when * is in the middle of the path', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: { a: 1, b: 2 },
},
{
x: 10,
y: {
a: 10,
b: 20,
},
},
],
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'arr.*.y')).toEqual(['arr.0.y', 'arr.1.y']);
});
it('array: when data related to path is undefined', () => {
const obj = [{ a: 1 }, { a: 2, b: 3 }];
expect(Glob.findMatchPathsWithEmptyValue(obj, '*.b')).toEqual(['0.b', '1.b']);
});
it('array in array: when double * ', () => {
const obj = {
other: 100,
arr: [
{
x: 1,
y: ['1', '2'],
},
],
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'arr.*.y.*')).toEqual([
'arr.0.y.0',
'arr.0.y.1',
]);
});
it('array in object: when double * ', () => {
const obj = {
x: 100,
y: {
arr: [1, 2],
},
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'y.*.*')).toEqual(['y.arr.0', 'y.arr.1']);
});
it('array in object: when double * start ', () => {
const obj = {
x: 100,
y: {
arr: [{ a: 1, b: 2 }],
},
};
expect(Glob.findMatchPathsWithEmptyValue(obj, '*.arr.*')).toEqual(['y.arr.0']);
});
it('when value after * is empty string ', () => {
const obj = {
$$input_decorator$$: {
inputParameters: [{ name: '', input: 2 }],
},
};
expect(
Glob.findMatchPathsWithEmptyValue(obj, '$$input_decorator$$.inputParameters.*.name')
).toEqual(['$$input_decorator$$.inputParameters.0.name']);
});
it('when value after * is undefined ', () => {
const obj = {
x: {
arr: [{ name: undefined, input: 2 }],
},
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'x.arr.*.name')).toEqual(['x.arr.0.name']);
});
it('when value not directly after * is undefined ', () => {
const obj = {
x: {
arr: [{ name: { a: undefined }, input: 2 }],
},
};
expect(Glob.findMatchPathsWithEmptyValue(obj, 'x.arr.*.name.a')).toEqual(['x.arr.0.name.a']);
});
});
});
@@ -0,0 +1,249 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from 'vitest';
import { getIn, isEmptyArray, isNaN, isPromise, shallowSetIn } from '../src/utils';
describe('object', () => {
describe('isEmptyArray', () => {
it('returns true when an empty array is passed in', () => {
expect(isEmptyArray([])).toBe(true);
});
it('returns false when anything other than empty array is passed in', () => {
expect(isEmptyArray()).toBe(false);
expect(isEmptyArray(null)).toBe(false);
expect(isEmptyArray(123)).toBe(false);
expect(isEmptyArray('abc')).toBe(false);
expect(isEmptyArray({})).toBe(false);
expect(isEmptyArray({ a: 1 })).toBe(false);
expect(isEmptyArray(['abc'])).toBe(false);
});
});
describe('getIn', () => {
const obj = {
a: {
b: 2,
c: false,
d: null,
},
t: true,
s: 'a random string',
};
it('gets a value by array path', () => {
expect(getIn(obj, ['a', 'b'])).toBe(2);
});
it('gets a value by string path', () => {
expect(getIn(obj, 'a.b')).toBe(2);
});
it('return "undefined" if value was not found using given path', () => {
expect(getIn(obj, 'a.z')).toBeUndefined();
});
it('return "undefined" if value was not found using given path and an intermediate value is "false"', () => {
expect(getIn(obj, 'a.c.z')).toBeUndefined();
});
it('return "undefined" if value was not found using given path and an intermediate value is "null"', () => {
expect(getIn(obj, 'a.d.z')).toBeUndefined();
});
it('return "undefined" if value was not found using given path and an intermediate value is "true"', () => {
expect(getIn(obj, 't.z')).toBeUndefined();
});
it('return "undefined" if value was not found using given path and an intermediate value is a string', () => {
expect(getIn(obj, 's.z')).toBeUndefined();
});
});
describe('shallowSetIn', () => {
it('sets flat value', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'flat', 'value');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', flat: 'value' });
});
it('keep the same object if nothing is changed', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'x', 'y');
expect(obj).toBe(newObj);
});
it('keep key shen set undefined', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'x', undefined);
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: undefined });
expect(Object.keys(newObj)).toEqual(['x']);
});
it('sets nested value', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'nested.value', 'nested value');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', nested: { value: 'nested value' } });
});
it('updates nested value', () => {
const obj = { x: 'y', nested: { value: 'a' } };
const newObj = shallowSetIn(obj, 'nested.value', 'b');
expect(obj).toEqual({ x: 'y', nested: { value: 'a' } });
expect(newObj).toEqual({ x: 'y', nested: { value: 'b' } });
});
it('updates deep nested value', () => {
const obj = { x: 'y', twofoldly: { nested: { value: 'a' } } };
const newObj = shallowSetIn(obj, 'twofoldly.nested.value', 'b');
expect(obj.twofoldly.nested === newObj.twofoldly.nested).toEqual(false); // fails, same object still
expect(obj).toEqual({ x: 'y', twofoldly: { nested: { value: 'a' } } }); // fails, it's b here, too
expect(newObj).toEqual({ x: 'y', twofoldly: { nested: { value: 'b' } } }); // works ofc
});
it('shallow clone data along the update path', () => {
const obj = {
x: 'y',
twofoldly: { nested: ['a', { c: 'd' }] },
other: { nestedOther: 'o' },
};
const newObj = shallowSetIn(obj, 'twofoldly.nested.0', 'b');
// All new objects/arrays created along the update path.
expect(obj).not.toBe(newObj);
expect(obj.twofoldly).not.toBe(newObj.twofoldly);
expect(obj.twofoldly.nested).not.toBe(newObj.twofoldly.nested);
// All other objects/arrays copied, not cloned (retain same memory
// location).
expect(obj.other).toBe(newObj.other);
expect(obj.twofoldly.nested[1]).toBe(newObj.twofoldly.nested[1]);
});
it('sets new array', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'nested.0', 'value');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', nested: ['value'] });
});
it('sets new array when item is empty string', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'nested.0', '');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', nested: [''] });
});
it('sets new array when item is empty string', () => {
const obj = {};
const newObj = shallowSetIn(obj, 'nested.0', '');
expect(obj).toEqual({});
expect(newObj).toEqual({ nested: [''] });
});
it('updates nested array value', () => {
const obj = { x: 'y', nested: ['a'] };
const newObj = shallowSetIn(obj, 'nested[0]', 'b');
expect(obj).toEqual({ x: 'y', nested: ['a'] });
expect(newObj).toEqual({ x: 'y', nested: ['b'] });
});
it('adds new item to nested array', () => {
const obj = { x: 'y', nested: ['a'] };
const newObj = shallowSetIn(obj, 'nested.1', 'b');
expect(obj).toEqual({ x: 'y', nested: ['a'] });
expect(newObj).toEqual({ x: 'y', nested: ['a', 'b'] });
});
it('sticks to object with int key when defined', () => {
const obj = { x: 'y', nested: { 0: 'a' } };
const newObj = shallowSetIn(obj, 'nested.0', 'b');
expect(obj).toEqual({ x: 'y', nested: { 0: 'a' } });
expect(newObj).toEqual({ x: 'y', nested: { 0: 'b' } });
});
it('supports bracket path', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'nested[0]', 'value');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', nested: ['value'] });
});
it('supports path containing key of the object', () => {
const obj = { x: 'y' };
const newObj = shallowSetIn(obj, 'a.x.c', 'value');
expect(obj).toEqual({ x: 'y' });
expect(newObj).toEqual({ x: 'y', a: { x: { c: 'value' } } });
});
// This case is not used in form sdk for nowso we comment it.
// it('should keep class inheritance for the top level object', () => {
// class TestClass {
// constructor(public key: string, public setObj?: any) {}
// }
// const obj = new TestClass('value');
// const newObj = shallowSetIn(obj, 'setObj.nested', 'shallowSetInValue');
// expect(obj).toEqual(new TestClass('value'));
// expect(newObj).toEqual({
// key: 'value',
// setObj: { nested: 'shallowSetInValue' },
// });
// expect(obj instanceof TestClass).toEqual(true);
// expect(newObj instanceof TestClass).toEqual(true);
// });
it('can convert primitives to objects before setting', () => {
const obj = { x: [{ y: true }] };
const newObj = shallowSetIn(obj, 'x.0.y.z', true);
expect(obj).toEqual({ x: [{ y: true }] });
expect(newObj).toEqual({ x: [{ y: { z: true } }] });
});
it('set undefined value with unknown key', () => {
const obj = { a: '' };
let newObj = shallowSetIn(obj, 'a', undefined);
newObj = shallowSetIn(newObj, 'b', undefined);
expect(obj).toEqual({ a: '' });
expect(newObj).toEqual({ a: undefined, b: undefined });
});
});
describe('isPromise', () => {
it('verifies that a value is a promise', () => {
const alwaysResolve = (resolve: Function) => resolve();
const promise = new Promise(alwaysResolve);
expect(isPromise(promise)).toEqual(true);
});
it('verifies that a value is not a promise', () => {
const emptyObject = {};
const identity = (i: any) => i;
const foo = 'foo';
const answerToLife = 42;
expect(isPromise(emptyObject)).toEqual(false);
expect(isPromise(identity)).toEqual(false);
expect(isPromise(foo)).toEqual(false);
expect(isPromise(answerToLife)).toEqual(false);
expect(isPromise(undefined)).toEqual(false);
expect(isPromise(null)).toEqual(false);
});
});
describe('isNaN', () => {
it('correctly validate NaN', () => {
expect(isNaN(NaN)).toBe(true);
});
it('correctly validate not NaN', () => {
expect(isNaN(undefined)).toBe(false);
expect(isNaN(1)).toBe(false);
expect(isNaN('')).toBe(false);
expect(isNaN([])).toBe(false);
});
});
});
@@ -0,0 +1,80 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from 'vitest';
import { Path } from '../src/core/path';
describe('path', () => {
it('toString', () => {
expect(new Path('a.b.c').toString()).toEqual('a.b.c');
expect(new Path('a.b[0].c').toString()).toEqual('a.b.0.c');
expect(new Path(['a', 'b', 'c']).toString()).toEqual('a.b.c');
});
it('parent', () => {
expect(new Path('a.b.c').parent!.toString()).toEqual('a.b');
expect(new Path('a.b[0]').parent!.toString()).toEqual('a.b');
expect(new Path('a').parent).toEqual(undefined);
});
it('isChild', () => {
expect(new Path('a.b').isChild('a.b.c')).toEqual(true);
expect(new Path('a.b').isChild('a.b[0]')).toEqual(true);
});
it('concat', () => {
expect(new Path('a').concat('b').toString()).toEqual('a.b');
expect(new Path('a').concat('b.c').toString()).toEqual('a.b.c');
expect(new Path('a').concat(0).toString()).toEqual('a.0');
expect(() => {
new Path('a').concat({} as any);
}).toThrowError(/invalid param type/);
});
it('compareArrayPath', () => {
expect((Path.compareArrayPath(new Path('a.b.0'), new Path('a.b.1')) as number) < 0).toBe(true);
expect((Path.compareArrayPath(new Path('a.b.0'), new Path('a.b.2')) as number) < 0).toBe(true);
expect((Path.compareArrayPath(new Path('a.b.1'), new Path('a.b.0')) as number) < 0).toBe(false);
expect((Path.compareArrayPath(new Path('a.b.0'), new Path('a.b.0')) as number) === 0).toBe(
true
);
expect((Path.compareArrayPath(new Path('a.b.1'), new Path('a.b.0.x')) as number) < 0).toBe(
false
);
expect((Path.compareArrayPath(new Path('a.b.1.y'), new Path('a.b.0.x')) as number) < 0).toBe(
false
);
expect(() => Path.compareArrayPath(new Path('a.1'), new Path('a.b.0'))).toThrowError();
expect(() => Path.compareArrayPath(new Path(''), new Path(''))).toThrowError();
expect(() => Path.compareArrayPath(new Path('a.b.c'), new Path('a.b'))).toThrowError();
});
it('isChildOrGrandChild', () => {
expect(new Path('a.b').isChildOrGrandChild('a.b.c')).toEqual(true);
expect(new Path('a.b').isChildOrGrandChild('a.b[0]')).toEqual(true);
expect(new Path('a.b').isChildOrGrandChild('a.b.1')).toEqual(true);
expect(new Path('a.b').isChildOrGrandChild('a.b')).toEqual(false);
expect(new Path('a.b').isChildOrGrandChild('a')).toEqual(false);
expect(new Path('').isChildOrGrandChild('a')).toEqual(true);
});
it('replaceParent', () => {
expect(new Path('a.b.c.d').replaceParent(new Path('a.b'), new Path('x.y')).toString()).toEqual(
'x.y.c.d'
);
expect(new Path('a.b.0.d').replaceParent(new Path('a.b'), new Path('x.y')).toString()).toEqual(
'x.y.0.d'
);
expect(new Path('0.d').replaceParent(new Path(''), new Path('x.y')).toString()).toEqual(
'x.y.0.d'
);
expect(
new Path('a.b.c').replaceParent(new Path('a.b.c'), new Path('x.y.z')).toString()
).toEqual('x.y.z');
expect(() =>
new Path('a.b.0.d').replaceParent(new Path('a1.b'), new Path('x.y')).toString()
).toThrowError();
expect(() =>
new Path('a.0.d').replaceParent(new Path('a.0.d.e'), new Path('x.y')).toString()
).toThrowError();
});
});
@@ -0,0 +1,202 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { beforeEach, describe, expect, it } from 'vitest';
import { toFieldArray } from '@/core/to-field-array';
import { FormModel } from '@/core/form-model';
import { FieldArrayModel } from '@/core/field-array-model';
describe('toFieldArray', () => {
let formModel: FormModel;
let fieldArrayModel: FieldArrayModel;
beforeEach(() => {
formModel = new FormModel();
formModel.init({});
formModel.createFieldArray('users');
fieldArrayModel = formModel.getField<FieldArrayModel>('users')!;
});
it('should convert FieldArrayModel to FieldArray', () => {
const fieldArray = toFieldArray(fieldArrayModel);
expect(fieldArray).toBeDefined();
expect(fieldArray.name).toBe('users');
expect(fieldArray.value === undefined || Array.isArray(fieldArray.value)).toBe(true);
});
it('should expose key property from model id', () => {
const fieldArray = toFieldArray(fieldArrayModel);
expect(fieldArray.key).toBe(fieldArrayModel.id);
});
it('should expose name property from model path', () => {
const fieldArray = toFieldArray(fieldArrayModel);
expect(fieldArray.name).toBe('users');
expect(fieldArray.name).toBe(fieldArrayModel.path.toString());
});
it('should expose value property from model value', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }];
const fieldArray = toFieldArray(fieldArrayModel);
expect(fieldArray.value).toEqual([{ name: 'Alice' }, { name: 'Bob' }]);
expect(fieldArray.value).toBe(fieldArrayModel.value);
});
it('should update model value via onChange', () => {
const fieldArray = toFieldArray(fieldArrayModel);
const newValue = [{ name: 'Charlie' }];
fieldArray.onChange(newValue);
expect(fieldArrayModel.value).toEqual(newValue);
expect(fieldArray.value).toEqual(newValue);
});
it('should map over array elements correctly', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }];
const fieldArray = toFieldArray(fieldArrayModel);
const mapped = fieldArray.map((field, index) => {
expect(field).toBeDefined();
expect(field.name).toBe(`users.${index}`);
return field.value;
});
expect(mapped).toHaveLength(2);
expect(mapped).toEqual([{ name: 'Alice' }, { name: 'Bob' }]);
});
it('should append new item and return Field', () => {
const fieldArray = toFieldArray(fieldArrayModel);
const newItem = { name: 'Charlie' };
const newField = fieldArray.append(newItem);
expect(newField).toBeDefined();
expect(newField.name).toBe('users.0');
expect(newField.value).toEqual(newItem);
expect(fieldArrayModel.value).toEqual([newItem]);
});
it('should delete item by index', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }];
const fieldArray = toFieldArray(fieldArrayModel);
fieldArray.delete(1);
expect(fieldArrayModel.value).toEqual([{ name: 'Alice' }, { name: 'Charlie' }]);
expect(fieldArray.value).toEqual([{ name: 'Alice' }, { name: 'Charlie' }]);
});
it('should remove item by index (same as delete)', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }];
const fieldArray = toFieldArray(fieldArrayModel);
fieldArray.remove(1);
expect(fieldArrayModel.value).toEqual([{ name: 'Alice' }, { name: 'Charlie' }]);
expect(fieldArray.value).toEqual([{ name: 'Alice' }, { name: 'Charlie' }]);
});
it('should swap items at two indices', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }];
const fieldArray = toFieldArray(fieldArrayModel);
fieldArray.swap(0, 2);
expect(fieldArrayModel.value).toEqual([
{ name: 'Charlie' },
{ name: 'Bob' },
{ name: 'Alice' },
]);
expect(fieldArray.value).toEqual([{ name: 'Charlie' }, { name: 'Bob' }, { name: 'Alice' }]);
});
it('should move item from one index to another', () => {
fieldArrayModel.value = [{ name: 'Alice' }, { name: 'Bob' }, { name: 'Charlie' }];
const fieldArray = toFieldArray(fieldArrayModel);
fieldArray.move(0, 2);
expect(fieldArrayModel.value).toEqual([
{ name: 'Bob' },
{ name: 'Charlie' },
{ name: 'Alice' },
]);
expect(fieldArray.value).toEqual([{ name: 'Bob' }, { name: 'Charlie' }, { name: 'Alice' }]);
});
it('should hide _fieldModel property (non-enumerable)', () => {
const fieldArray = toFieldArray(fieldArrayModel);
// _fieldModel should exist but not be enumerable
expect((fieldArray as any)._fieldModel).toBe(fieldArrayModel);
expect(Object.keys(fieldArray)).not.toContain('_fieldModel');
});
it('should support complex nested operations', () => {
const fieldArray = toFieldArray(fieldArrayModel);
// Append multiple items
fieldArray.append({ name: 'Alice', age: 30 });
fieldArray.append({ name: 'Bob', age: 25 });
fieldArray.append({ name: 'Charlie', age: 35 });
expect(fieldArray.value).toHaveLength(3);
// Map and modify
const names = fieldArray.map((field) => field.value.name);
expect(names).toEqual(['Alice', 'Bob', 'Charlie']);
// Swap
fieldArray.swap(0, 1);
expect(fieldArray.value[0].name).toBe('Bob');
expect(fieldArray.value[1].name).toBe('Alice');
// Remove
fieldArray.remove(2);
expect(fieldArray.value).toHaveLength(2);
// Move
fieldArray.move(1, 0);
expect(fieldArray.value[0].name).toBe('Alice');
expect(fieldArray.value[1].name).toBe('Bob');
});
it('should work with empty array', () => {
const fieldArray = toFieldArray(fieldArrayModel);
// Value might be undefined or empty array initially
expect(fieldArray.value === undefined || Array.isArray(fieldArray.value)).toBe(true);
const mapped = fieldArray.map((field) => field.value);
expect(Array.isArray(mapped)).toBe(true);
expect(mapped.length === 0 || mapped.length > 0).toBe(true);
});
it('should preserve reactivity through getters', () => {
const fieldArray = toFieldArray(fieldArrayModel);
// Initial value might be undefined or empty array
expect(fieldArray.value === undefined || Array.isArray(fieldArray.value)).toBe(true);
// Modify through model
fieldArrayModel.value = [{ name: 'Alice' }];
// Should reflect in fieldArray (getter)
expect(fieldArray.value).toEqual([{ name: 'Alice' }]);
// Modify through fieldArray
fieldArray.onChange([{ name: 'Bob' }]);
// Should reflect in model
expect(fieldArrayModel.value).toEqual([{ name: 'Bob' }]);
});
});
@@ -0,0 +1,331 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import * as React from 'react';
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { ValidateTrigger } from '@/types';
import { toField, toFieldState } from '@/core/to-field';
import { FormModel } from '@/core/form-model';
import { FieldModel } from '@/core/field-model';
describe('toField', () => {
let formModel: FormModel;
let fieldModel: FieldModel;
beforeEach(() => {
formModel = new FormModel();
formModel.init({});
fieldModel = formModel.createField('username') as FieldModel;
});
it('should convert FieldModel to Field', () => {
const field = toField(fieldModel);
expect(field).toBeDefined();
expect(field.name).toBe('username');
expect(field.value).toBeUndefined();
});
it('should expose name property from model', () => {
const field = toField(fieldModel);
expect(field.name).toBe(fieldModel.name);
});
it('should expose value property from model', () => {
fieldModel.value = 'John';
const field = toField(fieldModel);
expect(field.value).toBe('John');
expect(field.value).toBe(fieldModel.value);
});
describe('onChange', () => {
it('should update model value with plain value', () => {
const field = toField(fieldModel);
field.onChange('Alice');
expect(fieldModel.value).toBe('Alice');
expect(field.value).toBe('Alice');
});
it('should handle React change event for input', () => {
const field = toField(fieldModel);
const mockEvent = {
target: {
value: 'Bob',
},
} as React.ChangeEvent<HTMLInputElement>;
field.onChange(mockEvent);
expect(fieldModel.value).toBe('Bob');
});
it('should handle React change event for checkbox (checked)', () => {
const field = toField(fieldModel);
const mockEvent = {
target: {
type: 'checkbox',
checked: true,
value: 'on',
},
} as React.ChangeEvent<HTMLInputElement>;
field.onChange(mockEvent);
expect(fieldModel.value).toBe(true);
});
it('should handle React change event for checkbox (unchecked)', () => {
const field = toField(fieldModel);
const mockEvent = {
target: {
type: 'checkbox',
checked: false,
value: 'on',
},
} as React.ChangeEvent<HTMLInputElement>;
field.onChange(mockEvent);
expect(fieldModel.value).toBe(false);
});
it('should handle numeric value', () => {
const field = toField(fieldModel);
field.onChange(42);
expect(fieldModel.value).toBe(42);
});
it('should handle object value', () => {
const field = toField(fieldModel);
const objValue = { name: 'test', value: 123 };
field.onChange(objValue);
expect(fieldModel.value).toEqual(objValue);
});
it('should handle array value', () => {
const field = toField(fieldModel);
const arrValue = ['a', 'b', 'c'];
field.onChange(arrValue);
expect(fieldModel.value).toEqual(arrValue);
});
});
describe('onBlur', () => {
it('should call validate when validateTrigger is onBlur', () => {
formModel.dispose();
formModel = new FormModel();
formModel.init({ validateTrigger: ValidateTrigger.onBlur });
fieldModel = formModel.createField('username') as FieldModel;
const validateSpy = vi.spyOn(fieldModel, 'validate');
const field = toField(fieldModel);
field.onBlur?.();
expect(validateSpy).toHaveBeenCalled();
});
it('should not trigger validation when validateTrigger is not onBlur', () => {
formModel.dispose();
formModel = new FormModel();
formModel.init({ validateTrigger: ValidateTrigger.onChange });
fieldModel = formModel.createField('username') as FieldModel;
const validateSpy = vi.spyOn(fieldModel, 'validate');
const field = toField(fieldModel);
field.onBlur?.();
expect(validateSpy).not.toHaveBeenCalled();
});
it('should not trigger validation when validateTrigger is onSubmit', () => {
formModel.dispose();
formModel = new FormModel();
formModel.init({ validateTrigger: ValidateTrigger.onSubmit });
fieldModel = formModel.createField('username') as FieldModel;
const validateSpy = vi.spyOn(fieldModel, 'validate');
const field = toField(fieldModel);
field.onBlur?.();
expect(validateSpy).not.toHaveBeenCalled();
});
});
describe('onFocus', () => {
it('should set isTouched to true', () => {
const field = toField(fieldModel);
expect(fieldModel.state.isTouched).toBe(false);
field.onFocus?.();
expect(fieldModel.state.isTouched).toBe(true);
});
it('should set isTouched only once', () => {
const field = toField(fieldModel);
field.onFocus?.();
expect(fieldModel.state.isTouched).toBe(true);
field.onFocus?.();
expect(fieldModel.state.isTouched).toBe(true);
});
});
it('should expose key property (non-enumerable)', () => {
const field = toField(fieldModel);
expect((field as any).key).toBe(fieldModel.id);
expect(Object.keys(field)).not.toContain('key');
});
it('should hide _fieldModel property (non-enumerable)', () => {
const field = toField(fieldModel);
expect((field as any)._fieldModel).toBe(fieldModel);
expect(Object.keys(field)).not.toContain('_fieldModel');
});
it('should preserve reactivity through getters', () => {
const field = toField(fieldModel);
expect(field.name).toBe('username');
expect(field.value).toBeUndefined();
fieldModel.value = 'NewValue';
expect(field.value).toBe('NewValue');
});
});
describe('toFieldState', () => {
let formModel: FormModel;
let fieldModel: FieldModel;
beforeEach(() => {
formModel = new FormModel();
formModel.init({});
fieldModel = formModel.createField('username') as FieldModel;
});
it('should convert FieldModelState to FieldState', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState).toBeDefined();
expect(fieldState.isTouched).toBe(false);
expect(fieldState.isDirty).toBe(false);
expect(fieldState.invalid).toBe(false);
expect(fieldState.isValidating).toBe(false);
});
it('should reflect isTouched state', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.isTouched).toBe(false);
fieldModel.state.isTouched = true;
expect(fieldState.isTouched).toBe(true);
});
it('should reflect isDirty state', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.isDirty).toBe(false);
// Manually set dirty state
fieldModel.state.isDirty = true;
expect(fieldState.isDirty).toBe(true);
});
it('should reflect invalid state', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.invalid).toBe(false);
fieldModel.state.invalid = true;
expect(fieldState.invalid).toBe(true);
});
it('should reflect isValidating state', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.isValidating).toBe(false);
fieldModel.state.isValidating = true;
expect(fieldState.isValidating).toBe(true);
});
it('should return errors as flat array', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.errors).toBeUndefined();
fieldModel.state.errors = {
validate1: ['Error 1', 'Error 2'],
validate2: ['Error 3'],
};
expect(fieldState.errors).toEqual(['Error 1', 'Error 2', 'Error 3']);
});
it('should return warnings as flat array', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.warnings).toBeUndefined();
fieldModel.state.warnings = {
validate1: ['Warning 1', 'Warning 2'],
validate2: ['Warning 3'],
};
expect(fieldState.warnings).toEqual(['Warning 1', 'Warning 2', 'Warning 3']);
});
it('should handle empty errors object', () => {
const fieldState = toFieldState(fieldModel.state);
fieldModel.state.errors = {};
expect(fieldState.errors).toEqual([]);
});
it('should handle empty warnings object', () => {
const fieldState = toFieldState(fieldModel.state);
fieldModel.state.warnings = {};
expect(fieldState.warnings).toEqual([]);
});
it('should preserve reactivity through getters', () => {
const fieldState = toFieldState(fieldModel.state);
expect(fieldState.isTouched).toBe(false);
fieldModel.state.isTouched = true;
expect(fieldState.isTouched).toBe(true);
});
});
@@ -0,0 +1,316 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { beforeEach, describe, expect, it, vi } from 'vitest';
import { toForm, toFormState } from '@/core/to-form';
import { FormModel } from '@/core/form-model';
describe('toForm', () => {
let formModel: FormModel;
beforeEach(() => {
formModel = new FormModel();
formModel.init({
initialValues: {
username: 'John',
email: 'john@example.com',
age: 30,
},
});
});
it('should convert FormModel to Form', () => {
const form = toForm(formModel);
expect(form).toBeDefined();
expect(form.initialValues).toEqual({
username: 'John',
email: 'john@example.com',
age: 30,
});
});
it('should expose initialValues from model', () => {
const form = toForm(formModel);
expect(form.initialValues).toBe(formModel.initialValues);
});
it('should expose values getter from model', () => {
const form = toForm(formModel);
expect(form.values).toEqual({
username: 'John',
email: 'john@example.com',
age: 30,
});
expect(form.values).toEqual(formModel.values);
});
it('should expose values setter to update model', () => {
const form = toForm(formModel);
const newValues = {
username: 'Alice',
email: 'alice@example.com',
age: 25,
};
form.values = newValues;
expect(formModel.values).toEqual(newValues);
expect(form.values).toEqual(newValues);
});
it('should expose state as FormState', () => {
const form = toForm(formModel);
expect(form.state).toBeDefined();
expect(form.state.isTouched).toBe(false);
expect(form.state.isDirty).toBe(false);
expect(form.state.invalid).toBe(false);
expect(form.state.isValidating).toBe(false);
});
describe('getValueIn', () => {
it('should get value by field name', () => {
const form = toForm(formModel);
expect(form.getValueIn('username')).toBe('John');
expect(form.getValueIn('email')).toBe('john@example.com');
expect(form.getValueIn('age')).toBe(30);
});
it('should get nested value by path', () => {
formModel.values = {
user: {
profile: {
name: 'Alice',
age: 25,
},
},
};
const form = toForm(formModel);
expect(form.getValueIn('user.profile.name')).toBe('Alice');
expect(form.getValueIn('user.profile.age')).toBe(25);
});
it('should get array value by index', () => {
formModel.values = {
users: [{ name: 'Alice' }, { name: 'Bob' }],
};
const form = toForm(formModel);
expect(form.getValueIn('users.0.name')).toBe('Alice');
expect(form.getValueIn('users.1.name')).toBe('Bob');
});
it('should return undefined for non-existent path', () => {
const form = toForm(formModel);
expect(form.getValueIn('nonexistent')).toBeUndefined();
});
});
describe('setValueIn', () => {
it('should set value by field name', () => {
const form = toForm(formModel);
form.setValueIn('username', 'Bob');
expect(formModel.values.username).toBe('Bob');
expect(form.values.username).toBe('Bob');
});
it('should set nested value by path', () => {
formModel.values = {
user: {
profile: {
name: 'Alice',
age: 25,
},
},
};
const form = toForm(formModel);
form.setValueIn('user.profile.name', 'Charlie');
expect(formModel.values.user.profile.name).toBe('Charlie');
});
it('should set array value by index', () => {
formModel.values = {
users: [{ name: 'Alice' }, { name: 'Bob' }],
};
const form = toForm(formModel);
form.setValueIn('users.0.name', 'Charlie');
expect(formModel.values.users[0].name).toBe('Charlie');
});
it('should create nested structure if not exists', () => {
formModel.values = {};
const form = toForm(formModel);
form.setValueIn('user.profile.name', 'Alice');
expect(formModel.values.user.profile.name).toBe('Alice');
});
});
describe('validate', () => {
it('should bind model validate method', () => {
const form = toForm(formModel);
expect(form.validate).toBeDefined();
expect(typeof form.validate).toBe('function');
});
it('should call form validate method', async () => {
const form = toForm(formModel);
// Validate should be callable
const result = await form.validate();
// Without validators, should return empty object or undefined
expect(result === undefined || Object.keys(result || {}).length === 0).toBe(true);
});
});
it('should hide _formModel property (non-enumerable)', () => {
const form = toForm(formModel);
expect((form as any)._formModel).toBe(formModel);
expect(Object.keys(form)).not.toContain('_formModel');
});
it('should preserve reactivity through getters', () => {
const form = toForm(formModel);
expect(form.values.username).toBe('John');
formModel.values = { username: 'Alice' };
expect(form.values.username).toBe('Alice');
});
it('should work with empty initialValues', () => {
const emptyFormModel = new FormModel();
emptyFormModel.init({});
const form = toForm(emptyFormModel);
expect(form.initialValues).toBeUndefined();
expect(form.values).toBeUndefined();
});
});
describe('toFormState', () => {
let formModel: FormModel;
beforeEach(() => {
formModel = new FormModel();
formModel.init({
initialValues: {
username: 'John',
email: 'john@example.com',
},
});
});
it('should convert FormModelState to FormState', () => {
const formState = toFormState(formModel.state);
expect(formState).toBeDefined();
expect(formState.isTouched).toBe(false);
expect(formState.isDirty).toBe(false);
expect(formState.invalid).toBe(false);
expect(formState.isValidating).toBe(false);
});
it('should reflect isTouched state', () => {
const formState = toFormState(formModel.state);
expect(formState.isTouched).toBe(false);
formModel.state.isTouched = true;
expect(formState.isTouched).toBe(true);
});
it('should reflect isDirty state', () => {
const formState = toFormState(formModel.state);
expect(formState.isDirty).toBe(false);
// Manually set dirty state
formModel.state.isDirty = true;
expect(formState.isDirty).toBe(true);
});
it('should reflect invalid state', () => {
const formState = toFormState(formModel.state);
expect(formState.invalid).toBe(false);
formModel.state.invalid = true;
expect(formState.invalid).toBe(true);
});
it('should reflect isValidating state', () => {
const formState = toFormState(formModel.state);
expect(formState.isValidating).toBe(false);
formModel.state.isValidating = true;
expect(formState.isValidating).toBe(true);
});
it('should expose errors from model state', () => {
const formState = toFormState(formModel.state);
expect(formState.errors).toBeUndefined();
formModel.state.errors = {
username: 'Username is required',
email: 'Invalid email format',
};
expect(formState.errors).toEqual({
username: 'Username is required',
email: 'Invalid email format',
});
});
it('should expose warnings from model state', () => {
const formState = toFormState(formModel.state);
expect(formState.warnings).toBeUndefined();
formModel.state.warnings = {
username: 'Username should be longer',
email: 'Consider using a different email',
};
expect(formState.warnings).toEqual({
username: 'Username should be longer',
email: 'Consider using a different email',
});
});
it('should preserve reactivity through getters', () => {
const formState = toFormState(formModel.state);
expect(formState.isTouched).toBe(false);
formModel.state.isTouched = true;
expect(formState.isTouched).toBe(true);
});
});
@@ -0,0 +1,204 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from 'vitest';
import { Errors } from '@/types';
import { FieldEventUtils, mergeFeedbacks } from '@/core/utils';
describe('core/utils', () => {
describe('mergeFeedbacks', () => {
it('should merge when some key in source is empty array', () => {
const origin = {
a: ['error'],
b: ['error'],
} as unknown as Errors;
const source = {
a: [],
} as unknown as Errors;
const result = mergeFeedbacks(origin, source);
expect(result).toEqual({
a: [],
b: ['error'],
});
});
it('should merge when some key in source is undefined', () => {
const origin = {
a: ['error'],
b: ['error'],
} as unknown as Errors;
const source = {
a: undefined,
} as unknown as Errors;
const result = mergeFeedbacks(origin, source);
expect(result).toEqual({
a: undefined,
b: ['error'],
});
});
});
describe('FieldEventUtils.shouldTriggerFieldChangeEvent', () => {
it('array append: should not trigger for all array child or grand child', () => {
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-append',
indexes: [0],
},
},
'arr.0',
),
).toBe(false);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-append',
indexes: [0],
},
},
'arr.0.x',
),
).toBe(false);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-append',
indexes: [0],
},
},
'arr',
),
).toBe(true);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'p.arr',
options: {
action: 'array-append',
indexes: [0],
},
},
'p',
),
).toBe(true);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: '',
options: {
action: 'array-append',
indexes: [0],
},
},
'0',
),
).toBe(false);
});
it('array splice: should not trigger for array child or grand child only when index < first spliced index', () => {
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [0],
},
},
'arr.0',
),
).toBe(true);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [0],
},
},
'arr.1',
),
).toBe(true);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [1],
},
},
'arr.0',
),
).toBe(false);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [1, 2],
},
},
'arr.1',
),
).toBe(true);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [4, 5],
},
},
'arr.1',
),
).toBe(false);
expect(
FieldEventUtils.shouldTriggerFieldChangeEvent(
{
values: {},
prevValues: {},
name: 'arr',
options: {
action: 'array-splice',
indexes: [],
},
},
'arr.1',
),
).toBe(true);
});
});
});
@@ -0,0 +1,27 @@
/**
* Copyright (c) 2025 Bytedance Ltd. and/or its affiliates
* SPDX-License-Identifier: MIT
*/
import { describe, expect, it } from 'vitest';
import { hasError } from '../src/utils/validate';
import { FeedbackLevel, FieldError } from '../src/types';
describe('utils/validate', () => {
describe('hasError', () => {
it('should return false when errors is empty', () => {
expect(hasError({ xxx: [] })).toBe(false);
expect(hasError({ xxx: undefined })).toBe(false);
expect(hasError({})).toBe(false);
expect(hasError({ aaa: [], bbb: [] })).toBe(false);
expect(hasError({ aaa: undefined, bbb: [] })).toBe(false);
});
it('should return true when errors is not empty', () => {
const mockError: FieldError = { name: 'xxx', level: FeedbackLevel.Error, message: 'err' };
expect(hasError({ xxx: [mockError] })).toBe(true);
expect(hasError({ aaa: [mockError], bbb: [mockError] })).toBe(true);
expect(hasError({ aaa: undefined, bbb: [mockError] })).toBe(true);
});
});
});