@tldraw/validate 4.1.0-next.b6dfe9bccde9 → 4.1.0-next.b73a0d46b63f

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -1,4 +1,5 @@
1
1
  import * as T from '../lib/validation'
2
+ import { ValidationError } from '../lib/validation'
2
3
 
3
4
  describe('validations', () => {
4
5
  it('Returns referentially identical objects', () => {
@@ -119,12 +120,62 @@ describe('validations', () => {
119
120
  })
120
121
 
121
122
  describe('T.refine', () => {
122
- it.todo('Refines a validator.')
123
- it.todo('Produces a type error if the refinement is not of the correct type.')
123
+ it('Refines a validator.', () => {
124
+ const stringToNumber = T.string.refine((str) => parseInt(str, 10))
125
+ const originalEnv = process.env.NODE_ENV
126
+ process.env.NODE_ENV = 'production'
127
+ expect(stringToNumber.validate('42')).toBe(42)
128
+ process.env.NODE_ENV = originalEnv
129
+
130
+ const prefixedString = T.string.refine((str) =>
131
+ str.startsWith('prefix:') ? str : `prefix:${str}`
132
+ )
133
+ process.env.NODE_ENV = 'production'
134
+ expect(prefixedString.validate('test')).toBe('prefix:test')
135
+ expect(prefixedString.validate('prefix:existing')).toBe('prefix:existing')
136
+ process.env.NODE_ENV = originalEnv
137
+ })
138
+
139
+ it('Produces a type error if the refinement is not of the correct type.', () => {
140
+ const stringToNumber = T.string.refine((str) => {
141
+ const num = parseInt(str, 10)
142
+ if (isNaN(num)) {
143
+ throw new ValidationError('Invalid number format')
144
+ }
145
+ return num
146
+ })
147
+
148
+ expect(() => stringToNumber.validate('not-a-number')).toThrowErrorMatchingInlineSnapshot(
149
+ `[ValidationError: At null: Invalid number format]`
150
+ )
151
+ })
124
152
  })
125
153
 
126
154
  describe('T.check', () => {
127
- it.todo('Adds a check to a validator.')
155
+ it('Adds a check to a validator.', () => {
156
+ const evenNumber = T.number.check((value) => {
157
+ if (value % 2 !== 0) {
158
+ throw new ValidationError('Expected even number')
159
+ }
160
+ })
161
+
162
+ expect(evenNumber.validate(4)).toBe(4)
163
+ expect(evenNumber.validate(0)).toBe(0)
164
+ expect(() => evenNumber.validate(3)).toThrowErrorMatchingInlineSnapshot(
165
+ `[ValidationError: At null: Expected even number]`
166
+ )
167
+
168
+ const namedCheck = T.number.check('positive', (value) => {
169
+ if (value <= 0) {
170
+ throw new ValidationError('Must be positive')
171
+ }
172
+ })
173
+
174
+ expect(namedCheck.validate(5)).toBe(5)
175
+ expect(() => namedCheck.validate(-1)).toThrowErrorMatchingInlineSnapshot(
176
+ `[ValidationError: At (check positive): Must be positive]`
177
+ )
178
+ })
128
179
  })
129
180
 
130
181
  describe('T.indexKey', () => {