ArticleZip > Protractor Check If Element Does Not Exist

Protractor Check If Element Does Not Exist

When writing tests for your web application using Protractor, you might come across scenarios where you need to check if an element does not exist on the page. This can be crucial in ensuring the reliability and accuracy of your tests. In this article, we'll guide you through the process of checking if an element does not exist using Protractor.

To begin, let's first understand why it's important to verify the absence of an element. When writing test cases, you want to cover both positive and negative scenarios to ensure complete test coverage. By checking for the non-existence of an element, you can ensure that your application behaves as expected even when specific elements are missing from the page.

In Protractor, you can use the ExpectedConditions class along with the 'presenceOf' method to check if an element does not exist. This method allows you to define a condition that should not be met. To use this in your Protractor test, you can follow these steps:

1. Import the necessary dependencies:

Javascript

const { browser, ExpectedConditions } = require('protractor');

2. Write a function to check the absence of an element:

Javascript

const isElementNotPresent = async (elementLocator) => {
    return browser.wait(
        ExpectedConditions.invisibilityOf(elementLocator)
    );
};

3. Call the function in your test case:

Javascript

it('should check if an element does not exist', async () => {
    await browser.get('yourpageurl.com');
    const elementToCheck = element(by.css('your-css-selector'));
    expect(await isElementNotPresent(elementToCheck)).toBe(true);
});

In the code snippet above, we created a function called 'isElementNotPresent' that takes an element locator as an argument. This function uses the 'invisibilityOf' method from ExpectedConditions to wait until the element becomes invisible or does not exist on the page.

Within your test case, you can then call this function and pass the element you want to verify. The function will return true if the element is not present and false if the element is still visible on the page.

By incorporating this technique into your Protractor tests, you can enhance the robustness of your test suite by verifying the non-existence of elements on your web application. This ensures that your tests provide accurate feedback on the behavior of your application under various conditions.

Remember to use this method judiciously in your test cases to cover a wide range of scenarios and improve the overall quality of your automated tests. Happy testing with Protractor!