I want to test an array of answers, which can have multiple choice answers of dissertative answers. When the type is multiple choice, it must have an option id, when the type is dissertative, it must have an answer, something like this:
const answers = [
{
question: 'question_id1',
type: 'MULTIPLE_CHOICE',
option: 'option_id1'
},
{
question: 'question_id2',
type: 'DISSERTATIVE',
answer: 'This is an answer'
},
];
I've defined a schema like this:
const schema = object().shape({
answers: array()
.of(
object().shape({
question: string().required("Invalid question"),
type: string().required('Invalid type'),
option: object().when("type", {
is: type => type === "MULTIPLE_CHOICE",
then: string().required
}),
answer: object().when("type", {
is: type => type === "DISSERTATIVE",
then: string().required
})
})
)
.min(1)
.max(10)
});
But all I am getting is an error: Cannot read property 'test' of undefined
Reproducible repo is here: https://codesandbox.io/s/nrnjzv4nkp

ok, I've solved that doing this: https://codesandbox.io/s/r0v7v22jln
const schema = object().shape({
answers: array()
.of(
object().shape({
question: string().required("Invalid question"),
type: string().required('Invalid type'),
option: string().test("is-option", function(value) {
return this.parent.type === "MULTIPLE_CHOICE" &&
(typeof value !== "string" || value.length < 1)
? false
: true;
}),
answer: string().test("is-answer", function(value) {
return this.parent.type === "DISSERTATIVE" &&
(typeof value !== "string" || value.length < 1)
? false
: true;
})
})
)
.min(1)
.max(10)
});
But I guess that it still has a bug when using when.
Feel free to close this issue if it does not make sense anymore.
the problem was you weren't calling string.required -> string.required()
Thanks!!! Now I am getting this: You cannotconcat()schema's of different types: object and string

Just changed from object().when() to string().when() and worked 馃帀
Most helpful comment
Just changed from
object().when()tostring().when()and worked 馃帀