|
4 | 4 | *--------------------------------------------------------------------------------------------*/ |
5 | 5 |
|
6 | 6 | import { describe, expect, it } from 'vitest'; |
7 | | -import { vBoolean, vNumber, vObj, vRequired, vString } from '../../common/validator'; |
| 7 | +import { vBoolean, vNull, vNumber, vObj, vRequired, vString, vUnion } from '../../common/validator'; |
8 | 8 |
|
9 | 9 | describe('vRequired', () => { |
10 | 10 | it('should mark a field as required', () => { |
@@ -160,3 +160,48 @@ describe('vRequired', () => { |
160 | 160 | expect(result2.error).toBeDefined(); |
161 | 161 | }); |
162 | 162 | }); |
| 163 | + |
| 164 | +describe('vNull', () => { |
| 165 | + it('should validate null values', () => { |
| 166 | + const validator = vNull(); |
| 167 | + |
| 168 | + const result = validator.validate(null); |
| 169 | + expect(result.error).toBeUndefined(); |
| 170 | + expect(result.content).toBe(null); |
| 171 | + }); |
| 172 | + |
| 173 | + it('should reject non-null values', () => { |
| 174 | + const validator = vNull(); |
| 175 | + |
| 176 | + const result1 = validator.validate(undefined); |
| 177 | + expect(result1.error).toBeDefined(); |
| 178 | + expect(result1.error?.message).toContain("Expected null"); |
| 179 | + |
| 180 | + const result2 = validator.validate("string"); |
| 181 | + expect(result2.error).toBeDefined(); |
| 182 | + |
| 183 | + const result3 = validator.validate(0); |
| 184 | + expect(result3.error).toBeDefined(); |
| 185 | + }); |
| 186 | + |
| 187 | + it('should work with vUnion for nullable fields', () => { |
| 188 | + const validator = vObj({ |
| 189 | + name: vRequired(vUnion(vString(), vNull())), |
| 190 | + age: vNumber(), |
| 191 | + }); |
| 192 | + |
| 193 | + // null value should be valid |
| 194 | + const result1 = validator.validate({ name: null, age: 25 }); |
| 195 | + expect(result1.error).toBeUndefined(); |
| 196 | + expect(result1.content).toEqual({ name: null, age: 25 }); |
| 197 | + |
| 198 | + // string value should also be valid |
| 199 | + const result2 = validator.validate({ name: "John", age: 25 }); |
| 200 | + expect(result2.error).toBeUndefined(); |
| 201 | + expect(result2.content).toEqual({ name: "John", age: 25 }); |
| 202 | + |
| 203 | + // other types should fail |
| 204 | + const result3 = validator.validate({ name: 123, age: 25 }); |
| 205 | + expect(result3.error).toBeDefined(); |
| 206 | + }); |
| 207 | +}); |
0 commit comments