如何从codeception&;phantomjs测试


how to get current url from codeception & phantomjs test?

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

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

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

我是从控制台运行这个测试的,而不是从web浏览器,所以我不能访问服务器端的$_SERVER。

但如果我在codeception框架中有一些像$I->canSeeCurrentUrlEquals()这样的方法,那么我应该能够以某种方式访问当前的url。。。

怎么做?

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

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

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

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

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

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

此函数接受regex以返回当前URL的特定部分,但也。。。

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

所以,像这个一样使用它

$uri = $I->grabFromCurrentUrl();