Skip to main content
Version: 5.x

omitWhen - Conditionally omit tests from a suite

In some cases, we need to wish to omit certain portions of our suite in a way that these tests won't run, and will not count against isValid. For example, when we have some tests that are only allowed to run when a certain checkbox is checked by the user.

Generally, when we skip fields, they are counted against isValid, meaning, unless specifically marked as optional, the suite will not be regarded as valid. Using omitWhen fixes it by both preventing the omitted tests from running, and allowing the suite to be valid even without them.

Differences from skipWhen

Unlike skipWhen, tests omitted using omitWhen are not counted against isValid. Additionally, any validation message of an omitted test will be excluded from the suite result if the condition for the omitWhen is true.

Params

NameTypeDescription
Conditionalboolean/function*The conditional expression to be evaluated. When Truthy, the tests within omitWhen will be omitted.
BodyfunctionA callback function containing the tests to either omit or run.

* When using the function conditional, the function will be passed the current validation result as an argument, so it can be used to skip tests based on the current validation result.

Usage Example

import { create, test, enforce, omitWhen, only } from 'vest';

create((data = {}, currentField) => {
only(currentField);

test('username', 'username is required', () => {
enforce(data.username).isNotBlank();
});

omitWhen(data.useNewAddress, () => {
test('address_line_1', 'Address Line 1 is required', () => {
enforce(data.address_line_1).isNotBlank();
});

test('city', 'City is required', () => {
enforce(data.city).isNotBlank();
});

test('postal_code', 'Postal code is required', () => {
enforce(data.postal_code).isNotBlank();
});
});
});
omitWhen(
res => res.hasErrors('username'),
() => {
test('username', 'Username already exists', () => {
// this is an example for a server call
return doesUserExist(data.username);
});
}
);