找不到元素时打字稿不会失败

时间:2018-12-26 14:57:59

标签: typescript jasmine protractor

我正在使用Typescript-Protractor茉莉花。当找不到元素时,它不会使测试用例失败(“ it”块)。尽管它显示UnhandledPromiseRejectionWarning,但仍显示脚本已传递。

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

1 个答案:

答案 0 :(得分:1)

要正确处理此类情况,您必须努力工作(断言)。 如果单击或其他操作未成功,则并不意味着测试应失败。 您必须指定何时失败。

例如:

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();
});

或者使用异常处理“ 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
    });

或有期望

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();
    });

封装的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);
        }

    });

您可以在此处阅读有关POM的更多信息: https://github.com/angular/protractor/blob/master/docs/page-objects.md