user812142
user812142

Reputation: 173

Typescript not failing when element not found

I am using Typescript-Protractor Jasmine. When an element is not found it is not failing the test case (the 'it' block). It is showing UnhandledPromiseRejectionWarning though but it is still showing the script as passed.

   await element(by.xpath("xpath")).click().then(()=>{logObj.info("clicked")});

Upvotes: 0

Views: 377

Answers (1)

Infern0
Infern0

Reputation: 2814

To properly handle such cases you have to work with expectation (assert). If the click or other action is not success, that does not mean test should fail. You have to specify when to fail.

For example:

it('should do something smart', async (done) => {
    await element(by.xpath('dsadadada')).click()
        .then(() => {
            logObj.info("clicked");
        })
        .catch(rejected => {
            logObj.info("it was not clicked due rejected promise");
            done.fail(rejected); // fail the test
        });

    done();
});

Or work with exception handling 'try catch':

   it('should do something smart', async (done) => {

        try {
            await element(by.xpath('dsadadada')).click(); // will throw error if not clickable
            await element(by.xpath('dsadadada')).sendKeys('dasdada'); // will throw error if cannot sendkeys

        } catch (e) {
            done.fail(e); // will fail the test if some action throw an error.
        }

        done(); // if there is no error will mark the test as success
    });

or with expecations

it('should do something smart', async (done) => {

        await element(by.xpath('dsadadada')).click(); // will throw error if not clickable
        expect(element(by.xpath('some new element on the page after click')).isPresent()).toBeTruthy();
        done();
    });

Example of encapsulated POM

public class PageObjectClass {
        // action of click.
        public async clickOnXBtn() {
            await await element(by.xpath('dsadadada')).click();
        }
    }

    it('do something dummy', async (done) => {
        try {
            // pageobject is class which holds the action for this button.
            const pageObject = new PageObjectClass();

            await pageObject.clickOnXBtn();
        } catch (e) {
            done.fail(e);
        }

    });

You can read more for POM here: https://github.com/angular/protractor/blob/master/docs/page-objects.md

Upvotes: 1

Related Questions