Reputation: 137
Is it possible to verify 'what's your sign'text in prompt? Alert and Confirm can be verified text, but prompt I wonder if possible?
Upvotes: 2
Views: 568
Reputation: 8610
You can simply assign a variable name to the prompt code and retrieve its value by calling the variable.
const main = document.querySelector('#main');
const num = Number(window.prompt("How old are you?", ""));
// now do some evaluation with conditional
let output = '';
// conditional stmt to see if input is higher or lower than US drinking age
num < 21 ? output = `Sorry but ${num} years old is not old enough to drink.` :
output = `Excellent, at ${num} years old, you can drink.`;
// set mains text content to the output message we wish
// to show depending on age user input into prompt
main.textContent = output;
<div id="main"></div>
Upvotes: 1
Reputation: 32034
You can set up a stub before the action that triggers the prompt:
Generally,
let stub;
cy.window().then(win => {
stub = cy.stub(win, 'prompt').returns(' World') // types this value
})
cy.get('button-opening-prompt').click()
cy.wrap(stub).should(() => {
expect(stub).to.have.been.calledWith('Hello') // argument is the message
// displayed in the prompt
})
A simple app that prompts after 2 seconds:
<body>
<div>Hello </div>
<script>
setTimeout(() => {
const result = window.prompt('Hello')
const div = document.querySelector('div')
div.innerText += result
}, 2000)
</script>
</body>
This can be tested with
let stub;
cy.visit('http://127.0.0.1:5500/html/prompt.html', {
onBeforeLoad: (win) => {
stub = cy.stub(win, 'prompt').returns(' World')
}
})
cy.get('div').should('contain', 'Hello World') // checks the result added to page
cy.wrap(stub).should(() => {
expect(stub).to.have.been.calledWith('Hello')
})
To test the cancel button being pressed, substitute
stub = cy.stub(win, 'prompt').callsFake(() => null)
Upvotes: 5