vest 3.2.8-dev-6d7c74 → 3.2.8

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.
Files changed (80) hide show
  1. package/README.md +115 -0
  2. package/any.d.ts +3 -0
  3. package/any.js +1 -0
  4. package/classNames.d.ts +14 -0
  5. package/classNames.js +1 -0
  6. package/docs/.nojekyll +0 -0
  7. package/docs/README.md +115 -0
  8. package/docs/_assets/favicon.ico +0 -0
  9. package/docs/_assets/vest-logo.png +0 -0
  10. package/docs/_sidebar.md +19 -0
  11. package/docs/_sidebar.md.bak +14 -0
  12. package/docs/cross_field_validations.md +79 -0
  13. package/docs/enforce.md +18 -0
  14. package/docs/enforce.md.bak +13 -0
  15. package/docs/exclusion.md +128 -0
  16. package/docs/getting_started.md +79 -0
  17. package/docs/group.md +142 -0
  18. package/docs/index.html +41 -0
  19. package/docs/migration.md +107 -0
  20. package/docs/n4s/compound.md +187 -0
  21. package/docs/n4s/custom.md +52 -0
  22. package/docs/n4s/external.md +54 -0
  23. package/docs/n4s/rules.md +1282 -0
  24. package/docs/n4s/template.md +53 -0
  25. package/docs/node.md +43 -0
  26. package/docs/optional.md +51 -0
  27. package/docs/result.md +238 -0
  28. package/docs/state.md +102 -0
  29. package/docs/test.md +172 -0
  30. package/docs/utilities.md +105 -0
  31. package/docs/warn.md +82 -0
  32. package/enforce.d.ts +230 -0
  33. package/esm/package.json +1 -0
  34. package/esm/vest.es.development.js +2493 -0
  35. package/esm/vest.es.production.js +2490 -0
  36. package/esm/vest.es.production.min.js +1 -0
  37. package/package.json +65 -12
  38. package/promisify.d.ts +7 -0
  39. package/{dist/umd/promisify.production.js → promisify.js} +1 -1
  40. package/schema.d.ts +26 -0
  41. package/schema.js +1 -0
  42. package/vest.cjs.development.js +2494 -0
  43. package/vest.cjs.production.js +2491 -0
  44. package/vest.cjs.production.min.js +1 -0
  45. package/vest.d.ts +254 -0
  46. package/vest.js +7 -0
  47. package/vest.umd.development.js +2711 -0
  48. package/vest.umd.production.js +2708 -0
  49. package/vest.umd.production.min.js +1 -0
  50. package/vestResult.d.ts +105 -0
  51. package/CHANGELOG.md +0 -94
  52. package/LICENSE +0 -21
  53. package/classnames/index.js +0 -7
  54. package/classnames/package.json +0 -1
  55. package/dist/cjs/classnames.development.js +0 -67
  56. package/dist/cjs/classnames.production.js +0 -1
  57. package/dist/cjs/promisify.development.js +0 -20
  58. package/dist/cjs/promisify.production.js +0 -1
  59. package/dist/cjs/vest.development.js +0 -1616
  60. package/dist/cjs/vest.production.js +0 -1
  61. package/dist/es/classnames.development.js +0 -65
  62. package/dist/es/classnames.production.js +0 -1
  63. package/dist/es/promisify.development.js +0 -18
  64. package/dist/es/promisify.production.js +0 -1
  65. package/dist/es/vest.development.js +0 -1604
  66. package/dist/es/vest.production.js +0 -1
  67. package/dist/umd/classnames.development.js +0 -73
  68. package/dist/umd/classnames.production.js +0 -1
  69. package/dist/umd/promisify.development.js +0 -26
  70. package/dist/umd/vest.development.js +0 -1622
  71. package/dist/umd/vest.production.js +0 -1
  72. package/index.js +0 -7
  73. package/promisify/index.js +0 -7
  74. package/promisify/package.json +0 -1
  75. package/types/classnames.d.ts +0 -71
  76. package/types/classnames.d.ts.map +0 -1
  77. package/types/promisify.d.ts +0 -61
  78. package/types/promisify.d.ts.map +0 -1
  79. package/types/vest.d.ts +0 -271
  80. package/types/vest.d.ts.map +0 -1
