admin管理员组

文章数量:1296260

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?

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?

Share asked Aug 2, 2019 at 6:49 KoushaKousha 36.3k59 gold badges187 silver badges313 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 8

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');
 });
});

本文标签: javascriptHow to test inquirer validationStack Overflow