1+ import { expect } from 'chai' ;
2+ import { describe , it } from 'mocha' ;
3+ import * as yup from 'yup' ;
4+ import Form from '../../../../src' ;
5+ import $yup from "../../../../src/validators/YUP" ;
6+
7+ const plugins = {
8+ dvr : $yup ( {
9+ package : yup ,
10+ schema : ( y : any ) =>
11+ y . object ( ) . shape ( {
12+ subscribe : y . boolean ( ) ,
13+ email : y . string ( ) . when ( 'subscribe' , {
14+ is : true ,
15+ then : ( schema : any ) => schema . required ( 'Email is required if subscribed' ) ,
16+ otherwise : ( schema : any ) => schema . notRequired ( ) ,
17+ } ) ,
18+ } ) ,
19+ } ) ,
20+ } ;
21+
22+ const fields = [
23+ {
24+ name : 'subscribe' ,
25+ label : 'Subscribe' ,
26+ type : 'checkbox' ,
27+ } ,
28+ {
29+ name : 'email' ,
30+ label : 'Email' ,
31+ placeholder : 'Enter your email' ,
32+ } ,
33+ ] ;
34+
35+ export const form626b = new Form ( { fields } , { plugins } ) ;
36+
37+
38+ describe ( 'Yup plugin with yup.when()' , ( ) => {
39+ it ( 'should require email when subscribe is true' , async ( ) => {
40+ form626b . reset ( ) ;
41+ form626b . $ ( 'subscribe' ) . set ( true ) ;
42+ form626b . $ ( 'email' ) . set ( '' ) ;
43+
44+ await form626b . validate ( ) ;
45+
46+ expect ( form626b . isValid ) . to . be . false ;
47+ expect ( form626b . $ ( 'email' ) . hasError ) . to . be . true ;
48+ expect ( form626b . $ ( 'email' ) . error ) . to . equal ( 'Email is required if subscribed' ) ;
49+ } ) ;
50+
51+ it ( 'should not require email when subscribe is false' , async ( ) => {
52+ form626b . reset ( ) ;
53+ form626b . $ ( 'subscribe' ) . set ( false ) ;
54+ form626b . $ ( 'email' ) . set ( '' ) ;
55+
56+ await form626b . validate ( ) ;
57+
58+ expect ( form626b . isValid ) . to . be . true ;
59+ expect ( form626b . $ ( 'email' ) . hasError ) . to . be . false ;
60+ } ) ;
61+
62+ it ( 'should pass validation if email is set when subscribe is true' , async ( ) => {
63+ form626b . reset ( ) ;
64+ form626b . $ ( 'subscribe' ) . set ( true ) ;
65+ form626b . $ ( 'email' ) . set ( 'test@example.com' ) ;
66+
67+ await form626b . validate ( ) ;
68+
69+ expect ( form626b . isValid ) . to . be . true ;
70+ expect ( form626b . $ ( 'email' ) . hasError ) . to . be . false ;
71+ } ) ;
72+ } ) ;
0 commit comments