3

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?

Kousha
  • 32,871
  • 51
  • 172
  • 296

1 Answers1

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');
 });
});
udalmik
  • 7,838
  • 26
  • 40
  • This is a good unit test for the validation function. The only drawback it's tied to `inquirer`. If we replace `inquirer` with any cli prompting solution the test will fail. I would suggest creating a test that verifies `'Incorrect answer'` was prompted via stdout. This would assert what the user sees. I haven't found a way to do this yet. – mitra Jul 28 '20 at 00:56
  • 1
    it is not tied, it is just testing validation function, thats it. so we are testing our func and rely on 3rd party library to do its work. test on controlling the stdout, produced by module looks like a component test, not unit. – udalmik Jul 28 '20 at 12:42
  • Yes, it's an integration/component test. Hey, thanks for answering I'm just recently learning about testing and cli's. Do you think a unit test on this validation function provides a good enough value? imagine you have like 10 of these. Isn't it a higher value option to write integration/component tests? – mitra Jul 28 '20 at 14:21
  • 1
    I always depends on the case. I think in general it does. Unit tests for your pure functions are always a good start, as they are fast and stable. So you can test all kind of cases. Component tests require more maintenance effort, so I prefer to use them for critical paths only. – udalmik Jul 28 '20 at 14:59