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