【问题标题】:How to assert page/tab/window title in Behat + Mink如何在 Behat + Mink 中声明页面/选项卡/窗口标题
【发布时间】:2019-07-04 18:02:19
【问题描述】:

我需要为我的测试声明一个页面标题,即使用 Behat+Mink 的选项卡/窗口标题
我试过 getWindowName() 但意识到这不是我要找的函数。

【问题讨论】:

    标签: behat mink


    【解决方案1】:

    您应该使用 css 的常规查找作为标题标签,并使用 getText() 来获取标题。

    css 应该是:"head title"

    您的解决方案几乎没问题,您需要注意可能的异常,尤其是遇到可能会停止您的套件的致命异常。

    例如find()方法将返回一个对象或null,如果null被返回并且你在它上面使用getText()它将导致一个致命异常并且你的套件将停止。

    略微改进的方法:

    /**
     * @Given /^the page title should be "([^"]*)"$/
     */
    public function thePageTitleShouldBe($expectedTitle)
    {
        $titleElement = $this->getSession()->getPage()->find('css', 'head title');
        if ($titleElement === null) {
            throw new Exception('Page title element was not found!');
        } else {
            $title = $titleElement->getText();
            if ($expectedTitle !== $title) {
                throw new Exception("Incorrect title! Expected:$expectedTitle | Actual:$title ");
            }
        }
    }
    

    改进:

    • 处理了可能的致命异常
    • 如果找不到元素则抛出异常
    • 如果标题不匹配,则抛出带有详细信息的异常

    请注意,您还可以使用其他方法来检查标题,例如:stripos、strpos 或像我一样简单地比较字符串。如果我需要精确的文本或 php 的 strpos/stripos 方法,我更喜欢简单的比较,我个人会避免常规异常和相关方法,如 preg_match 通常会慢一些。

    您可以做的一个主要改进是拥有一种等待元素并为您处理异常的方法,并使用它而不是简单的查找,当您需要根据元素的存在做出决定时可以使用查找,例如:如果元素存在,则执行此操作。

    【讨论】:

      【解决方案2】:

      感谢劳达。是的,这确实有效。编写如下函数:

      /**
           * @Given /^the page title should be "([^"]*)"$/
           */
          public function thePageTitleShouldBe($arg1)
          {
              $actTitle = $this->getSession()->getPage()->find('css','head title')->getText();
              if (!preg_match($arg1, $actTitle)) {
                  throw new Exception ('Incorrect title');
              }
          }
      

      【讨论】:

        【解决方案3】:

        在使用 Javascript 和 history.pushState/replaceState 操作标题的情况下,这对我不起作用

        这里有一个适用于 Javascript 的实现:

          /**
           * @Then /^the title is "([^"]*)"$/
           */
          public function theTitleIs($arg1) {
            $title = $this->getSession()->evaluateScript("return document.title");
            if ($arg1 !== $title) {
              throw new \Exception("expected title '$arg1', got '$title'");
            }
          }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-04-30
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2013-01-07
          • 1970-01-01
          相关资源
          最近更新 更多