Esquema de objeto Joi:
import Joi from 'joi'; export const schema = Joi.object({ payway: Joi.when('productPackageType', { is: Joi.string().valid('1', '6', '7'), then: Joi.array().min(1).max(2).items(Joi.string().valid('alipay', 'wxpay').required()) .required() .messages({ 'array.min': 'payway is required', 'array.includesRequiredUnknowns': 'payway is not correct', }), otherwise: Joi.optional(), }), productPackageType: Joi.string().required(), });archivo de prueba:
test.only('should validate error if productPackageType is "1" and payway is an empty array ', () => { const v = { payway: [], productPackageType: '1', }; const r = schema.validate(v); expect(r.error?.details[0].message).toMatch('payway is required'); });Prueba fallida:
● validator › schema › should validate error if productPackageType is "1" and payway is an empty array expect(received).toMatch(expected) Expected substring: "payway is required" Received string: "payway is not correct" 22 | }; 23 | const r = schema.validate(v); > 24 | expect(r.error?.details[0].message).toMatch('payway is required'); | ^ 25 | }); 26 | 27 | // test('should validate error if productPackageType is "1" and payway has invalid element', () => { Espero que Joi valide primero la longitud de la matriz y luego el elemento de la matriz. Esto significa que el mensaje de error debería ser 'payway is required' en lugar de 'payway is not correct' .
No sé cuál es la prioridad de la validación de Joi. ¿Qué validador se usa primero, .min(1) o .items(Joi.string().valid('alipay', 'wxpay').required()) ?