Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to test inquirer validation

I have already seen the question and answer on How to write unit tests for Inquirer.js?

I want to test that my validation is correct. So for example, if I have:

const answer = await inquirer.prompt({
   name: 'answer',
   message: 'are you sure?'
   type: 'input',
   validate: async (input) => {
      if (input !== 'y' || input !== 'n') {
         return 'Incorrect asnwer';
      }

      return true;
   }
});

I want to run a unit test that I can run and verify that if I provided blah, the validation will validate correctly. How can I write a test for this?

like image 556
Kousha Avatar asked Oct 28 '25 14:10

Kousha


1 Answers

I would move validation to separate function, and test it in isolation. Both test and code will look clearer:

 const confirmAnswerValidator = async (input) => {
      if (input !== 'y' || input !== 'n') {
         return 'Incorrect asnwer';
      }
      return true;
   };
const answer = await inquirer.prompt({
   name: 'answer',
   message: 'are you sure?'
   type: 'input',
   validate: confirmAnswerValidator
});

and then in test

describe('Confirm answer validator', () => {
 it('Raises an error on "blah"', async () => {
   const result = await confirmAnswerValidator('blah');
   expect(result).toBe('Incorrect asnwer');
 });
});
like image 77
udalmik Avatar answered Oct 31 '25 04:10

udalmik



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!