Yup: Cannot read property 'test' of undefined

Created on 27 Feb 2019  路  4Comments  路  Source: jquense/yup

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

screen shot 2019-02-27 at 11 52 22

Most helpful comment

Just changed from object().when() to string().when() and worked 馃帀

All 4 comments

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

screen shot 2019-02-27 at 13 15 22

Just changed from object().when() to string().when() and worked 馃帀

Was this page helpful?
0 / 5 - 0 ratings

Related issues

aprat84 picture aprat84  路  4Comments

ghost picture ghost  路  4Comments

Simmetopia picture Simmetopia  路  4Comments

odesey picture odesey  路  4Comments

the-daniel-rothig picture the-daniel-rothig  路  4Comments