@@ -0,0 +1,53 @@
1
+ # Enforce templates
2
+
3
+ When you have common patterns you need to repeat in multiple places, it might be simpler to store them as templates.
4
+
5
+ For example, let's assume that all across our systems, a username must be a non-numeric string that's longer than 3 characters.
6
+
7
+ ```js
8
+ enforce(username).isString().isNotEmpty().isNotNumeric().longerThan(3);
9
+ ```
10
+
11
+ This is quite simple to understand, but if you have to keep it up-to-date in every place you validate a username, you may eventually have inconsistent or out-of-date validations.
12
+
13
+ It can be beneficial in that case to keep this enforcement as a template for later use:
14
+
15
+ ```js
16
+ const Username = enforce.template(
17
+ enforce.isString().isNotEmpty().isNotNumeric().longerThan(3)
18
+ );
19
+ ```
20
+
21
+ And then, anywhere else you can use your new `Username` template to validate usernames all across your application:
22
+
23
+ ```js
24
+ Username('myUsername'); // passes
25
+ Username('1234'); // throws
26
+ Username('ab'); // throws
27
+ ```
28
+
29
+ You can also use templates inside other compound rules, such as `shape`, `isArrayOf` ,`anyOf` or `allOf`.
30
+
31
+ ```js
32
+ enforce({
33
+ username: 'someusername',
34
+ }).shape({ username: Username });
35
+
36
+ enforce(['user1', 'user2']).isArrayOf(Username);
37
+ ```
38
+
39
+ Templates can also be nested and composited:
40
+
41
+ ```js
42
+ const RequiredField = enforce.template(enforce.isNotEmpty());
43
+ const NumericString = enforce.template(enforce.isNumeric().isString());
44
+
45
+ const EvenNumeric = enforce.template(
46
+ RequiredField,
47
+ NumericString,
48
+ enforce.isEven()
49
+ );
50
+
51
+ EvenNumeric('10'); // pases
52
+ EvenNumeric('1'); // throws
53
+ ```
package/docs/node.md ADDED
@@ -0,0 +1,43 @@
1
+ # Using Vest in node
2
+
3
+ Using Vest in node is mostly the same as it is in the browser, but you should consider your runtime.
4
+
5
+ ## Validation state
6
+
7
+ When running your validations in your api, you usually want to have stateless validations to prevent leakage between requests.
8
+
9
+ Read more about [Vest's state](./state).
10
+
11
+ ## require vs import
12
+
13
+ Depending on your node version and the module system you support you can use different syntax to include Vest.
14
+
15
+ ### Most compatible: commonjs
16
+
17
+ To be on the safe side and compatible with all node versions, use a `require` statement.
18
+
19
+ ```js
20
+ const vest = require('vest');
21
+ const { test, enforce } = vest;
22
+ ```
23
+
24
+ Depending on your node version and used flag, your require statement might default to Vest's minified es5 bundle. If you want to make sure to use the non-minified es6 commonjs bundle, you can require it directly.
25
+
26
+ ```js
27
+ const vest = require('vest/vest.cjs.production.js');
28
+ const { test, enforce } = vest;
29
+ ```
30
+
31
+ ### Node 14
32
+
33
+ With node 14's support of [package entry points](https://nodejs.org/api/esm.html#esm_package_entry_points), node should be able to detect on its own which import style you use and load the correct bundle.
34
+
35
+ Both of the following should work:
36
+
37
+ ```js
38
+ import { create, test } from 'vest';
39
+ ```
40
+
41
+ ```js
42
+ const vest = require('vest');
43
+ ```
@@ -0,0 +1,51 @@
1
+ # optional fields
2
+
3
+ > Since 3.2.0
4
+
5
+ It is possible to mark fields in your suite as optional fields. This means that when they are skipped, the suite may still be considered as valid.
6
+ All fields are by default required, unless explicitly marked as optional using the `optional` function.
7
+
8
+ ## Usage
9
+
10
+ `optional` can take a field name as its argument, or an array of field names.
11
+
12
+ ```js
13
+ import { create, optional, only, test, enforce } from 'vest';
14
+
15
+ const suite = create('RegisterPet', (data, currentField) => {
16
+ only(currentField); // only validate this specified field
17
+
18
+ optional(['pet_color', 'pet_age']);
19
+ /** Equivalent to:
20
+ * optional('pet_color')
21
+ * optional('pet_age')
22
+ **/
23
+
24
+ test('pet_name', 'Pet Name is required', () => {
25
+ enforce(data.name).isNotEmpty();
26
+ });
27
+
28
+ test('pet_color', 'If provided, pet color must be a string', () => {
29
+ enforce(data.color).isString();
30
+ });
31
+
32
+ test('pet_age', 'If provided, pet age must be numeric', () => {
33
+ enforce(data.age).isNumeric();
34
+ });
35
+ });
36
+
37
+ suite({ name: 'Indie' }, /* -> only validate pet_name */ 'pet_name').isValid();
38
+ // ✅ Since pet_color and pet_age are optional, the suite may still be valid
39
+
40
+ suite({ age: 'Five' }, /* -> only validate pet_age */ 'pet_age').isValid();
41
+ // 🚨 When erroring, optional fields still make the suite invalid
42
+ ```
43
+
44
+ ## Difference between `optional` and `warn`
45
+
46
+ While on its surface, optional might seem similar to warn, they are quite different.
47
+ optional, like "only" and "skip" is set on the field level, which means that when set - all tests of an optional field are considered optional. Warn, on the other hand - is set on the test level, so the only tests affected are the tests that have the "warn" option applied within them.
48
+
49
+ Another distinction is that warning tests cannot set the suite to be invalid.
50
+
51
+ There may be rare occasions in which you have an optional and a warning only field, in which case, you may combine the two.
package/docs/result.md ADDED
@@ -0,0 +1,238 @@
1
+ # Vest's result object
2
+
3
+ Vest validations return a results object that holds all the information regarding the current run, and methods to easily interact with the data.
4
+
5
+ A result object would look somewhat like this:
6
+
7
+ ```js
8
+ {
9
+ 'name': 'formName', // The name of the validation suite
10
+ 'errorCount': Number 0, // Overall count of errors in the suite
11
+ 'warnCount': Number 0, // Overall count of warnings in the suite
12
+ 'testCount': Number 0, // Overall test count for the suite (passing, failing and warning)
13
+ 'tests': Object { // An object containing all non-skipped tests
14
+ 'fieldName': Object { // Name of each field
15
+ 'errorCount': Number 0, // Error count per field
16
+ 'errors': Array [], // Array of error messages fer field (may be undefined)
17
+ 'warnings': Array [], // Array of warning messages fer field (may be undefined)
18
+ 'warnCount': Number 0, // Warning count per field
19
+ 'testCount': Number 0, // Overall test count for the field (passing, failing and warning)
20
+ },
21
+ 'groups': Object { // An object containing groups declared in the suite
22
+ 'fieldName': Object { // Subset of res.tests[fieldName] only containing tests
23
+ /*... */ // only containing tests that ran within the group
24
+ }
25
+ }
26
+ }
27
+ }
28
+ ```
29
+
30
+ ## Accessing the recent result object with `.get`
31
+
32
+ If you need to access your validation results out of context - for example, from a different UI component or function, you can use `.get()` - a function that exists as a property of your validation suite.
33
+
34
+ In case your validations did not run yet, `.get` returns an empty validation result object - which can be helpful when trying to access validation result object when rendering the initial UI, or setting it in the initial state of your components.
35
+
36
+ ```js
37
+ const suite = create('my_form', () => {
38
+ /*...*/
39
+ });
40
+
41
+ suite.get(); // -> returns the most recent result object for the current suite
42
+ ```
43
+
44
+ # Result Object Methods:
45
+
46
+ Along with these values, the result object exposes the following methods:
47
+
48
+ ## `isValid` function
49
+
50
+ `isValid` returns whether the validation suite as a whole is valid or not.
51
+
52
+ A suite is considered valid if the following conditions are met:
53
+
54
+ - There are no errors (`hasErrors() === false`) in the suite - warnings are not counted as errors.
55
+ - All non [optional](./optional) fields have passing tests.
56
+ - There are no pending async tests.
57
+
58
+ ```js
59
+ result.isValid();
60
+
61
+ suite.get().isValid();
62
+ ```
63
+
64
+ ?> **Note** when `isValid` equals `false`, it does not necessarily mean that the form is inValid, but that it might not be valid _yet_. For example, if not all the fields are filled, the form is simply not valid, even though it may not be strictly invalid.
65
+
66
+ ## `hasErrors` and `hasWarnings` functions
67
+
68
+ If you only need to know if a certain field has validation errors or warnings but don't really care which they are, you can use `hasErrors` or `hasWarnings` functions.
69
+
70
+ ```js
71
+ resultObject.hasErrors('username');
72
+ // true
73
+
74
+ resultObject.hasWarnings('password');
75
+ // false
76
+ ```
77
+
78
+ In case you want to know whether the whole suite has errors or warnings (to prevent submit, for example), you can use the same functions, just without specifying a field
79
+
80
+ ```js
81
+ resultObject.hasErrors();
82
+ // true
83
+
84
+ resultObject.hasWarnings();
85
+ // true
86
+ ```
87
+
88
+ ## `hasErrorsByGroup` and `hasWarningsByGroup` functions
89
+
90
+ Similar to `hasErrors` and `hasWarnings`, but returns the result for a specified [group](./group)
91
+
92
+ To get the result for a given field in the group:
93
+
94
+ ```js
95
+ resultObject.hasErrorsByGroup('groupName', 'fieldName');
96
+ // true
97
+
98
+ resultObject.hasWarningsByGroup('groupName', 'fieldName');
99
+ // false
100
+ ```
101
+
102
+ And to get the result for a whole group.
103
+
104
+ ```js
105
+ resultObject.hasErrorsByGroup('groupName');
106
+ // true
107
+
108
+ resultObject.hasWarningsByGroup('groupName');
109
+ // true
110
+ ```
111
+
112
+ [Read more about groups](./group)
113
+
114
+ ## `getErrors` and `getWarnings` functions
115
+
116
+ These functions return an array of errors for the specified field. If no field specified, it returns an object with all fields as keys and their error arrays as values.
117
+
118
+ ```js
119
+ resultObject.getErrors('username');
120
+ // ['Username is too short', `Username already exists`]
121
+
122
+ resultObject.getWarnings('password');
123
+ // ['Password must contain special characters']
124
+ ```
125
+
126
+ If there are no errors for the field, the function defaults to an empty array:
127
+
128
+ ```js
129
+ resultObject.getErrors('username');
130
+ // []
131
+
132
+ resultObject.getWarnings('username');
133
+ // []
134
+ ```
135
+
136
+ You can also call these functions without a field name, which will return you an array per field:
137
+
138
+ ```js
139
+ resultObject.getErrors();
140
+
141
+ // {
142
+ // username: ['Username is too short', `Username already exists`],
143
+ // password: ['Password must contain special characters']
144
+ // }
145
+ ```
146
+
147
+ !> **NOTE** If you did not specify error messages for your tests, your errors array will be empty as well. In such case you should always rely on `.hasErrors()` instead.
148
+
149
+ ## `getErrorsByGroup` and `getWarningsByGroup` functions
150
+
151
+ Just like get `getErrors` and `getWarnings`, but narrows the result to a specified [group](./group).
152
+
153
+ ```js
154
+ resultObject.getErrorsByGroup('groupName', 'fieldName');
155
+ resultObject.getWarningsByGroup('groupName', 'fieldName');
156
+ resultObject.getErrorsByGroup('groupName'');
157
+ resultObject.getWarningsByGroup('groupName'');
158
+ ```
159
+
160
+ [Read more about groups](./group).
161
+
162
+ ## `.done()`
163
+
164
+ Done is a function that can be chained to your validation suite, and allows invoking callbacks whenever a specific, or all, tests finish their validation - regardless of the validation result.
165
+
166
+ If we specify a field name in our `done` call, vest will not wait for the whole suite to finish before running our callback. It will invoke immediately when all tests with that given name finished running.
167
+
168
+ `.done()` calls can be infinitely chained after one another, and as the validation suite completes - they will all run immediately.
169
+
170
+ `done` takes one or two arguments:
171
+
172
+ | Name | Type | Optional | Description |
173
+ | ----------- | ---------- | -------- | ------------------------------------------------------------------------------------------------------------------------------- |
174
+ | `fieldName` | `String` | Yes | If passed, the current done call will not wait for the whole suite to complete, but instead wait for a certain field to finish. |
175
+ | `callback` | `Function` | No | A callback to be run when either the whole suite or the specified field finished running. |
176
+
177
+ The result object is being passed down to the `done` object as an argument.
178
+
179
+ **Example**
180
+
181
+ In the below example, the `done` callback for `UserName` may run before the whole suite finishes. Only when the rest of the suite finishes, it will call the other two done callbacks that do not have a field name specified.
182
+
183
+ ```js
184
+ import { create, test, enforce } from 'vest';
185
+
186
+ const suite = create('SendEmailForm', data => {
187
+ test(
188
+ 'UserEmail',
189
+ 'Marked as spam address',
190
+ async () => await isKnownSpammer(data.address)
191
+ );
192
+
193
+ test(
194
+ 'UserName',
195
+ 'must not be blacklisted',
196
+ async () => await isBlacklistedUser(data.username)
197
+ );
198
+ });
199
+
200
+ const validationResult = suite(data)
201
+ .done('UserName', res => {
202
+ if (res.hasErrors('UserName')) {
203
+ showUserNameErrors(res.errors);
204
+ }
205
+ })
206
+ .done(output => {
207
+ reportToServer(output);
208
+ })
209
+ .done(output => {
210
+ promptUserQuestionnaire(output);
211
+ });
212
+ ```
213
+
214
+ !> **IMPORTANT** .done calls must not be used conditionally - especially when involving async tests. This might cause unexpected behavior or missed callbacks. Instead, if needed, perform your conditional logic within your callback.
215
+
216
+ ```js
217
+ // 🚨 This might not work as expected when working with async validations
218
+
219
+ if (field === 'username') {
220
+ result.done(() => {
221
+ /*do something*/
222
+ });
223
+ }
224
+ ```
225
+
226
+ ```js
227
+ // ✅ Instead, perform your checks within your done callback
228
+
229
+ result.done(() => {
230
+ if (field === 'username') {
231
+ /*do something*/
232
+ }
233
+ });
234
+ ```
235
+
236
+ ### Read more on:
237
+
238
+ [Optional tests](./optional)
package/docs/state.md ADDED
@@ -0,0 +1,102 @@
1
+ # Understanding Vest's state
2
+
3
+ Vest is designed to help perform validations on user inputs. The nature of user inputs is that they are filled one by one by the user. In order to provide good user experience, the best approach is to validate fields as the user type, or when they leave the field.
4
+
5
+ The difficult part when validating upon user interaction is that we want to only validate the field that the user is currently interacting with, and not the rest of the form. This
6
+ This can be done with Vest's [`only()` hook](./exclusion). That's where the state mechanism is becoming useful.
7
+
8
+ When you have skipped fields in your validation suite, vest will try to see if those skipped fields ran in the previous suite, and merge them into the currently running suite result - so the result object you get will include all the fields that your user interacted with.
9
+
10
+ ## What Vest's state does
11
+
12
+ - _Skipped field merge_
13
+
14
+ As mentioned before - whenever you skip a field, vest will look for it in your previously ran validations and add it to the current result.
15
+
16
+ - _Lagging async `done` callback blocking_
17
+
18
+ In case you have an async test that didn't finish from the previous suite run - and you already ran another async test for the same field - vest will block the [`done()`]('./result#done) callbacks for that field from running for the previous suite result.
19
+
20
+ # Drawbacks when using stateful validations
21
+
22
+ When the validations are stateful, you get the benefit of not having to know which fields have already been validated, or keeping track of their previous results.
23
+
24
+ The drawback of this approach is that when you run the same form in multiple-unrelated contexts, the previous validation state still holds the previous result.
25
+
26
+ Here are a few examples and their solutions:
27
+
28
+ ## Single Page Application - suite result retention
29
+
30
+ This scenario applies for cases when your form is a part of an SPA with client side routing. Let's assume your user successfuly submits the form, navigates outside of the page, and then sometime and then, later in the same session, they navigate back to the form.
31
+
32
+ The form will then have a successful validation state since the previous result is stored in the suite state.
33
+
34
+ ### Solution: Resetting suite state with `.reset();`
35
+
36
+ In some cases, such as form reset, you want to discard of previous validation results. This can be done with `vest.reset()`.
37
+
38
+ `.reset` disables all pending async tests in your suite and empties the state out.
39
+
40
+ ### Usage:
41
+
42
+ `.rese()` Is a property on your validation suite, calling it will remove your suite's state.
43
+
44
+ ```js
45
+ import { create } from 'vest';
46
+
47
+ const suite = create(() => {
48
+ // Your tests go here
49
+ });
50
+
51
+ suite.reset(); // validation result is removed from Vest's state.
52
+ ```
53
+
54
+ ## Dynamically added fields
55
+
56
+ When your form contains dynamically added fields, for example - when a customer can add fields to their checkout form on the fly, those items would still exist in the suite state when the user removed them from the form. This means that you may have an unsuccessful suite result, even though it should be successful.
57
+
58
+ ### Solution: Removing a single field from the validation result
59
+
60
+ Instead of resetting the whole suite, you can alternatively remove just one field. This is useful when dynamically adding and removing fields upon user interaction - and you want to delete a deleted field from the state.
61
+
62
+ ```js
63
+ import { create, test } from 'vest';
64
+
65
+ const suite = create(() => {
66
+ // Your tests go here
67
+
68
+ test('username', 'must be at least 3 chars long', () => {
69
+ /*...*/
70
+ });
71
+ });
72
+
73
+ suite.remove('username'); // validation result is removed from Vest's state.
74
+ ```
75
+
76
+ ## Server side validations
77
+
78
+ When running your validations on the server, you want to keep each request isolated with its own state, and not update the same validation state between requests. Doing that can cause failed validations to seem successful or vice versa due to different requests relying on the same state.
79
+
80
+ ### Solution: Treat validations as stateless
81
+
82
+ While when on the browser you usually want to treat validations as statefull - even though it might sometimes not be the case - on the server you almost always want to treat your validations as stateless.
83
+
84
+ To do that, all you need to do is wrap your suite initialization with a wrapper function. Whenever you call that function, a new suite state will be created.
85
+
86
+ ### Example
87
+
88
+ ```js
89
+ import { create } from 'vest';
90
+
91
+ function suite(data) {
92
+ return create(() => {
93
+ test('username', 'username is required', () => {
94
+ enforce(data.username).isNotEmpty();
95
+ });
96
+ })();
97
+ // Note that we're immediately invoking our suite
98
+ // so what we return is actually the suite result
99
+ }
100
+
101
+ const result = suite({ username: 'Mike123' });
102
+ ```
package/docs/test.md ADDED
@@ -0,0 +1,172 @@
1
+ # Using the `test` function
2
+
3
+ The `test` function is represents a single case in your validation suite. It accepts the following arguments:
4
+
5
+ | Name | Type | Optional | Description |
6
+ | ---------- | ---------- | -------- | ------------------------------------------------------------- |
7
+ | `name` | `String` | No | The name of the value or field being validated. |
8
+ | `message` | `String` | Yes | An error message to display to the user in case of a failure. |
9
+ | `callback` | `Function` | No | The actual validation logic for the given test. |
10
+
11
+ A test can either be synchronous or asynchronous, and it can either have a [severity](./warn) of `error` or of `warn`.
12
+
13
+ ## Failing a test
14
+
15
+ There are three ways to fail a test:
16
+
17
+ ### Throwing inside your test body (using enforce)
18
+
19
+ Just like in most unit testing frameworks, a validation fails whenever the test body throws an exception. [`Enforce`](./enforce) throws on failed validations.
20
+ When thrown with a string
21
+
22
+ ```js
23
+ // const username = 'Gina.Vandervort';
24
+ // const password = 'Q3O';
25
+
26
+ test('username', 'Should be at least 3 characters long', () => {
27
+ enforce(username).longerThanOrEquals(3);
28
+ }); // this test passes
29
+
30
+ test('password', 'Should be at least 6 characters long', () => {
31
+ enforce(password).longerThanOrEquals(6); // an error is thrown here
32
+ }); // this test fails
33
+ ```
34
+
35
+ Alternatively, you can also throw a string value to use it as your test message. To do that, you need to omit the test message, and throw a string, for example - when using enforce.extend.
36
+
37
+ ```js
38
+ enforce.extend({
39
+ isChecked: value => {
40
+ return {
41
+ pass: !!value.checked,
42
+ message: () => 'value must be checked',
43
+ };
44
+ },
45
+ });
46
+
47
+ /*...*/
48
+
49
+ /*
50
+ tost = { checked: false }
51
+ */
52
+
53
+ test('tos', () => {
54
+ enforce(tos).isChecked(); // will fail with the message: "value must be checked"
55
+ });
56
+ ```
57
+
58
+ ### Explicitly returning false
59
+
60
+ To make it easy to migrate your existing validation logic into Vest, it also supports validations explicitly returning `false` (and not any other falsy value) to represent failures.
61
+
62
+ ```js
63
+ // const username = 'Gina.Vandervort';
64
+ // const password = 'Q3O';
65
+
66
+ test('username', 'Should be at least 3 characters long', () => {
67
+ return username.length >= 3; // = true
68
+ }); // this test passes
69
+
70
+ test('password', 'Should be at least 6 characters long', () => {
71
+ return password.length >= 6; // = false
72
+ }); // this test fails
73
+ ```
74
+
75
+ ### Rejecting a Promise
76
+
77
+ This is only true for async tests, more on that below.
78
+
79
+ ## Asynchronous Tests
80
+
81
+ Sometimes you need to validate your data with information not present in your current context, for example - data from the server, such as username availability. In those cases, you need to go out to the server and fetch data as part of your validation logic.
82
+
83
+ An async test is declared by returning a [promise](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise) from your test body. When the promise resolves, your test passes, and when your promise rejects, it fails.
84
+
85
+ ```js
86
+ // Example using a promise
87
+ test('name', 'I always fail', () => Promise.reject());
88
+
89
+ // Example using async/await
90
+ test('name', 'Already Taken', async () => {
91
+ return await doesUserExist(user);
92
+ });
93
+ ```
94
+
95
+ ### Rejecting with a message
96
+
97
+ When performing validations on the server, your server might need to respond with different error messages. When rejecting with a string value, your string value will be picked up as the message to show to the user.
98
+
99
+ ```js
100
+ test('name', () =>
101
+ new Promise((resolve, reject) => {
102
+ fetch(`/checkUsername?name=${name}`)
103
+ .then(res => res.json)
104
+ .then(data => {
105
+ if (data.status === 'fail') {
106
+ reject(data.message); // rejects with message and marks the test as failing
107
+ } else {
108
+ resolve(); // completes. doesn't mark the test as failing
109
+ }
110
+ });
111
+ }));
112
+ ```
113
+
114
+ ## test.memo for memoized tests
115
+
116
+ In order to improve performance and runtime in heavy or long-running tests (such as async tests that go to the server), tests individual test results can be cached and saved for a later time, so whenever the exact same params appear again in the same runtime, the test result will be used from cache, instead of having to be re-evaluated.
117
+
118
+ ### Usage:
119
+
120
+ Memoized tests are almost identical to regular tests, only with the added dependency array as the last argument. The dependency array is an array of items, that when identical (strict equality, `===`) to a previously presented array in the same test, its previous result will be used. You can see it as your cache key to the test result.
121
+
122
+ ### Example:
123
+
124
+ ```js
125
+ import { vest, test } from 'vest';
126
+ export default create('form-name', data => {
127
+ test.memo(
128
+ 'username',
129
+ 'username already exists',
130
+ () => doesUserExist(data.username),
131
+ [data.username]
132
+ );
133
+ });
134
+ ```
135
+
136
+ ## test.each for dynamically creating tests from a table
137
+
138
+ Use test.each when you need to dynamically create tests from data, or when you have multiple tests that have the same overall structure.
139
+
140
+ test.each takes an array of arrays. The inner array contains the arguments that each of the tests will recieve.
141
+
142
+ Because of the dynamic nature of the iterative tests, you can also dynamically construct the fieldName and the test message by providing a function instead of a string. Your array's content will be passed over as arguments to each of these functions.
143
+
144
+ ```js
145
+ /*
146
+ const data = {
147
+ products: [
148
+ ['Game Boy Color', 25],
149
+ ['Speak & Spell', 22.5],
150
+ ['Tamagotchi', 15],
151
+ ['Connect Four', 7.88],
152
+ ]
153
+ }
154
+ */
155
+
156
+ const suite = create('store_edit', data => {
157
+ test.each(data.products)(
158
+ name => name,
159
+ 'Price must be numeric and above zero.',
160
+ (_, price) => {
161
+ enforce(price).isNumeric().greaterThan(0);
162
+ }
163
+ );
164
+ });
165
+ ```
166
+
167
+ **Read next about:**
168
+
169
+ - [Warn only tests](./warn).
170
+ - [Grouping tests](./group).
171
+ - [Asserting with enforce](./enforce).
172
+ - [Skipping or including tests](./exclusion).