如何在Behat + Mink中声明页面/标签/窗口标题 [英] How to assert page/tab/window title in Behat + Mink

查看:54
本文介绍了如何在Behat + Mink中声明页面/标签/窗口标题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要为测试声明一个页面标题,这是使用Behat + Mink的选项卡/窗口标题
我尝试了getWindowName(),但意识到那不是我要寻找的功能.

I need to assert a page title for my test, which is the tab/window title using Behat+Mink
I tried getWindowName() but realized that is not the function I am looking for.

推荐答案

您应该使用css的常规find作为title标签,并使用getText()获取标题.

You should use a regular find by css for the title tag and use getText() to get the title.

css应该是:标题"

The css should be: "head title"

您的解决方案几乎可以,您需要注意可能出现的异常,尤其是致命的异常,如果遇到异常可能会阻止您的套件.

Your solution is almost ok, you need to watch for possible exception, especially fatal ones that can stop your suite if encountered.

例如,find()方法将返回一个对象或null,如果返回了null且您正在使用getText(),则会导致致命异常和您的套件将停止.

For example find() method will return an object or null, if null is returned and you are using getText() on it it will result in a fatal exception and your suite will stop.

略有改进的方法:

/**
 * @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 ");
        }
    }
}

改进:

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

请注意,您还可以使用其他方法来检查标题,例如:striposstrpos,或者像我一样简单地比较字符串.如果我需要精确的文本或php的strpos/stripos方法,而我个人而言,我希望进行简单比较,避免常规异常和诸如preg_match之类的关联方法,这些方法通常会慢一些.

Note that you can also use other methods to check the title like: stripos, strpos or simply compare strings like i did. I prefer a simple compare if i need exact text or strpos/stripos method of php and I personally, avoid regular exceptions and associated methods like preg_match which are usually a bit slower.

您可以做的一个重大改进是拥有一种等待元素并为您处理异常的方法,并使用该方法代替简单的查找,可以在需要根据元素的存在来做出决定时使用查找,例如:如果元素存在,则执行其他操作.

One major improvement you could do is to have a method for waiting the element and handle the exception for you and use that instead of simple find, find you can use when you need to take decision based on the presence of the element like: if element exists do this else..

这篇关于如何在Behat + Mink中声明页面/标签/窗口标题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