Show List

Alerts and pop-ups

Here's a sample TestCafe test script that demonstrates working with alerts and pop-ups:


import { Selector } from 'testcafe'; fixture('Alert and Pop-up Test') .page('https://www.example.com'); test('Handle Alert and Pop-up', async t => { // Selector for the element that triggers the alert const alertButton = Selector('#alert-button'); // Click the button to trigger the alert await t .click(alertButton); // Handle the alert await t .expect(Selector('div').withText('Alert message').exists).ok() .click('#confirm-ok'); // Assuming there's an OK button to dismiss the alert // Selector for the element that triggers the pop-up const popupButton = Selector('#popup-button'); // Click the button to trigger the pop-up await t .click(popupButton); // Switch to the pop-up window const popupWindow = await t .getWindow((await t.getWindows()).length - 1); // Perform actions in the pop-up window await t .switchToWindow(popupWindow) // Perform actions in the pop-up window, for example: .typeText('#username', 'testuser') .typeText('#password', 'password') .click('#login-button') // Switch back to the main window .switchToMainWindow(); });

In this test:

  • We import the Selector function from TestCafe to select elements on the web page.
  • We define a fixture named 'Alert and Pop-up Test' and set the page to 'https://www.example.com'.
  • Inside the test function:
    • We define a selector for the button that triggers the alert (alertButton) and another selector for the button that triggers the pop-up (popupButton).
    • We click the alertButton to trigger the alert.
    • We handle the alert by expecting its existence and clicking on the OK button to dismiss it.
    • We click the popupButton to trigger the pop-up.
    • We switch to the pop-up window and perform actions inside it (e.g., entering username and password and clicking login).
    • Finally, we switch back to the main window.

Make sure to replace 'https://www.example.com' with the URL of the website you want to test, and adjust the selectors accordingly based on the structure of the webpage you are testing. Additionally, replace '#confirm-ok', '#username', '#password', and '#login-button' with appropriate selectors for the elements in your webpage.


    Leave a Comment


  • captcha text