HumHub Documentation (unofficial)

Yii2 extends Framework
in package
implements ActiveRecord, MultiSession, PartedModule

This module provides integration with [Yii framework](http://www.yiiframework.com/) (2.0).

It initializes the Yii framework in a test environment and provides actions for functional testing.

Application state during testing

This section details what you can expect when using this module.

  • You will get a fresh application in \Yii::$app at the start of each test (available in the test and in _before()).
  • Inside your test you may change application state; however these changes will be lost when doing a request if you have enabled recreateApplication.
  • When executing a request via one of the request functions the request and response component are both recreated.
  • After a request the whole application is available for inspection / interaction.
  • You may use multiple database connections, each will use a separate transaction; to prevent accidental mistakes we will warn you if you try to connect to the same database twice but we cannot reuse the same connection.

Config

  • configFile required - path to the application config file. The file should be configured for the test environment and return a configuration array.
  • applicationClass - Fully qualified class name for the application. There are several ways to define the application class. Either via a class key in the Yii config, via specifying this codeception module configuration value or let codeception use its default value yii\web\Application. In a standard Yii application, this value should be either yii\console\Application, yii\web\Application or unset.
  • entryUrl - initial application url (default: http://localhost/index-test.php).
  • entryScript - front script title (like: index-test.php). If not set it's taken from entryUrl.
  • transaction - (default: true) wrap all database connection inside a transaction and roll it back after the test. Should be disabled for acceptance testing.
  • cleanup - (default: true) cleanup fixtures after the test
  • ignoreCollidingDSN - (default: false) When 2 database connections use the same DSN but different settings an exception will be thrown. Set this to true to disable this behavior.
  • fixturesMethod - (default: _fixtures) Name of the method used for creating fixtures.
  • responseCleanMethod - (default: clear) Method for cleaning the response object. Note that this is only for multiple requests inside a single test case. Between test cases the whole application is always recreated.
  • requestCleanMethod - (default: recreate) Method for cleaning the request object. Note that this is only for multiple requests inside a single test case. Between test cases the whole application is always recreated.
  • recreateComponents - (default: []) Some components change their state making them unsuitable for processing multiple requests. In production this is usually not a problem since web apps tend to die and start over after each request. This allows you to list application components that need to be recreated before each request. As a consequence, any components specified here should not be changed inside a test since those changes will get discarded.
  • recreateApplication - (default: false) whether to recreate the whole application before each request

You can use this module by setting params in your functional.suite.yml:

actor: FunctionalTester
modules:
    enabled:
        - Yii2:
            configFile: 'path/to/config.php'

Parts

By default all available methods are loaded, but you can also use the part option to select only the needed actions and to avoid conflicts. The available parts are:

  • init - use the module only for initialization (for acceptance tests).
  • orm - include only haveRecord/grabRecord/seeRecord/dontSeeRecord actions.
  • fixtures - use fixtures inside tests with haveFixtures/grabFixture/grabFixtures actions.
  • email - include email actions seeEmailsIsSent/grabLastSentEmail/...

See WebDriver module for general information on how to load parts of a framework module.

Example (acceptance.suite.yml)

actor: AcceptanceTester
modules:
    enabled:
        - WebDriver:
            url: http://127.0.0.1:8080/
            browser: firefox
        - Yii2:
            configFile: 'config/test.php'
            part: orm # allow to use AR methods
            transaction: false # don't wrap test in transaction
            cleanup: false # don't cleanup the fixtures
            entryScript: index-test.php

Fixtures

This module allows to use fixtures inside a test. There are two ways to do that. Fixtures can either be loaded with the haveFixtures method inside a test:

<?php
$I->haveFixtures(['posts' => PostsFixture::className()]);

or, if you need to load fixtures before the test, you can specify fixtures in the _fixtures method of a test case:

<?php
// inside Cest file or Codeception\TestCase\Unit
public function _fixtures()
{
    return ['posts' => PostsFixture::className()]
}

URL

With this module you can also use Yii2's URL format for all codeception commands that expect a URL:

<?php
$I->amOnPage(['site/view','page'=>'about']);
$I->amOnPage('index-test.php?site/index');
$I->amOnPage('http://localhost/index-test.php?site/index');
$I->sendAjaxPostRequest(['/user/update', 'id' => 1], ['UserForm[name]' => 'G.Hopper']);

Status

Maintainer: samdark Stability: stable

Table of Contents

Interfaces

ActiveRecord
MultiSession
PartedModule
Interface PartedModule

Properties

$aliases  : array<string|int, mixed>
Allows to rename actions
$client  : AbstractBrowser
$client  : Yii2
$excludeActions  : array<string|int, mixed>
Allows to explicitly exclude actions from module.
$headers  : array<string|int, string>
$includeInheritedActions  : bool
By setting it to false module wan't inherit methods of parent class.
$loadedFixtures  : array<string|int, FixturesStore>
$onlyActions  : array<string|int, mixed>
Allows to explicitly set what methods have this class.
$backupConfig  : mixed
$config  : array<string|int, mixed>
Application config file must be set.
$crawler  : Crawler
$defaultCookieParameters  : array<string, string>|array<string, bool>|array<string, null>
$forms  : array<string|int, mixed>|array<string|int, Form>
$internalDomains  : mixed
$moduleContainer  : ModuleContainer
$requiredFields  : mixed
$storage  : mixed
$baseUrl  : mixed
$connectionWatcher  : ConnectionWatcher
Helper to manage database connections
$server  : array<string|int, mixed>
$transactionForcer  : TransactionForcer
Helper to force database transaction

Methods

__construct()  : mixed
Module constructor.
_after()  : mixed
**HOOK** executed after test
_afterStep()  : mixed
**HOOK** executed after step
_afterSuite()  : mixed
**HOOK** executed after suite
_backupSession()  : array<string|int, mixed>
Return the session content for future restoring. Implements MultiSession.
_before()  : mixed
**HOOK** executed before test
_beforeStep()  : mixed
**HOOK** executed before step
_beforeSuite()  : mixed
**HOOK** executed before suite
_closeSession()  : mixed
Close and dump a session. Implements MultiSession.
_conflicts()  : string
Returns class name or interface of module which can conflict with current.
_failed()  : mixed
**HOOK** executed when test fails but before `_after`
_findElements()  : array<string|int, mixed>
Locates element using available Codeception locator types:
_getConfig()  : mixed
Get config values or specific config item.
_getCurrentUri()  : string
_getName()  : string
Returns a module name for a Module, a class name for Helper
_getResponseContent()  : string
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
_getResponseStatusCode()  : mixed
_hasRequiredFields()  : bool
Checks if a module has required fields
_initialize()  : mixed
**HOOK** triggered after module is created and configuration is loaded
_initializeSession()  : mixed
Initialize an empty session. Implements MultiSession.
_loadPage()  : mixed
Opens a page with arbitrary request parameters.
_loadSession()  : mixed
Restore a session. Implements MultiSession.
_parts()  : mixed
_reconfigure()  : mixed
Allows to redefine config for a specific test.
_request()  : string
Send custom request to a backend using method, uri, parameters, etc.
_resetConfig()  : mixed
Reverts config changed by `_reconfigure`
_savePageSource()  : mixed
Saves page source of to a file
_setConfig()  : mixed
Allows to define initial module config.
amHttpAuthenticated()  : mixed
Authenticates user for HTTP_AUTH
amLoggedInAs()  : mixed
Authenticates a user on a site without submitting a login form.
amOnPage()  : mixed
Opens the page for the given relative URI or route.
amOnRoute()  : mixed
Similar to `amOnPage` but accepts a route as first argument and params as second
attachFile()  : mixed
Attaches a file relative to the Codeception `_data` directory to the given file upload field.
checkOption()  : mixed
Ticks a checkbox. For radio buttons, use the `selectOption` method instead.
click()  : mixed
Perform a click on a link or a button, given by a locator.
createAndSetCsrfCookie()  : array<string|int, string>
Creates the CSRF Cookie.
deleteHeader()  : mixed
Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
dontSee()  : mixed
Checks that the current page doesn't contain the text specified (case insensitive).
dontSeeCheckboxIsChecked()  : mixed
Check that the specified checkbox is unchecked.
dontSeeCookie()  : mixed
Checks that there isn't a cookie with the given name.
dontSeeCurrentUrlEquals()  : mixed
Checks that the current URL doesn't equal the given string.
dontSeeCurrentUrlMatches()  : mixed
Checks that current url doesn't match the given regular expression.
dontSeeElement()  : mixed
Checks that the given element is invisible or not present on the page.
dontSeeEmailIsSent()  : mixed
Checks that no email was sent
dontSeeInCurrentUrl()  : mixed
Checks that the current URI doesn't contain the given string.
dontSeeInField()  : mixed
Checks that an input field or textarea doesn't contain the given value.
dontSeeInFormFields()  : mixed
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
dontSeeInSource()  : mixed
Checks that the current page contains the given string in its raw source code.
dontSeeInTitle()  : mixed
Checks that the page title does not contain the given string.
dontSeeLink()  : mixed
Checks that the page doesn't contain a link with the given string.
dontSeeOptionIsSelected()  : mixed
Checks that the given option is not selected.
dontSeeRecord()  : mixed
Checks that a record does not exist in the database.
dontSeeResponseCodeIs()  : mixed
Checks that response code is equal to value provided.
fillField()  : mixed
Fills a text field or textarea with the given string.
followRedirect()  : mixed
Follow pending redirect if there is one.
getInternalDomains()  : array<string|int, mixed>
Returns a list of regex patterns for recognized domain names
grabAttributeFrom()  : mixed
Grabs the value of the given attribute value from the given element.
grabComponent()  : mixed
Gets a component from the Yii container. Throws an exception if the component is not available
grabCookie()  : mixed
Grabs a cookie value.
grabFixture()  : mixed
Gets a fixture by name.
grabFixtures()  : array<string|int, mixed>
Returns all loaded fixtures.
grabFromCurrentUrl()  : mixed
Executes the given regular expression against the current URI and returns the first capturing group.
grabLastSentEmail()  : mixed
Returns the last sent email:
grabMultiple()  : array<string|int, string>
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
grabPageSource()  : string
Grabs current page source code.
grabRecord()  : mixed
Retrieves a record from the database
grabSentEmails()  : array<string|int, mixed>
Returns array of all sent email messages.
grabTextFrom()  : mixed
Finds and returns the text contents of the given element.
grabValueFrom()  : array<string|int, mixed>|mixed|null|string
Finds the value for the given form field.
haveFixtures()  : mixed
Creates and loads fixtures from a config.
haveHttpHeader()  : mixed
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
haveRecord()  : mixed
Inserts a record into the database.
haveServerParameter()  : mixed
Sets SERVER parameter valid for all next requests.
makeHtmlSnapshot()  : mixed
Use this method within an [interactive pause](https://codeception.com/docs/02-GettingStarted#Interactive-Pause) to save the HTML source code of the current page.
moveBack()  : mixed
Moves back in history.
resetCookie()  : mixed
Unsets cookie with the given name.
see()  : mixed
Checks that the current page contains the given string (case insensitive).
seeCheckboxIsChecked()  : mixed
Checks that the specified checkbox is checked.
seeCookie()  : mixed
Checks that a cookie with the given name is set.
seeCurrentUrlEquals()  : mixed
Checks that the current URL is equal to the given string.
seeCurrentUrlMatches()  : mixed
Checks that the current URL matches the given regular expression.
seeElement()  : mixed
Checks that the given element exists on the page and is visible.
seeEmailIsSent()  : mixed
Checks that an email is sent.
seeInCurrentUrl()  : mixed
Checks that current URI contains the given string.
seeInField()  : mixed
Checks that the given input field or textarea *equals* (i.e. not just contains) the given value.
seeInFormFields()  : mixed
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
seeInSource()  : mixed
Checks that the current page contains the given string in its raw source code.
seeInTitle()  : mixed
Checks that the page title contains the given string.
seeLink()  : mixed
Checks that there's a link with the specified text.
seeNumberOfElements()  : mixed
Checks that there are a certain number of elements matched by the given locator on the page.
seeOptionIsSelected()  : mixed
Checks that the given option is selected.
seePageNotFound()  : mixed
Asserts that current page has 404 response status code.
seeRecord()  : mixed
Checks that a record exists in the database.
seeResponseCodeIs()  : mixed
Checks that response code is equal to value provided.
seeResponseCodeIsBetween()  : mixed
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
seeResponseCodeIsClientError()  : mixed
Checks that the response code is 4xx
seeResponseCodeIsRedirection()  : mixed
Checks that the response code 3xx
seeResponseCodeIsServerError()  : mixed
Checks that the response code is 5xx
seeResponseCodeIsSuccessful()  : mixed
Checks that the response code 2xx
selectOption()  : mixed
Selects an option in a select tag or in radio button group.
sendAjaxGetRequest()  : mixed
Sends an ajax GET request with the passed parameters.
sendAjaxPostRequest()  : mixed
Sends an ajax POST request with the passed parameters.
sendAjaxRequest()  : mixed
Sends an ajax request, using the passed HTTP method.
setCookie()  : mixed
Sets a cookie and, if validation is enabled, signs it.
setMaxRedirects()  : mixed
Sets the maximum number of redirects that the Client can follow.
setServerParameters()  : mixed
Sets SERVER parameters valid for all next requests.
startFollowingRedirects()  : mixed
Enables automatic redirects to be followed by the client.
stopFollowingRedirects()  : mixed
Prevents automatic redirects to be followed by the client.
submitForm()  : mixed
Submits the given form on the page, with the given form values. Pass the form field's values as an array in the second parameter.
switchToIframe()  : mixed
Switch to iframe or frame on the page.
uncheckOption()  : mixed
Unticks a checkbox.
assert()  : mixed
assertDomContains()  : mixed
assertDomNotContains()  : mixed
assertFileNotExists()  : mixed
Asserts that a file does not exist.
assertGreaterOrEquals()  : mixed
Asserts that a value is greater than or equal to another value.
assertIsEmpty()  : mixed
Asserts that a variable is empty.
assertLessOrEquals()  : mixed
Asserts that a value is smaller than or equal to another value.
assertNot()  : mixed
assertNotRegExp()  : mixed
Asserts that a string does not match a given regular expression.
assertPageContains()  : mixed
assertPageNotContains()  : mixed
assertPageSourceContains()  : mixed
assertPageSourceNotContains()  : mixed
assertRegExp()  : mixed
Asserts that a string matches a given regular expression.
assertThatItsNot()  : mixed
Evaluates a PHPUnit\Framework\Constraint matcher object.
clickByLocator()  : bool
clientRequest()  : mixed
To support to use the behavior of urlManager component for the methods like this: amOnPage(), sendAjaxRequest() and etc.
configureClient()  : mixed
debug()  : mixed
Print debug message to the screen.
debugCookieJar()  : mixed
debugResponse()  : mixed
debugSection()  : mixed
Print debug message with a title
filterByAttributes()  : mixed
filterByCSS()  : Crawler
filterByXPath()  : Crawler
findRecord()  : mixed
getAbsoluteUrlFor()  : string
Returns an absolute URL for the passed URI with the current URL as the base path.
getFieldByLabelOrCss()  : Crawler
getFieldsByLabelOrCss()  : Crawler
getFormFor()  : Form
Returns the DomCrawler\Form object for the form pointed to by $node or its closes form parent.
getFormPhpValues()  : array<string|int, mixed>
getFormUrl()  : string
Returns the form action's absolute URL.
getFormValuesFor()  : array<string|int, mixed>
Returns an array of name => value pairs for the passed form.
getInputValue()  : array<string|int, mixed>|string
Get the values of a set of input fields.
getModule()  : Module
Get another module by its name:
getModules()  : array<string|int, mixed>
Get all enabled modules
getNormalizedResponseContent()  : string
getResponseStatusCode()  : mixed
getSubmissionFormFieldName()  : string
Strips out one pair of trailing square brackets from a field's name.
getValueAndTextFromField()  : array<string|int, mixed>|string
Get the values of a set of fields and also the texts of selected options.
hasModule()  : bool
Checks that module is enabled.
isInternalDomain()  : bool
match()  : Crawler
matchFormField()  : FormField
matchOption()  : string
matchSelectedOption()  : Crawler
onReconfigure()  : mixed
Module configuration changed inside a test.
proceedCheckOption()  : ChoiceFormField
proceedSeeInField()  : mixed
proceedSeeInFormFields()  : mixed
proceedSubmitForm()  : mixed
Submits the form currently selected in the passed SymfonyCrawler, after setting any values passed in $params and setting the value of the passed button name.
pushFormField()  : void
Map an array element passed to seeInFormFields to its corresponding field, recursing through array values if the field is not found.
recreateClient()  : mixed
Instantiates the client based on module configuration
redirectIfNecessary()  : Crawler
rollbackTransactions()  : mixed
scalarizeArray()  : mixed
setCheckboxBoolValues()  : array<string|int, mixed>
Replaces boolean values in $params with the corresponding field's value for checkbox form fields.
setCookiesFromOptions()  : mixed
shortenMessage()  : string
Short text message to an amount of chars
startTransactions()  : mixed
strictMatch()  : Crawler
validateConfig()  : mixed
Validates current config for required fields and required packages.
clickButton()  : bool
Clicks the link or submits the form when the button is clicked
defineConstants()  : mixed
getBaseUrl()  : mixed
getCrawler()  : Crawler
getFormFromCrawler()  : Form
Returns a crawler Form object for the form pointed to by the passed SymfonyCrawler.
getRunningClient()  : mixed
initServerGlobal()  : mixed
Adds the required server params.
loadFixtures()  : mixed
load fixtures before db transaction
openHrefFromDomNode()  : mixed
retrieveBaseUrl()  : string
stringifySelector()  : mixed

Properties

$aliases

Allows to rename actions

public static array<string|int, mixed> $aliases = []

$excludeActions

Allows to explicitly exclude actions from module.

public static array<string|int, mixed> $excludeActions = []

$includeInheritedActions

By setting it to false module wan't inherit methods of parent class.

public static bool $includeInheritedActions = true

$onlyActions

Allows to explicitly set what methods have this class.

public static array<string|int, mixed> $onlyActions = []

$backupConfig

protected mixed $backupConfig = []

$config

Application config file must be set.

protected array<string|int, mixed> $config = ['fixturesMethod' => '_fixtures', 'cleanup' => true, 'ignoreCollidingDSN' => false, 'transaction' => true, 'entryScript' => '', 'entryUrl' => 'http://localhost/index-test.php', 'responseCleanMethod' => \Codeception\Lib\Connector\Yii2::CLEAN_CLEAR, 'requestCleanMethod' => \Codeception\Lib\Connector\Yii2::CLEAN_RECREATE, 'recreateComponents' => [], 'recreateApplication' => false, 'closeSessionOnRecreateApplication' => true, 'applicationClass' => null]

$defaultCookieParameters

protected array<string, string>|array<string, bool>|array<string, null> $defaultCookieParameters = ['expires' => null, 'path' => '/', 'domain' => '', 'secure' => false]

$forms

protected array<string|int, mixed>|array<string|int, Form> $forms = []

$requiredFields

protected mixed $requiredFields = ['configFile']

$storage

protected mixed $storage = []

$server

private array<string|int, mixed> $server

The contents of $_SERVER upon initialization of this object. This is only used to restore it upon object destruction. It MUST not be used anywhere else.

Methods

__construct()

Module constructor.

public __construct(ModuleContainer $moduleContainer[, array<string|int, mixed>|null $config = null ]) : mixed

Requires module container (to provide access between modules of suite) and config.

Parameters
$moduleContainer : ModuleContainer
$config : array<string|int, mixed>|null = null

_afterStep()

**HOOK** executed after step

public _afterStep(Step $step) : mixed
Parameters
$step : Step

_afterSuite()

**HOOK** executed after suite

public _afterSuite() : mixed

_backupSession()

Return the session content for future restoring. Implements MultiSession.

public _backupSession() : array<string|int, mixed>
Return values
array<string|int, mixed>

backup data

_beforeStep()

**HOOK** executed before step

public _beforeStep(Step $step) : mixed
Parameters
$step : Step

_beforeSuite()

**HOOK** executed before suite

public _beforeSuite([array<string|int, mixed> $settings = [] ]) : mixed
Parameters
$settings : array<string|int, mixed> = []

_closeSession()

Close and dump a session. Implements MultiSession.

public _closeSession([mixed $session = null ]) : mixed
Parameters
$session : mixed = null

_conflicts()

Returns class name or interface of module which can conflict with current.

public _conflicts() : string
Return values
string

_findElements()

Locates element using available Codeception locator types:

public _findElements(mixed $locator) : array<string|int, mixed>
  • XPath
  • CSS
  • Strict Locator

Use it in Helpers or GroupObject or Extension classes:

<?php
$els = $this->getModule('{{MODULE_NAME}}')->_findElements('.items');
$els = $this->getModule('{{MODULE_NAME}}')->_findElements(['name' => 'username']);

$editLinks = $this->getModule('{{MODULE_NAME}}')->_findElements(['link' => 'Edit']);
// now you can iterate over $editLinks and check that all them have valid hrefs

WebDriver module returns Facebook\WebDriver\Remote\RemoteWebElement instances PhpBrowser and Framework modules return Symfony\Component\DomCrawler\Crawler instances

Parameters
$locator : mixed
Return values
array<string|int, mixed>

of interactive elements

_getConfig()

Get config values or specific config item.

public _getConfig([mixed $key = null ]) : mixed
Parameters
$key : mixed = null
Return values
mixed

the config item's value or null if it doesn't exist

_getName()

Returns a module name for a Module, a class name for Helper

public _getName() : string
Return values
string

_getResponseContent()

Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.

public _getResponseContent() : string
APIYes
<?php
// in Helper class
public function seeResponseContains($text)
{
   $this->assertStringContainsString($text, $this->getModule('{{MODULE_NAME}}')->_getResponseContent(), "response contains");
}
Tags
throws
ModuleException
Return values
string

_getResponseStatusCode()

public _getResponseStatusCode() : mixed

_hasRequiredFields()

Checks if a module has required fields

public _hasRequiredFields() : bool
Return values
bool

_initialize()

**HOOK** triggered after module is created and configuration is loaded

public _initialize() : mixed

_initializeSession()

Initialize an empty session. Implements MultiSession.

public _initializeSession() : mixed

_loadPage()

Opens a page with arbitrary request parameters.

public _loadPage(string $method, string $uri[, array<string|int, mixed> $parameters = [] ][, array<string|int, mixed> $files = [] ][, array<string|int, mixed> $server = [] ][, string $content = null ]) : mixed
APIYes

Useful for testing multi-step forms on a specific step.

<?php
// in Helper class
public function openCheckoutFormStep2($orderId) {
    $this->getModule('{{MODULE_NAME}}')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]);
}
Parameters
$method : string
$uri : string
$parameters : array<string|int, mixed> = []
$files : array<string|int, mixed> = []
$server : array<string|int, mixed> = []
$content : string = null

_loadSession()

Restore a session. Implements MultiSession.

public _loadSession(mixed $session) : mixed
Parameters
$session : mixed

_parts()

public _parts() : mixed

_reconfigure()

Allows to redefine config for a specific test.

public _reconfigure(mixed $config) : mixed

Config is restored at the end of a test.

<?php
// cleanup DB only for specific group of tests
public function _before(Test $test) {
    if (in_array('cleanup', $test->getMetadata()->getGroups()) {
        $this->getModule('Db')->_reconfigure(['cleanup' => true]);
    }
}
Parameters
$config : mixed
Tags
throws
ModuleConfigException
throws
ModuleException

_request()

Send custom request to a backend using method, uri, parameters, etc.

public _request(string $method, string $uri[, array<string|int, mixed> $parameters = [] ][, array<string|int, mixed> $files = [] ][, array<string|int, mixed> $server = [] ][, string $content = null ]) : string
APIYes

Use it in Helpers to create special request actions, like accessing API Returns a string with response body.

<?php
// in Helper class
public function createUserByApi($name) {
    $userData = $this->getModule('{{MODULE_NAME}}')->_request('POST', '/api/v1/users', ['name' => $name]);
    $user = json_decode($userData);
    return $user->id;
}

Does not load the response into the module so you can't interact with response page (click, fill forms). To load arbitrary page for interaction, use _loadPage method.

Parameters
$method : string
$uri : string
$parameters : array<string|int, mixed> = []
$files : array<string|int, mixed> = []
$server : array<string|int, mixed> = []
$content : string = null
Tags
throws
ExternalUrlException
see

_loadPage

Return values
string

_resetConfig()

Reverts config changed by `_reconfigure`

public _resetConfig() : mixed

_savePageSource()

Saves page source of to a file

public _savePageSource(mixed $filename) : mixed
$this->getModule('{{MODULE_NAME}}')->_savePageSource(codecept_output_dir().'page.html');
Parameters
$filename : mixed

_setConfig()

Allows to define initial module config.

public _setConfig(mixed $config) : mixed

Can be used in _beforeSuite hook of Helpers or Extensions

<?php
public function _beforeSuite($settings = []) {
    $this->getModule('otherModule')->_setConfig($this->myOtherConfig);
}
Parameters
$config : mixed
Tags
throws
ModuleConfigException
throws
ModuleException

amHttpAuthenticated()

Authenticates user for HTTP_AUTH

public amHttpAuthenticated(string $username, string $password) : mixed
Parameters
$username : string
$password : string

amLoggedInAs()

Authenticates a user on a site without submitting a login form.

public amLoggedInAs(mixed $user) : mixed

Use it for fast pragmatic authorization in functional tests.

<?php
// User is found by id
$I->amLoggedInAs(1);

// User object is passed as parameter
$admin = \app\models\User::findByUsername('admin');
$I->amLoggedInAs($admin);

Requires the user component to be enabled and configured.

Parameters
$user : mixed
Tags
throws
ModuleException

amOnPage()

Opens the page for the given relative URI or route.

public amOnPage(string|array<string|int, mixed> $page) : mixed
<?php
// opens front page
$I->amOnPage('/');
// opens /register page
$I->amOnPage('/register');
// opens customer view page for id 25
$I->amOnPage(['customer/view', 'id' => 25]);
Parameters
$page : string|array<string|int, mixed>

the URI or route in array format

amOnRoute()

Similar to `amOnPage` but accepts a route as first argument and params as second

public amOnRoute(string $route[, array<string|int, mixed> $params = [] ]) : mixed
$I->amOnRoute('site/view', ['page' => 'about']);
Parameters
$route : string

A route

$params : array<string|int, mixed> = []

Additional route parameters

attachFile()

Attaches a file relative to the Codeception `_data` directory to the given file upload field.

public attachFile(mixed $field, mixed $filename) : mixed
<?php
// file is stored in 'tests/_data/prices.xls'
$I->attachFile('input[@type="file"]', 'prices.xls');
?>
Parameters
$field : mixed
$filename : mixed

checkOption()

Ticks a checkbox. For radio buttons, use the `selectOption` method instead.

public checkOption(mixed $option) : mixed
<?php
$I->checkOption('#agree');
?>
Parameters
$option : mixed

click()

Perform a click on a link or a button, given by a locator.

public click(mixed $link[, mixed $context = null ]) : mixed

If a fuzzy locator is given, the page will be searched for a button, link, or image matching the locator string. For buttons, the "value" attribute, "name" attribute, and inner text are searched. For links, the link text is searched. For images, the "alt" attribute and inner text of any parent links are searched.

The second parameter is a context (CSS or XPath locator) to narrow the search.

Note that if the locator matches a button of type submit, the form will be submitted.

<?php
// simple link
$I->click('Logout');
// button of form
$I->click('Submit');
// CSS button
$I->click('#form input[type=submit]');
// XPath
$I->click('//form/*[@type="submit"]');
// link in context
$I->click('Logout', '#nav');
// using strict locator
$I->click(['link' => 'Login']);
?>
Parameters
$link : mixed
$context : mixed = null

createAndSetCsrfCookie()

Creates the CSRF Cookie.

public createAndSetCsrfCookie(string $val) : array<string|int, string>
Parameters
$val : string

The value of the CSRF token

Return values
array<string|int, string>

Returns an array containing the name of the CSRF param and the masked CSRF token.

deleteHeader()

Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.

public deleteHeader(string $name) : mixed

Example:

<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');
// ...
$I->deleteHeader('X-Requested-With');
$I->amOnPage('some-other-page.php');
Parameters
$name : string

the name of the header to delete.

dontSee()

Checks that the current page doesn't contain the text specified (case insensitive).

public dontSee(mixed $text[, mixed $selector = null ]) : mixed

Give a locator as the second parameter to match a specific region.

<?php
$I->dontSee('Login');                         // I can suppose user is already logged in
$I->dontSee('Sign Up','h1');                  // I can suppose it's not a signup page
$I->dontSee('Sign Up','//body/h1');           // with XPath
$I->dontSee('Sign Up', ['css' => 'body h1']); // with strict CSS locator

Note that the search is done after stripping all HTML tags from the body, so $I->dontSee('strong') will fail on strings like:

  • <p>I am Stronger than thou</p>
  • <script>document.createElement('strong');</script>

But will ignore strings like:

  • <strong>Home</strong>
  • <div class="strong">Home</strong>
  • <!-- strong -->

For checking the raw source code, use seeInSource().

Parameters
$text : mixed
$selector : mixed = null

optional

dontSeeCheckboxIsChecked()

Check that the specified checkbox is unchecked.

public dontSeeCheckboxIsChecked(mixed $checkbox) : mixed
<?php
$I->dontSeeCheckboxIsChecked('#agree'); // I suppose user didn't agree to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user didn't check the first checkbox in form.
?>
Parameters
$checkbox : mixed

dontSeeCookie()

Checks that there isn't a cookie with the given name.

public dontSeeCookie(mixed $cookie[, array<string|int, mixed> $params = [] ]) : mixed

You can set additional cookie params like domain, path as array passed in last argument.

Parameters
$cookie : mixed
$params : array<string|int, mixed> = []

dontSeeCurrentUrlEquals()

Checks that the current URL doesn't equal the given string.

public dontSeeCurrentUrlEquals(mixed $uri) : mixed

Unlike dontSeeInCurrentUrl, this only matches the full URL.

<?php
// current url is not root
$I->dontSeeCurrentUrlEquals('/');
?>
Parameters
$uri : mixed

dontSeeCurrentUrlMatches()

Checks that current url doesn't match the given regular expression.

public dontSeeCurrentUrlMatches(mixed $uri) : mixed
<?php
// to match root url
$I->dontSeeCurrentUrlMatches('~^/users/(\d+)~');
?>
Parameters
$uri : mixed

dontSeeElement()

Checks that the given element is invisible or not present on the page.

public dontSeeElement(mixed $selector[, mixed $attributes = [] ]) : mixed

You can also specify expected attributes of this element.

<?php
$I->dontSeeElement('.error');
$I->dontSeeElement('//form/input[1]');
$I->dontSeeElement('input', ['name' => 'login']);
$I->dontSeeElement('input', ['value' => '123456']);
?>
Parameters
$selector : mixed
$attributes : mixed = []

dontSeeEmailIsSent()

Checks that no email was sent

public dontSeeEmailIsSent() : mixed
Tags
part

email

dontSeeInCurrentUrl()

Checks that the current URI doesn't contain the given string.

public dontSeeInCurrentUrl(mixed $uri) : mixed
<?php
$I->dontSeeInCurrentUrl('/users/');
?>
Parameters
$uri : mixed

dontSeeInField()

Checks that an input field or textarea doesn't contain the given value.

public dontSeeInField(mixed $field, mixed $value) : mixed

For fuzzy locators, the field is matched by label text, CSS and XPath.

<?php
$I->dontSeeInField('Body','Type your comment here');
$I->dontSeeInField('form textarea[name=body]','Type your comment here');
$I->dontSeeInField('form input[type=hidden]','hidden_value');
$I->dontSeeInField('#searchform input','Search');
$I->dontSeeInField('//form/*[@name=search]','Search');
$I->dontSeeInField(['name' => 'search'], 'Search');
?>
Parameters
$field : mixed
$value : mixed

dontSeeInFormFields()

Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.

public dontSeeInFormFields(mixed $formSelector, array<string|int, mixed> $params) : mixed
<?php
$I->dontSeeInFormFields('form[name=myform]', [
     'input1' => 'non-existent value',
     'input2' => 'other non-existent value',
]);
?>

To check that an element hasn't been assigned any one of many values, an array can be passed as the value:

<?php
$I->dontSeeInFormFields('.form-class', [
     'fieldName' => [
         'This value shouldn\'t be set',
         'And this value shouldn\'t be set',
     ],
]);
?>

Additionally, checkbox values can be checked with a boolean.

<?php
$I->dontSeeInFormFields('#form-id', [
     'checkbox1' => true,        // fails if checked
     'checkbox2' => false,       // fails if unchecked
]);
?>
Parameters
$formSelector : mixed
$params : array<string|int, mixed>

dontSeeInSource()

Checks that the current page contains the given string in its raw source code.

public dontSeeInSource(mixed $raw) : mixed
<?php
$I->dontSeeInSource('<h1>Green eggs &amp; ham</h1>');
Parameters
$raw : mixed

dontSeeInTitle()

Checks that the page title does not contain the given string.

public dontSeeInTitle(mixed $title) : mixed
Parameters
$title : mixed

Checks that the page doesn't contain a link with the given string.

public dontSeeLink(mixed $text[, mixed $url = '' ]) : mixed

If the second parameter is given, only links with a matching "href" attribute will be checked.

<?php
$I->dontSeeLink('Logout'); // I suppose user is not logged in
$I->dontSeeLink('Checkout now', '/store/cart.php');
?>
Parameters
$text : mixed
$url : mixed = ''

optional

dontSeeOptionIsSelected()

Checks that the given option is not selected.

public dontSeeOptionIsSelected(mixed $selector, mixed $optionText) : mixed
<?php
$I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
Parameters
$selector : mixed
$optionText : mixed

dontSeeRecord()

Checks that a record does not exist in the database.

public dontSeeRecord(mixed $model[, array<string|int, mixed> $attributes = [] ]) : mixed
$I->dontSeeRecord('app\models\User', array('name' => 'davert'));
Parameters
$model : mixed
$attributes : array<string|int, mixed> = []
Tags
part

orm

dontSeeResponseCodeIs()

Checks that response code is equal to value provided.

public dontSeeResponseCodeIs(int $code) : mixed
<?php
$I->dontSeeResponseCodeIs(200);

// recommended \Codeception\Util\HttpCode
$I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
Parameters
$code : int

fillField()

Fills a text field or textarea with the given string.

public fillField(mixed $field, mixed $value) : mixed
<?php
$I->fillField("//input[@type='text']", "Hello World!");
$I->fillField(['name' => 'email'], 'jon@example.com');
?>
Parameters
$field : mixed
$value : mixed

followRedirect()

Follow pending redirect if there is one.

public followRedirect() : mixed
<?php
$I->followRedirect();

getInternalDomains()

Returns a list of regex patterns for recognized domain names

public getInternalDomains() : array<string|int, mixed>
Return values
array<string|int, mixed>

grabAttributeFrom()

Grabs the value of the given attribute value from the given element.

public grabAttributeFrom(mixed $cssOrXpath, mixed $attribute) : mixed

Fails if element is not found.

<?php
$I->grabAttributeFrom('#tooltip', 'title');
?>
Parameters
$cssOrXpath : mixed
$attribute : mixed

grabComponent()

Gets a component from the Yii container. Throws an exception if the component is not available

public grabComponent(mixed $component) : mixed
<?php
$mailer = $I->grabComponent('mailer');
Parameters
$component : mixed
Tags
throws
ModuleException
deprecated

in your tests you can use \Yii::$app directly.

grabCookie()

Grabs a cookie value.

public grabCookie(mixed $cookie[, array<string|int, mixed> $params = [] ]) : mixed

You can set additional cookie params like domain, path in array passed as last argument. If the cookie is set by an ajax request (XMLHttpRequest), there might be some delay caused by the browser, so try $I->wait(0.1).

Parameters
$cookie : mixed
$params : array<string|int, mixed> = []

grabFixture()

Gets a fixture by name.

public grabFixture(mixed $name[, mixed $index = null ]) : mixed

Returns a Fixture instance. If a fixture is an instance of \yii\test\BaseActiveFixture a second parameter can be used to return a specific model:

<?php
$I->haveFixtures(['users' => UserFixture::className()]);

$users = $I->grabFixture('users');

// get first user by key, if a fixture is an instance of ActiveFixture
$user = $I->grabFixture('users', 'user1');
Parameters
$name : mixed
$index : mixed = null
Tags
throws
ModuleException

if the fixture is not found

part

fixtures

grabFixtures()

Returns all loaded fixtures.

public grabFixtures() : array<string|int, mixed>

Array of fixture instances

Tags
part

fixtures

Return values
array<string|int, mixed>

grabFromCurrentUrl()

Executes the given regular expression against the current URI and returns the first capturing group.

public grabFromCurrentUrl([mixed $uri = null ]) : mixed

If no parameters are provided, the full URI is returned.

<?php
$user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~');
$uri = $I->grabFromCurrentUrl();
?>
Parameters
$uri : mixed = null

optional

grabLastSentEmail()

Returns the last sent email:

public grabLastSentEmail() : mixed
<?php
$I->seeEmailIsSent();
$message = $I->grabLastSentEmail();
$I->assertEquals('admin@site,com', $message->getTo());
Tags
part

email

grabMultiple()

Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.

public grabMultiple(mixed $cssOrXpath[, mixed $attribute = null ]) : array<string|int, string>
<a href="#first">First</a>
<a href="#second">Second</a>
<a href="#third">Third</a>
<?php
// would return ['First', 'Second', 'Third']
$aLinkText = $I->grabMultiple('a');

// would return ['#first', '#second', '#third']
$aLinks = $I->grabMultiple('a', 'href');
?>
Parameters
$cssOrXpath : mixed
$attribute : mixed = null
Return values
array<string|int, string>

grabPageSource()

Grabs current page source code.

public grabPageSource() : string
Tags
throws
ModuleException

if no page was opened.

Return values
string

Current page source code.

grabRecord()

Retrieves a record from the database

public grabRecord(mixed $model[, array<string|int, mixed> $attributes = [] ]) : mixed
$category = $I->grabRecord('app\models\User', array('name' => 'davert'));
Parameters
$model : mixed
$attributes : array<string|int, mixed> = []
Tags
part

orm

grabSentEmails()

Returns array of all sent email messages.

public grabSentEmails() : array<string|int, mixed>

Each message implements the yii\mail\MessageInterface interface. Useful to perform additional checks using the Asserts module:

<?php
$I->seeEmailIsSent();
$messages = $I->grabSentEmails();
$I->assertEquals('admin@site,com', $messages[0]->getTo());
Tags
part

email

throws
ModuleException
Return values
array<string|int, mixed>

grabTextFrom()

Finds and returns the text contents of the given element.

public grabTextFrom(mixed $cssOrXPathOrRegex) : mixed

If a fuzzy locator is used, the element is found using CSS, XPath, and by matching the full page source by regular expression.

<?php
$heading = $I->grabTextFrom('h1');
$heading = $I->grabTextFrom('descendant-or-self::h1');
$value = $I->grabTextFrom('~<input value=(.*?)]~sgi'); // match with a regex
?>
Parameters
$cssOrXPathOrRegex : mixed

grabValueFrom()

Finds the value for the given form field.

public grabValueFrom(mixed $field) : array<string|int, mixed>|mixed|null|string
Parameters
$field : mixed
Return values
array<string|int, mixed>|mixed|null|string

haveFixtures()

Creates and loads fixtures from a config.

public haveFixtures(mixed $fixtures) : mixed

The signature is the same as for the fixtures() method of yii\test\FixtureTrait

<?php
$I->haveFixtures([
    'posts' => PostsFixture::className(),
    'user' => [
        'class' => UserFixture::className(),
        'dataFile' => '@tests/_data/models/user.php',
     ],
]);

Note: if you need to load fixtures before a test (probably before the cleanup transaction is started; cleanup option is true by default), you can specify the fixtures in the _fixtures() method of a test case

<?php
// inside Cest file or Codeception\TestCase\Unit
public function _fixtures(){
    return [
        'user' => [
            'class' => UserFixture::className(),
            'dataFile' => codecept_data_dir() . 'user.php'
        ]
    ];
}

instead of calling haveFixtures in Cest _before

Parameters
$fixtures : mixed
Tags
part

fixtures

haveHttpHeader()

Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.

public haveHttpHeader(string $name, string $value) : mixed

Example:

<?php
$I->haveHttpHeader('X-Requested-With', 'Codeception');
$I->amOnPage('test-headers.php');

To use special chars in Header Key use HTML Character Entities: Example: Header with underscore - 'Client_Id' should be represented as - 'Client_Id' or 'Client_Id'

<?php
$I->haveHttpHeader('Client&#95;Id', 'Codeception');
Parameters
$name : string

the name of the request header

$value : string

the value to set it to for subsequent requests

haveRecord()

Inserts a record into the database.

public haveRecord(mixed $model[, array<string|int, mixed> $attributes = [] ]) : mixed
<?php
$user_id = $I->haveRecord('app\models\User', array('name' => 'Davert'));
?>
Parameters
$model : mixed
$attributes : array<string|int, mixed> = []
Tags
part

orm

haveServerParameter()

Sets SERVER parameter valid for all next requests.

public haveServerParameter(string $name, string $value) : mixed
$I->haveServerParameter('name', 'value');
Parameters
$name : string
$value : string

makeHtmlSnapshot()

Use this method within an [interactive pause](https://codeception.com/docs/02-GettingStarted#Interactive-Pause) to save the HTML source code of the current page.

public makeHtmlSnapshot([mixed $name = null ]) : mixed
<?php
$I->makeHtmlSnapshot('edit_page');
// saved to: tests/_output/debug/edit_page.html
$I->makeHtmlSnapshot();
// saved to: tests/_output/debug/2017-05-26_14-24-11_4b3403665fea6.html
Parameters
$name : mixed = null

moveBack()

Moves back in history.

public moveBack([int $numberOfSteps = 1 ]) : mixed
Parameters
$numberOfSteps : int = 1

(default value 1)

resetCookie()

Unsets cookie with the given name.

public resetCookie(mixed $cookie[, array<string|int, mixed> $params = [] ]) : mixed

You can set additional cookie params like domain, path in array passed as last argument.

Parameters
$cookie : mixed
$params : array<string|int, mixed> = []

see()

Checks that the current page contains the given string (case insensitive).

public see(mixed $text[, mixed $selector = null ]) : mixed

You can specify a specific HTML element (via CSS or XPath) as the second parameter to only search within that element.

<?php
$I->see('Logout');                        // I can suppose user is logged in
$I->see('Sign Up', 'h1');                 // I can suppose it's a signup page
$I->see('Sign Up', '//body/h1');          // with XPath
$I->see('Sign Up', ['css' => 'body h1']); // with strict CSS locator

Note that the search is done after stripping all HTML tags from the body, so $I->see('strong') will return true for strings like:

  • <p>I am Stronger than thou</p>
  • <script>document.createElement('strong');</script>

But will not be true for strings like:

  • <strong>Home</strong>
  • <div class="strong">Home</strong>
  • <!-- strong -->

For checking the raw source code, use seeInSource().

Parameters
$text : mixed
$selector : mixed = null

optional

seeCheckboxIsChecked()

Checks that the specified checkbox is checked.

public seeCheckboxIsChecked(mixed $checkbox) : mixed
<?php
$I->seeCheckboxIsChecked('#agree'); // I suppose user agreed to terms
$I->seeCheckboxIsChecked('#signup_form input[type=checkbox]'); // I suppose user agreed to terms, If there is only one checkbox in form.
$I->seeCheckboxIsChecked('//form/input[@type=checkbox and @name=agree]');
?>
Parameters
$checkbox : mixed

seeCookie()

Checks that a cookie with the given name is set.

public seeCookie(mixed $cookie[, array<string|int, mixed> $params = [] ]) : mixed

You can set additional cookie params like domain, path as array passed in last argument.

<?php
$I->seeCookie('PHPSESSID');
?>
Parameters
$cookie : mixed
$params : array<string|int, mixed> = []

seeCurrentUrlEquals()

Checks that the current URL is equal to the given string.

public seeCurrentUrlEquals(mixed $uri) : mixed

Unlike seeInCurrentUrl, this only matches the full URL.

<?php
// to match root url
$I->seeCurrentUrlEquals('/');
?>
Parameters
$uri : mixed

seeCurrentUrlMatches()

Checks that the current URL matches the given regular expression.

public seeCurrentUrlMatches(mixed $uri) : mixed
<?php
// to match root url
$I->seeCurrentUrlMatches('~^/users/(\d+)~');
?>
Parameters
$uri : mixed

seeElement()

Checks that the given element exists on the page and is visible.

public seeElement(mixed $selector[, mixed $attributes = [] ]) : mixed

You can also specify expected attributes of this element.

<?php
$I->seeElement('.error');
$I->seeElement('//form/input[1]');
$I->seeElement('input', ['name' => 'login']);
$I->seeElement('input', ['value' => '123456']);

// strict locator in first arg, attributes in second
$I->seeElement(['css' => 'form input'], ['name' => 'login']);
?>
Parameters
$selector : mixed
$attributes : mixed = []

seeEmailIsSent()

Checks that an email is sent.

public seeEmailIsSent([int $num = null ]) : mixed
<?php
// check that at least 1 email was sent
$I->seeEmailIsSent();

// check that only 3 emails were sent
$I->seeEmailIsSent(3);
Parameters
$num : int = null
Tags
throws
ModuleException
part

email

seeInCurrentUrl()

Checks that current URI contains the given string.

public seeInCurrentUrl(mixed $uri) : mixed
<?php
// to match: /home/dashboard
$I->seeInCurrentUrl('home');
// to match: /users/1
$I->seeInCurrentUrl('/users/');
?>
Parameters
$uri : mixed

seeInField()

Checks that the given input field or textarea *equals* (i.e. not just contains) the given value.

public seeInField(mixed $field, mixed $value) : mixed

Fields are matched by label text, the "name" attribute, CSS, or XPath.

<?php
$I->seeInField('Body','Type your comment here');
$I->seeInField('form textarea[name=body]','Type your comment here');
$I->seeInField('form input[type=hidden]','hidden_value');
$I->seeInField('#searchform input','Search');
$I->seeInField('//form/*[@name=search]','Search');
$I->seeInField(['name' => 'search'], 'Search');
?>
Parameters
$field : mixed
$value : mixed

seeInFormFields()

Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.

public seeInFormFields(mixed $formSelector, array<string|int, mixed> $params) : mixed
<?php
$I->seeInFormFields('form[name=myform]', [
     'input1' => 'value',
     'input2' => 'other value',
]);
?>

For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:

<?php
$I->seeInFormFields('.form-class', [
     'multiselect' => [
         'value1',
         'value2',
     ],
     'checkbox[]' => [
         'a checked value',
         'another checked value',
     ],
]);
?>

Additionally, checkbox values can be checked with a boolean.

<?php
$I->seeInFormFields('#form-id', [
     'checkbox1' => true,        // passes if checked
     'checkbox2' => false,       // passes if unchecked
]);
?>

Pair this with submitForm for quick testing magic.

<?php
$form = [
     'field1' => 'value',
     'field2' => 'another value',
     'checkbox1' => true,
     // ...
];
$I->submitForm('//form[@id=my-form]', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('//form[@id=my-form]', $form);
?>
Parameters
$formSelector : mixed
$params : array<string|int, mixed>

seeInSource()

Checks that the current page contains the given string in its raw source code.

public seeInSource(mixed $raw) : mixed
<?php
$I->seeInSource('<h1>Green eggs &amp; ham</h1>');
Parameters
$raw : mixed

seeInTitle()

Checks that the page title contains the given string.

public seeInTitle(mixed $title) : mixed
<?php
$I->seeInTitle('Blog - Post #1');
?>
Parameters
$title : mixed

Checks that there's a link with the specified text.

public seeLink(mixed $text[, mixed $url = null ]) : mixed

Give a full URL as the second parameter to match links with that exact URL.

<?php
$I->seeLink('Logout'); // matches <a href="#">Logout</a>
$I->seeLink('Logout','/logout'); // matches <a href="/logout">Logout</a>
?>
Parameters
$text : mixed
$url : mixed = null

optional

seeNumberOfElements()

Checks that there are a certain number of elements matched by the given locator on the page.

public seeNumberOfElements(mixed $selector, mixed $expected) : mixed
<?php
$I->seeNumberOfElements('tr', 10);
$I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements
?>
Parameters
$selector : mixed
$expected : mixed

int or int[]

seeOptionIsSelected()

Checks that the given option is selected.

public seeOptionIsSelected(mixed $selector, mixed $optionText) : mixed
<?php
$I->seeOptionIsSelected('#form input[name=payment]', 'Visa');
?>
Parameters
$selector : mixed
$optionText : mixed

seePageNotFound()

Asserts that current page has 404 response status code.

public seePageNotFound() : mixed

seeRecord()

Checks that a record exists in the database.

public seeRecord(mixed $model[, array<string|int, mixed> $attributes = [] ]) : mixed
$I->seeRecord('app\models\User', array('name' => 'davert'));
Parameters
$model : mixed
$attributes : array<string|int, mixed> = []
Tags
part

orm

seeResponseCodeIs()

Checks that response code is equal to value provided.

public seeResponseCodeIs(int $code) : mixed
<?php
$I->seeResponseCodeIs(200);

// recommended \Codeception\Util\HttpCode
$I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
Parameters
$code : int

seeResponseCodeIsBetween()

Checks that response code is between a certain range. Between actually means [from <= CODE <= to]

public seeResponseCodeIsBetween(int $from, int $to) : mixed
Parameters
$from : int
$to : int

seeResponseCodeIsClientError()

Checks that the response code is 4xx

public seeResponseCodeIsClientError() : mixed

seeResponseCodeIsRedirection()

Checks that the response code 3xx

public seeResponseCodeIsRedirection() : mixed

seeResponseCodeIsServerError()

Checks that the response code is 5xx

public seeResponseCodeIsServerError() : mixed

seeResponseCodeIsSuccessful()

Checks that the response code 2xx

public seeResponseCodeIsSuccessful() : mixed

selectOption()

Selects an option in a select tag or in radio button group.

public selectOption(mixed $select, mixed $option) : mixed
<?php
$I->selectOption('form select[name=account]', 'Premium');
$I->selectOption('form input[name=payment]', 'Monthly');
$I->selectOption('//form/select[@name=account]', 'Monthly');
?>

Provide an array for the second argument to select multiple options:

<?php
$I->selectOption('Which OS do you use?', array('Windows','Linux'));
?>

Or provide an associative array for the second argument to specifically define which selection method should be used:

<?php
$I->selectOption('Which OS do you use?', array('text' => 'Windows')); // Only search by text 'Windows'
$I->selectOption('Which OS do you use?', array('value' => 'windows')); // Only search by value 'windows'
?>
Parameters
$select : mixed
$option : mixed

sendAjaxGetRequest()

Sends an ajax GET request with the passed parameters.

public sendAjaxGetRequest(mixed $uri[, mixed $params = [] ]) : mixed

See sendAjaxPostRequest()

Parameters
$uri : mixed
$params : mixed = []

sendAjaxPostRequest()

Sends an ajax POST request with the passed parameters.

public sendAjaxPostRequest(string $uri[, array<string|int, mixed> $params = [] ]) : mixed

The appropriate HTTP header is added automatically: X-Requested-With: XMLHttpRequest Example:

<?php
$I->sendAjaxPostRequest('/add-task', ['task' => 'lorem ipsum']);

Some frameworks (e.g. Symfony) create field names in the form of an "array": <input type="text" name="form[task]"> In this case you need to pass the fields like this:

<?php
$I->sendAjaxPostRequest('/add-task', ['form' => [
    'task' => 'lorem ipsum',
    'category' => 'miscellaneous',
]]);
Parameters
$uri : string
$params : array<string|int, mixed> = []

sendAjaxRequest()

Sends an ajax request, using the passed HTTP method.

public sendAjaxRequest(mixed $method, mixed $uri[, array<string|int, mixed> $params = [] ]) : mixed

See sendAjaxPostRequest() Example:

<?php
$I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
Parameters
$method : mixed
$uri : mixed
$params : array<string|int, mixed> = []

setCookie()

Sets a cookie and, if validation is enabled, signs it.

public setCookie(string $name, string $val[, array<string|int, mixed> $params = [] ]) : mixed
Parameters
$name : string

The name of the cookie

$val : string

The value of the cookie

$params : array<string|int, mixed> = []

Additional cookie params like domain, path, expires and secure.

setMaxRedirects()

Sets the maximum number of redirects that the Client can follow.

public setMaxRedirects(int $maxRedirects) : mixed
<?php
$I->setMaxRedirects(2);
Parameters
$maxRedirects : int

setServerParameters()

Sets SERVER parameters valid for all next requests.

public setServerParameters(array<string|int, mixed> $params) : mixed

this will remove old ones.

$I->setServerParameters([]);
Parameters
$params : array<string|int, mixed>

startFollowingRedirects()

Enables automatic redirects to be followed by the client.

public startFollowingRedirects() : mixed
<?php
$I->startFollowingRedirects();

stopFollowingRedirects()

Prevents automatic redirects to be followed by the client.

public stopFollowingRedirects() : mixed
<?php
$I->stopFollowingRedirects();

submitForm()

Submits the given form on the page, with the given form values. Pass the form field's values as an array in the second parameter.

public submitForm(mixed $selector, array<string|int, mixed> $params[, mixed $button = null ]) : mixed

Although this function can be used as a short-hand version of fillField(), selectOption(), click() etc. it has some important differences:

  • Only field names may be used, not CSS/XPath selectors nor field labels
  • If a field is sent to this function that does not exist on the page, it will silently be added to the HTTP request. This is helpful for testing some types of forms, but be aware that you will not get an exception like you would if you called fillField() or selectOption() with a missing field.

Fields that are not provided will be filled by their values from the page, or from any previous calls to fillField(), selectOption() etc. You don't need to click the 'Submit' button afterwards. This command itself triggers the request to form's action.

You can optionally specify which button's value to include in the request with the last parameter (as an alternative to explicitly setting its value in the second parameter), as button values are not otherwise included in the request.

Examples:

<?php
$I->submitForm('#login', [
    'login' => 'davert',
    'password' => '123456'
]);
// or
$I->submitForm('#login', [
    'login' => 'davert',
    'password' => '123456'
], 'submitButtonName');

For example, given this sample "Sign Up" form:

<form id="userForm">
    Login:
    <input type="text" name="user[login]" /><br/>
    Password:
    <input type="password" name="user[password]" /><br/>
    Do you agree to our terms?
    <input type="checkbox" name="user[agree]" /><br/>
    Subscribe to our newsletter?
    <input type="checkbox" name="user[newsletter]" value="1" checked="checked" /><br/>
    Select pricing plan:
    <select name="plan">
        <option value="1">Free</option>
        <option value="2" selected="selected">Paid</option>
    </select>
    <input type="submit" name="submitButton" value="Submit" />
</form>

You could write the following to submit it:

<?php
$I->submitForm(
    '#userForm',
    [
        'user' => [
            'login' => 'Davert',
            'password' => '123456',
            'agree' => true
        ]
    ],
    'submitButton'
);

Note that "2" will be the submitted value for the "plan" field, as it is the selected option.

To uncheck the pre-checked checkbox "newsletter", call $I->uncheckOption(['name' => 'user[newsletter]']); before, then submit the form as shown here (i.e. without the "newsletter" field in the $params array).

You can also emulate a JavaScript submission by not specifying any buttons in the third parameter to submitForm.

<?php
$I->submitForm(
    '#userForm',
    [
        'user' => [
            'login' => 'Davert',
            'password' => '123456',
            'agree' => true
        ]
    ]
);

This function works well when paired with seeInFormFields() for quickly testing CRUD interfaces and form validation logic.

<?php
$form = [
     'field1' => 'value',
     'field2' => 'another value',
     'checkbox1' => true,
     // ...
];
$I->submitForm('#my-form', $form, 'submitButton');
// $I->amOnPage('/path/to/form-page') may be needed
$I->seeInFormFields('#my-form', $form);

Parameter values can be set to arrays for multiple input fields of the same name, or multi-select combo boxes. For checkboxes, you can use either the string value or boolean true/false which will be replaced by the checkbox's value in the DOM.

<?php
$I->submitForm('#my-form', [
     'field1' => 'value',
     'checkbox' => [
         'value of first checkbox',
         'value of second checkbox',
     ],
     'otherCheckboxes' => [
         true,
         false,
         false
     ],
     'multiselect' => [
         'first option value',
         'second option value'
     ]
]);

Mixing string and boolean values for a checkbox's value is not supported and may produce unexpected results.

Field names ending in [] must be passed without the trailing square bracket characters, and must contain an array for its value. This allows submitting multiple values with the same name, consider:

<?php
// This will NOT work correctly
$I->submitForm('#my-form', [
    'field[]' => 'value',
    'field[]' => 'another value',  // 'field[]' is already a defined key
]);

The solution is to pass an array value:

<?php
// This way both values are submitted
$I->submitForm('#my-form', [
    'field' => [
        'value',
        'another value',
    ]
]);
Parameters
$selector : mixed
$params : array<string|int, mixed>
$button : mixed = null

switchToIframe()

Switch to iframe or frame on the page.

public switchToIframe(string $name) : mixed

Example:

<iframe name="another_frame" src="http://example.com">
<?php
# switch to iframe
$I->switchToIframe("another_frame");
Parameters
$name : string

uncheckOption()

Unticks a checkbox.

public uncheckOption(mixed $option) : mixed
<?php
$I->uncheckOption('#notify');
?>
Parameters
$option : mixed

assert()

protected assert(mixed $arguments[, bool $not = false ]) : mixed
Parameters
$arguments : mixed
$not : bool = false

assertDomContains()

protected assertDomContains(mixed $nodes, string $message[, mixed $text = '' ]) : mixed
Parameters
$nodes : mixed
$message : string
$text : mixed = ''

assertDomNotContains()

protected assertDomNotContains(mixed $nodes, string $message[, mixed $text = '' ]) : mixed
Parameters
$nodes : mixed
$message : string
$text : mixed = ''

assertFileNotExists()

Asserts that a file does not exist.

protected assertFileNotExists(string $filename[, string $message = '' ]) : mixed
Parameters
$filename : string
$message : string = ''

assertGreaterOrEquals()

Asserts that a value is greater than or equal to another value.

protected assertGreaterOrEquals(mixed $expected, mixed $actual[, string $message = '' ]) : mixed
Parameters
$expected : mixed
$actual : mixed
$message : string = ''

assertIsEmpty()

Asserts that a variable is empty.

protected assertIsEmpty(mixed $actual[, string $message = '' ]) : mixed
Parameters
$actual : mixed
$message : string = ''

assertLessOrEquals()

Asserts that a value is smaller than or equal to another value.

protected assertLessOrEquals(mixed $expected, mixed $actual[, string $message = '' ]) : mixed
Parameters
$expected : mixed
$actual : mixed
$message : string = ''

assertNot()

protected assertNot(mixed $arguments) : mixed
Parameters
$arguments : mixed

assertNotRegExp()

Asserts that a string does not match a given regular expression.

protected assertNotRegExp(string $pattern, string $string[, string $message = '' ]) : mixed
Parameters
$pattern : string
$string : string
$message : string = ''

assertPageContains()

protected assertPageContains(mixed $needle[, string $message = '' ]) : mixed
Parameters
$needle : mixed
$message : string = ''

assertPageNotContains()

protected assertPageNotContains(mixed $needle[, string $message = '' ]) : mixed
Parameters
$needle : mixed
$message : string = ''

assertPageSourceContains()

protected assertPageSourceContains(mixed $needle[, string $message = '' ]) : mixed
Parameters
$needle : mixed
$message : string = ''

assertPageSourceNotContains()

protected assertPageSourceNotContains(mixed $needle[, string $message = '' ]) : mixed
Parameters
$needle : mixed
$message : string = ''

assertRegExp()

Asserts that a string matches a given regular expression.

protected assertRegExp(string $pattern, string $string[, string $message = '' ]) : mixed
Parameters
$pattern : string
$string : string
$message : string = ''

assertThatItsNot()

Evaluates a PHPUnit\Framework\Constraint matcher object.

protected assertThatItsNot(mixed $value, Constraint $constraint[, string $message = '' ]) : mixed
Parameters
$value : mixed
$constraint : Constraint
$message : string = ''

clickByLocator()

protected clickByLocator(mixed $link) : bool
Parameters
$link : mixed
Return values
bool

clientRequest()

To support to use the behavior of urlManager component for the methods like this: amOnPage(), sendAjaxRequest() and etc.

protected clientRequest(mixed $method, mixed $uri[, array<string|int, mixed> $parameters = [] ][, array<string|int, mixed> $files = [] ][, array<string|int, mixed> $server = [] ][, null $content = null ][, bool $changeHistory = true ]) : mixed
Parameters
$method : mixed
$uri : mixed
$parameters : array<string|int, mixed> = []
$files : array<string|int, mixed> = []
$server : array<string|int, mixed> = []
$content : null = null
$changeHistory : bool = true

configureClient()

protected configureClient(array<string|int, mixed> $settings) : mixed
Parameters
$settings : array<string|int, mixed>

debug()

Print debug message to the screen.

protected debug(mixed $message) : mixed
Parameters
$message : mixed

debugResponse()

protected debugResponse(mixed $url) : mixed
Parameters
$url : mixed

debugSection()

Print debug message with a title

protected debugSection(mixed $title, mixed $message) : mixed
Parameters
$title : mixed
$message : mixed

filterByAttributes()

protected filterByAttributes(Crawler $nodes, array<string|int, mixed> $attributes) : mixed
Parameters
$nodes : Crawler
$attributes : array<string|int, mixed>

findRecord()

protected findRecord(string $model[, array<string|int, mixed> $attributes = [] ]) : mixed
Parameters
$model : string

Class name

$attributes : array<string|int, mixed> = []

getAbsoluteUrlFor()

Returns an absolute URL for the passed URI with the current URL as the base path.

protected getAbsoluteUrlFor(string $uri) : string
Parameters
$uri : string

the absolute or relative URI

Tags
throws
TestRuntimeException

if either the current URL or the passed URI can't be parsed

Return values
string

the absolute URL

getFieldByLabelOrCss()

protected getFieldByLabelOrCss(mixed $field) : Crawler
Parameters
$field : mixed
Return values
Crawler

getFieldsByLabelOrCss()

protected getFieldsByLabelOrCss(mixed $field) : Crawler
Parameters
$field : mixed
Return values
Crawler

getFormFor()

Returns the DomCrawler\Form object for the form pointed to by $node or its closes form parent.

protected getFormFor(Crawler $node) : Form
Parameters
$node : Crawler
Return values
Form

getFormPhpValues()

protected getFormPhpValues(array<string|int, mixed> $requestParams) : array<string|int, mixed>
Parameters
$requestParams : array<string|int, mixed>
Return values
array<string|int, mixed>

getFormUrl()

Returns the form action's absolute URL.

protected getFormUrl(Crawler $form) : string
Parameters
$form : Crawler
Tags
throws
TestRuntimeException

if either the current URL or the URI of the form's action can't be parsed

Return values
string

getFormValuesFor()

Returns an array of name => value pairs for the passed form.

protected getFormValuesFor(Form $form) : array<string|int, mixed>

For form fields containing a name ending in [], an array is created out of all field values with the given name.

Parameters
$form : Form

the form

Return values
array<string|int, mixed>

an array of name => value pairs

getInputValue()

Get the values of a set of input fields.

protected getInputValue(Crawler $input) : array<string|int, mixed>|string
Parameters
$input : Crawler
Return values
array<string|int, mixed>|string

getModule()

Get another module by its name:

protected getModule(mixed $name) : Module
<?php
$this->getModule('WebDriver')->_findElements('.items');
Parameters
$name : mixed
Tags
throws
ModuleException
Return values
Module

getModules()

Get all enabled modules

protected getModules() : array<string|int, mixed>
Return values
array<string|int, mixed>

getNormalizedResponseContent()

protected getNormalizedResponseContent() : string
Return values
string

getResponseStatusCode()

protected getResponseStatusCode() : mixed

getSubmissionFormFieldName()

Strips out one pair of trailing square brackets from a field's name.

protected getSubmissionFormFieldName(string $name) : string
Parameters
$name : string

the field name

Return values
string

the name after stripping trailing square brackets

getValueAndTextFromField()

Get the values of a set of fields and also the texts of selected options.

protected getValueAndTextFromField(Crawler $nodes) : array<string|int, mixed>|string
Parameters
$nodes : Crawler
Return values
array<string|int, mixed>|string

hasModule()

Checks that module is enabled.

protected hasModule(mixed $name) : bool
Parameters
$name : mixed
Return values
bool

isInternalDomain()

protected isInternalDomain(mixed $domain) : bool
Parameters
$domain : mixed
Return values
bool

matchFormField()

protected matchFormField(string $name, array<string|int, mixed> $form, FormField $dynamicField) : FormField
Parameters
$name : string
$form : array<string|int, mixed>
$dynamicField : FormField
Return values
FormField

matchOption()

protected matchOption(Crawler $field, string|array<string|int, mixed> $option) : string
Parameters
$field : Crawler
$option : string|array<string|int, mixed>
Return values
string

matchSelectedOption()

protected matchSelectedOption(mixed $select) : Crawler
Parameters
$select : mixed
Return values
Crawler

onReconfigure()

Module configuration changed inside a test.

protected onReconfigure() : mixed

We always re-create the application.

proceedSeeInField()

protected proceedSeeInField(Crawler $fields, mixed $value) : mixed
Parameters
$fields : Crawler
$value : mixed

proceedSeeInFormFields()

protected proceedSeeInFormFields(mixed $formSelector, array<string|int, mixed> $params, mixed $assertNot) : mixed
Parameters
$formSelector : mixed
$params : array<string|int, mixed>
$assertNot : mixed

proceedSubmitForm()

Submits the form currently selected in the passed SymfonyCrawler, after setting any values passed in $params and setting the value of the passed button name.

protected proceedSubmitForm(Crawler $frmCrawl, array<string|int, mixed> $params[, string $button = null ]) : mixed
Parameters
$frmCrawl : Crawler

the form to submit

$params : array<string|int, mixed>

additional parameter values to set on the form

$button : string = null

the name of a submit button in the form

pushFormField()

Map an array element passed to seeInFormFields to its corresponding field, recursing through array values if the field is not found.

protected pushFormField(array<string|int, mixed> &$fields, Crawler $form, string $name, mixed $values) : void
Parameters
$fields : array<string|int, mixed>

The previously found fields.

$form : Crawler

The form in which to search for fields.

$name : string

The field's name.

$values : mixed

recreateClient()

Instantiates the client based on module configuration

protected recreateClient() : mixed

redirectIfNecessary()

protected redirectIfNecessary(Crawler $result, int $maxRedirects, int $redirectCount) : Crawler
Parameters
$result : Crawler
$maxRedirects : int
$redirectCount : int
Return values
Crawler

rollbackTransactions()

protected rollbackTransactions() : mixed

scalarizeArray()

protected scalarizeArray(mixed $array) : mixed
Parameters
$array : mixed

setCheckboxBoolValues()

Replaces boolean values in $params with the corresponding field's value for checkbox form fields.

protected setCheckboxBoolValues(Crawler $form, array<string|int, mixed> $params) : array<string|int, mixed>

The function loops over all input checkbox fields, checking if a corresponding key is set in $params. If it is, and the value is boolean or an array containing booleans, the value(s) are replaced in the array with the real value of the checkbox, and the array is returned.

Parameters
$form : Crawler

the form to find checkbox elements

$params : array<string|int, mixed>

the parameters to be submitted

Return values
array<string|int, mixed>

the $params array after replacing bool values

setCookiesFromOptions()

protected setCookiesFromOptions() : mixed

shortenMessage()

Short text message to an amount of chars

protected shortenMessage(mixed $message[, mixed $chars = 150 ]) : string
Parameters
$message : mixed
$chars : mixed = 150
Return values
string

startTransactions()

protected startTransactions() : mixed

validateConfig()

Validates current config for required fields and required packages.

protected validateConfig() : mixed

clickButton()

Clicks the link or submits the form when the button is clicked

private clickButton(DOMNode $node) : bool
Parameters
$node : DOMNode
Return values
bool

clicked something

defineConstants()

private defineConstants() : mixed

getFormFromCrawler()

Returns a crawler Form object for the form pointed to by the passed SymfonyCrawler.

private getFormFromCrawler(Crawler $form) : Form

The returned form is an independent Crawler created to take care of the following issues currently experienced by Crawler's form object:

  • input fields disabled at a higher level (e.g. by a surrounding fieldset) still return values
  • Codeception expects an empty value to match an unselected select box.

The function clones the crawler's node and creates a new crawler because it destroys or adds to the DOM for the form to achieve the desired functionality. Other functions simply querying the DOM wouldn't expect them.

Parameters
$form : Crawler

the form

Return values
Form

initServerGlobal()

Adds the required server params.

private initServerGlobal() : mixed

Note this is done separately from the request cycle since someone might call Url::to before doing a request, which would instantiate the request component with incorrect server params.

loadFixtures()

load fixtures before db transaction

private loadFixtures(mixed $test) : mixed
Parameters
$test : mixed

instance of test class

openHrefFromDomNode()

private openHrefFromDomNode(DOMNode $node) : mixed
Parameters
$node : DOMNode

retrieveBaseUrl()

private retrieveBaseUrl() : string
Return values
string

stringifySelector()

private stringifySelector(mixed $selector) : mixed
Parameters
$selector : mixed

        
On this page

Search results