【问题标题】:how to get current url from codeception & phantomjs test?如何从 codeception & phantomjs 测试中获取当前 url?
【发布时间】:2016-08-06 05:48:36
【问题描述】:

我正在使用我的测试在 estore 中创建产品,并且需要在提交表单后获取 url。

提交按钮后是否可以在测试范围内获取url

$I->click('#formSubmit');
$I->wait(5); // wait for redirect to new url
$url = $I->someFunctionToGetCurrentUrl()`

我是从控制台运行此测试,而不是从 Web 浏览器,所以我无权访问服务器端的 $_SERVER。

但是如果我在代码接收框架中有一些方法,比如$I->canSeeCurrentUrlEquals(),那么我应该能够以某种方式访问​​当前的 url...

怎么做?

【问题讨论】:

  • “在测试范围内”是什么意思?
  • 我是从控制台运行此测试,而不是从 Web 浏览器,所以我无权访问服务器端的 $_SERVER。但是,如果我在 codeception 框架中有一些方法,如 $I->canSeeCurrentUrlEquals(),那么我应该能够以某种方式访问​​当前的 url ......怎么做?这就是问题...
  • 请编辑您的问题以包含此附加信息。

标签: php phantomjs codeception


【解决方案1】:

解决方案是在 _support/AcceptanceHelper.php 文件中为 AcceptanceHelper 添加一个辅助方法:

    class AcceptanceHelper extends \Codeception\Module
    {

        /**
         * Get current url from WebDriver
         * @return mixed
         * @throws \Codeception\Exception\ModuleException
         */
        public function getCurrentUrl()
        {
            return $this->getModule('WebDriver')->_getCurrentUri();
        }

    }

然后在测试中使用它:

$url = $I->getCurrentUrl();

【讨论】:

  • 我只得到 URI/URL 的路径部分,而不是完整的东西(包括 http)。
  • 我希望它对某人有用,用协议等获取完整的 URL。用这个替换 return 语句:return $this->getModule('WebDriver')->_getUrl().$this- >getModule('WebDriver')->_getCurrentUri();
【解决方案2】:

如果您没有 AcceptanceHelper/FunctionalHelper 类(因此 $this->getModule 或 $this->client 未定义),那么您的 AcceptanceTester/FunctionalTester 类中的以下内容应该可以工作:

public function getCurrentUrl() {
    return $this->executeJS("return location.href");
}

【讨论】:

    【解决方案3】:

    您可以使用 CodeCeption 的 PhpBrowser 函数 grabFromCurrentUrl() 来获取当前 URL。

    https://codeception.com/docs/modules/PhpBrowser#grabFromCurrentUrl

    此函数接受正则表达式以返回当前 URL 的特定部分,但也...

    如果没有提供参数,则返回完整的 URI。

    所以,像这样使用它

    $uri = $I->grabFromCurrentUrl();
    

    【讨论】:

      猜你喜欢
      • 2014-01-27
      • 2016-06-05
      • 2012-06-01
      • 1970-01-01
      • 1970-01-01
      • 2017-04-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多