javascript - 如何使用 Protractor 设置错误消息

标签 javascript selenium protractor

所以我已经使用 Protractor 工作了一段时间,我发现我遇到了错误消息等问题。如果我在 60 秒内没有找到元素,那么我只会抛出超时错误。这并不是一个真正了解问题所在的好方法,我在这里问你们我如何能够放置我自己的错误消息等,即尚未找到此特定元素或类似的内容。

我已经编写了类似的代码。

测试用例类:

const userData = require("../globalContent.json");
const Page = require("../objects/ikeaProductPage.obj");


describe("Product page", function () {

    ikeaPage = new Page();

    for (let [link, amount] of Object.entries(userData[browser.baseUrl])) {
        // The Ikea page is accessible by the specified URL
        it(`Is defined by the URL: ${link}`,
            async function() {
                await Page.navigateDesktop(`${link}`);
            });

        // page has a quantity label and it can be filled out with user data
        it("Has a label quantity that can receive user data",
            async function() {
                await Page.fillFormWithUserData(`${amount}`);
            });

        // Details page allows the user to add to cart
        it("Enables resolution of added to cart",
            async function() {
                await Page.hasAddToShoppingCart();
            });

        // Details page allows the user to proceed to the next stage when page has been resolved
        it("Allows the user to proceed to the next stage of add to cart",
            async function() {
                await Page.hasAddedToBag();
                await browser.sleep(1000);
            });
    }
});

对象类别:

const utils = require("../utils/utils");
const Specs = require("../specs/ProductPage.specs");

module.exports = class Page {

    constructor() {
        const _fields = {
            amountInput: Specs.productAmount
        };

        const _formButtons = {
            addToCart: ikeaSpecs.addToCart
        };

        const _productFrame = {
            cartIcon: ikeaSpecs.cartIcon,
            addedToCartIcon: Specs.addedToCart,
        };

        this.getFields = function() {
            return _fields;
        };
        this.getFormButtons = function() {
            return _formButtons;
        };
        this.getFrame = function() {
            return _productFrame;
        };
    }

    getForm() {

        return {
            fields: this.getFields(),
            buttons: this.getFormButtons(),
        };
    }

    getPageFrame() {
        return {
            buttons: {
                iconFrames: this.getFrame()
            }
        };
    }


    //Navigate for Desktop
    async navigateDesktop(URL) {
        await browser.waitForAngularEnabled(false);
        await browser.manage().window().maximize();
        await browser.get(URL);
    }

    //Fill qty from globalContent.json
    async fillFormWithUserData(amountQuantity) {
        const formFields = this.getForm().fields.amountInput;
        await formFields.clear();
        await utils.sendKeys(formFields, amountQuantity);
    }

    //Check if we can add to shopping cart
    async hasAddToShoppingCart() {
        const formButton = this.getForm().buttons.addToCart;
        await utils.elementToBeClickable(formButton);
        await utils.click(formButton);
    }

    //Check if the product has been added
    async hasAddedToBag() {
        const frameCartIcon = this.getPageFrame().buttons.iconFrames.cartIcon;
        const frameAddedToCart = this.getPageFrame().buttons.iconFrames.addedToCartIcon;
        await utils.presenceOf(frameCartIcon);
        await utils.elementToBeClickable(frameAddedToCart);
    }

};

实用程序:

const utils = function () {
    var EC = protractor.ExpectedConditions;

    this.presenceOf = function (params) {
        return browser.wait(EC.presenceOf(params));
    };

    this.elementToBeClickable = function (params) {
        return browser.wait(EC.elementToBeClickable(params));
    };

    this.sendKeys = function (params, userData) {
        return params.sendKeys(userData);
    };

    this.click = function (params) {
        return browser.executeScript("arguments[0].click();", params.getWebElement());
    };

    this.switch = function (params) {
        return browser.switchTo().frame(params.getWebElement());
    };

    this.switchDefault = function () {
        return browser.switchTo().defaultContent();
    };
};

module.exports = new utils();

我想知道如何设置更正确的错误而不仅仅是超时?

最佳答案

由于您在后台使用 browser.wait,那么您需要考虑使用其中之一 parameters 。正如页面所示,它需要 3 个参数,并且所有参数都很有用:

browser.wait(
  () => true, // this is your condition, to wait for (until the function returns true)
  timeout, // default value is jasmineNodeOpts.defaultTimeoutInterval, but can be any timeout
  optionalMessage // this is what you're looking for
)

已更新

所以如果我使用全部三个,它会看起来像这样

this.presenceOf = function (params, message) {
  return browser.wait(
    EC.presenceOf(params),
    jasmine.DEFAULT_TIMEOUT_INTERVAL,
    `Element ${params.locator().toString()} is not present. Message: ${message}`
  )
};

当你调用它时,就像这样

await utils.presenceOf(frameCartIcon, 10000, "frame should be populated");

它失败了,你会得到这个堆栈

      - Failed: Element By(css selector, "some css") is not present. Message: frame should be populated
      Wait timed out after 1002ms
      Wait timed out after 1002ms
          at /Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:2201:17
          at ManagedPromise.invokeCallback_ (/Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:1376:14)
          at TaskQueue.execute_ (/Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:3084:14)
          at TaskQueue.executeNext_ (/Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:3067:27)
          at asyncRun (/Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:2927:27)
          at /Users/spleshakov/Documents/ui-automation/node_modules/selenium-webdriver/lib/promise.js:668:7
          at processTicksAndRejections (internal/process/next_tick.js:81:5)
      From: Task: Element By(css selector, "some css") is not present. Message: frame should be populated

关于javascript - 如何使用 Protractor 设置错误消息,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61189789/

相关文章:

javascript - Node 和 Angular cookie 路径

python - 在 Python 中使用 Selenium 抓取无限滚动网站

java - 如何使用 Selenium 获取 css 类名?

angularjs - 安全和 ngMockE2E

javascript - 无法循环遍历类名 JavaScript

javascript - 为什么我在使用变量 'name' 时在 Chrome 调试器中得到错误对象没有方法?

javascript - 检测元素高度变化并在太小时隐藏

Firefox:崩溃后禁用自动安全模式

javascript - Angular Protractor 测试因 Modal 内的 Select2 失败

javascript - 将多个数组插入一个数组形成一个二维数组