Skip to content

Commit

Permalink
feat: add validate method, add test. Resolve #129
Browse files Browse the repository at this point in the history
  • Loading branch information
Jenesius committed Aug 7, 2023
1 parent 477da96 commit f14a56e
Show file tree
Hide file tree
Showing 3 changed files with 69 additions and 1 deletion.
2 changes: 1 addition & 1 deletion src/classes/DependencyQueue.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ import FormError from "./FormError";
* При добавлении элемента устанавливается значение родителя, а также добавление в массив.
* При удалении значение родителя сбрасывается.
* */
export default class DependencyQueue<T extends DependencyItem> {
export default class DependencyQueue<T extends (DependencyItem & Record<string, any>)> {
private array: T[] = []
private readonly form: Form

Expand Down
14 changes: 14 additions & 0 deletions src/classes/Form.ts
Original file line number Diff line number Diff line change
Expand Up @@ -661,6 +661,20 @@ export default class Form extends EventEmitter implements FormDependence {

return !this.#availabilities[nearestName];
}

/**
* @description Method using for validate form and all child items.
* */
validate(): boolean {
const result = this.dependencies.reduce((acc, dep) => {
if (typeof dep.validate === "function") acc = acc && !!dep.validate();
return acc;
}, true);

debug.msg(`Validation ${result ? 'successful' : 'failed'}`);

return result;
}

}

Expand Down
54 changes: 54 additions & 0 deletions tests/units/form/form-validate.spec.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,54 @@
import Form from "../../../src/classes/Form";

describe("Form validate", () => {

test("Should return true if not validate functions was provided.", () => {
const form = new Form();
expect(form.validate()).toBe(true)
})
test("Should return false in first execute if child validate function return false", () => {
const form = new Form();
const child = {
name: "address",
count: -1,
validate() {
return this.count++ >= 0
}
}
form.subscribe(child);
expect(form.validate()).toBe(false);
expect(form.validate()).toBe(true);
})
test("Should be true if all children return true", () => {
const form = new Form();
for(let i = 0; i < 10; i++) {
form.subscribe({
name: `dep-${i}`,
validate() {
return true
}
})
}
expect(form.validate()).toBe(true)
})
test("Child form with children validation items", () => {
const form = new Form();
const child = new Form({
name: "address"
})
form.subscribe(child)
child.subscribe({
name: "city",
index: 0,
validate() {
console.log(this.index > 0)

return this.index++ > 0
}
})

expect(form.validate()).toBe(false)
expect(form.validate()).toBe(true)
})

})

0 comments on commit f14a56e

Please sign in to comment.