Skip to content
This repository has been archived by the owner on Apr 19, 2024. It is now read-only.

Testing survey.AskOne method with custom input #448

Closed
denizgursoy opened this issue Sep 2, 2022 · 1 comment
Closed

Testing survey.AskOne method with custom input #448

denizgursoy opened this issue Sep 2, 2022 · 1 comment
Labels

Comments

@denizgursoy
Copy link

denizgursoy commented Sep 2, 2022

How can I provide input from byte array or text file for survey? I want to use it for test purposes.When I ask for input, I want to send mock value. Example code:

result := ""

input := survey.Input{
	Message: direction,
}
err := survey.AskOne(&input, &result, survey.WithValidator(survey.Validator(validator)))
return result, err
@denizgursoy denizgursoy changed the title Testing Testing survey.AskOne method with custom input Sep 2, 2022
@mislav
Copy link
Collaborator

mislav commented Sep 21, 2022

Hi, mocking Survey responses currently isn't straightforward and will only become easier after #428.

In the meantime, you can set up a virtual terminal in your tests to simulate user input to your prompt: https://github.com/AlecAivazis/survey#testing. Note that this also isn't straightforward.

My personal choice would be to declare a Prompter type in your code that has a method like PromptInput that uses Survey under the hood:

func (p Prompter) PromptInput(message string, validator func(string) bool) (string, error) {
	var result string
	err := survey.AskOne(&survey.Input{
		Message: direction,
	}, &result, survey.WithValidator(survey.Validator(validator)))
	return result, err
}

Then, in test mode, pass a mock object to your app that responds to PromptInput() but returns pre-defined fake responses. That way, Survey never gets actually invoked in tests, and you avoid a whole lot of trouble.

@mislav mislav closed this as completed Sep 21, 2022
Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
Projects
None yet
Development

No branches or pull requests

2 participants