If you use Codeception installed using composer, install this module with the following command:
composer require --dev codeception/module-yii2
Alternatively, you can enable Yii2
module in suite configuration file and run
codecept init upgrade4
This module was bundled with Codeception 2 and 3, but since version 4 it is necessary to install it separately.
Some modules are bundled with PHAR files.
Warning. Using PHAR file and composer in the same project can cause unexpected errors.
This module provides integration with Yii framework (2.0).
It initializes the Yii framework in a test environment and provides actions for functional testing.
This section details what you can expect when using this module.
\Yii::$app
at the start of each test (available in the test and in _before()
).recreateApplication
.request
and response
component are both recreated.configFile
required - path to the application config file. The file should be configured for the test environment and return a configuration array.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 testignoreCollidingDSN
- (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 requestYou can use this module by setting params in your functional.suite.yml
:
actor: FunctionalTester modules: enabled: - Yii2: configFile: 'path/to/config.php'
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 avilable 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/...
functional.suite.yml
)actor: FunctionalTester modules: enabled: - Yii2: configFile: 'config/test.php'
unit.suite.yml
)actor: UnitTester modules: enabled: - Asserts - Yii2: configFile: 'config/test.php' part: init
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
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()] }
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']);
Maintainer: samdark Stability: stable
@property \Codeception\Lib\Connector\Yii2 $client
hidden API method, expected to be used from Helper classes
Locates element using available Codeception locator types:
Use it in Helpers or GroupObject or Extension classes:
<?php $els = $this->getModule('Yii2')->_findElements('.items'); $els = $this->getModule('Yii2')->_findElements(['name' => 'username']); $editLinks = $this->getModule('Yii2')->_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
param
$locatorreturn
array of interactive elementshidden API method, expected to be used from Helper classes
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
<?php // in Helper class public function seeResponseContains($text) { $this->assertStringContainsString($text, $this->getModule('Yii2')->_getResponseContent(), "response contains"); } ?>
return
string @throws ModuleExceptionhidden API method, expected to be used from Helper classes
Opens a page with arbitrary request parameters. Useful for testing multi-step forms on a specific step.
<?php // in Helper class public function openCheckoutFormStep2($orderId) { $this->getModule('Yii2')->_loadPage('POST', '/checkout/step2', ['order' => $orderId]); } ?>
param
$methodparam
$uriparam array
$parametersparam array
$filesparam array
$serverparam null
$contenthidden API method, expected to be used from Helper classes
Send custom request to a backend using method, uri, parameters, etc. 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('Yii2')->_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.
param
$methodparam
$uriparam array
$parametersparam array
$filesparam array
$serverparam null
$contentreturn
mixed|Crawler @throws ExternalUrlException @see _loadPage
hidden API method, expected to be used from Helper classes
Saves page source of to a file
$this->getModule('Yii2')->_savePageSource(codecept_output_dir().'page.html');
param
$filenameAuthenticates user for HTTP_AUTH
param
$usernameparam
$passwordAuthenticates a user on a site without submitting a login form. 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.
param
$user @throws ModuleExceptionOpens the page for the given relative URI or route.
<?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]);
param string|array
$page the URI or route in array formatSimilar to amOnPage
but accepts a route as first argument and params as second
$I->amOnRoute('site/view', ['page' => 'about']);
param string
$route A routeparam array
$params Additional route parametersAttaches a file relative to the Codeception _data
directory to the given file upload field.
<?php // file is stored in 'tests/_data/prices.xls' $I->attachFile('input[@type="file"]', 'prices.xls'); ?>
param
$fieldparam
$filenameTicks a checkbox. For radio buttons, use the selectOption
method instead.
<?php $I->checkOption('#agree'); ?>
param
$optionPerform a click on a link or a button, given by a locator. 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']); ?>
param
$linkparam
$contextCreates the CSRF Cookie.
param string
$val The value of the CSRF tokenreturn
string[] Returns an array containing the name of the CSRF param and the masked CSRF token.Deletes the header with the passed name. Subsequent requests will not have the deleted header in its request.
Example:
<?php $I->haveHttpHeader('X-Requested-With', 'Codeception'); $I->amOnPage('test-headers.php'); // ... $I->deleteHeader('X-Requested-With'); $I->amOnPage('some-other-page.php'); ?>
param string
$name the name of the header to delete.Checks that the current page doesn’t contain the text specified (case insensitive). 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()
.
param string
$textparam array|string
$selector optionalCheck that the specified checkbox is unchecked.
<?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. ?>
param
$checkboxChecks that there isn’t a cookie with the given name. You can set additional cookie params like domain
, path
as array passed in last argument.
param
$cookie
param array
$params
Checks that the current URL doesn’t equal the given string. Unlike dontSeeInCurrentUrl
, this only matches the full URL.
<?php // current url is not root $I->dontSeeCurrentUrlEquals('/'); ?>
param string
$uriChecks that current url doesn’t match the given regular expression.
<?php // to match root url $I->dontSeeCurrentUrlMatches('~^/users/(\d+)~'); ?>
param string
$uriChecks that the given element is invisible or not present on the page. 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']); ?>
param
$selectorparam array
$attributesChecks that no email was sent
[Part]
emailChecks that the current URI doesn’t contain the given string.
<?php $I->dontSeeInCurrentUrl('/users/'); ?>
param string
$uriChecks that an input field or textarea doesn’t contain the given value. 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'); ?>
param
$fieldparam
$valueChecks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
<?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 ]); ?>
param
$formSelectorparam
$paramsChecks that the current page contains the given string in its raw source code.
<?php $I->dontSeeInSource('<h1>Green eggs & ham</h1>');
param
$rawChecks that the page title does not contain the given string.
param
$titleChecks that the page doesn’t contain a link with the given string. 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'); ?>
param string
$textparam string
$url optionalChecks that the given option is not selected.
<?php $I->dontSeeOptionIsSelected('#form input[name=payment]', 'Visa'); ?>
param
$selectorparam
$optionTextChecks that a record does not exist in the database.
$I->dontSeeRecord('app\models\User', array('name' => 'davert'));
param
$modelparam array
$attributes[Part]
ormChecks that response code is equal to value provided.
<?php $I->dontSeeResponseCodeIs(200); // recommended \Codeception\Util\HttpCode $I->dontSeeResponseCodeIs(\Codeception\Util\HttpCode::OK);
param
$codeFills a text field or textarea with the given string.
<?php $I->fillField("//input[@type='text']", "Hello World!"); $I->fillField(['name' => 'email'], '[email protected]'); ?>
param
$fieldparam
$valueReturns a list of regex patterns for recognized domain names
return
arrayGrabs the value of the given attribute value from the given element. Fails if element is not found.
<?php $I->grabAttributeFrom('#tooltip', 'title'); ?>
param
$cssOrXpathparam
$attributeGets a component from the Yii container. Throws an exception if the component is not available
<?php $mailer = $I->grabComponent('mailer');
param
$component @throws ModuleException @deprecated in your tests you can use \Yii::$app directly.Grabs a cookie value. 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)
.
param
$cookie
param array
$params
Gets a fixture by name. 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');
param
$name @throws ModuleException if the fixture is not found[Part]
fixturesReturns all loaded fixtures. Array of fixture instances
[Part]
fixturesreturn
arrayExecutes the given regular expression against the current URI and returns the first capturing group. If no parameters are provided, the full URI is returned.
<?php $user_id = $I->grabFromCurrentUrl('~^/user/(\d+)/~'); $uri = $I->grabFromCurrentUrl(); ?>
param string
$uri optionalReturns the last sent email:
<?php $I->seeEmailIsSent(); $message = $I->grabLastSentEmail(); $I->assertEquals('[email protected],com', $message->getTo());
[Part]
emailGrabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
<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'); ?>
param
$cssOrXpathparam
$attributereturn
string[]Grabs current page source code.
@throws ModuleException if no page was opened.
return
string Current page source code.Retrieves a record from the database
$category = $I->grabRecord('app\models\User', array('name' => 'davert'));
param
$modelparam array
$attributes[Part]
ormReturns array of all sent email messages. 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('[email protected],com', $messages[0]->getTo());
[Part]
emailreturn
array @throws ModuleExceptionFinds and returns the text contents of the given element. 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 ?>
param
$cssOrXPathOrRegexparam
$field
return array | mixed | null | string |
Creates and loads fixtures from a config. 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
param
$fixtures[Part]
fixturesSets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
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_Id', 'Codeception'); ?>
param string
$name the name of the request headerparam string
$value the value to set it to for subsequent requestsInserts a record into the database.
<?php $user_id = $I->haveRecord('app\models\User', array('name' => 'Davert')); ?>
param
$modelparam array
$attributes[Part]
ormSets SERVER parameter valid for all next requests.
$I->haveServerParameter('name', 'value');
param
$nameparam
$valueSaves current page’s HTML into a temprary file. Use this method in debug mode within an interactive pause to get a source code of current page.
<?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
param null
$nameMoves back in history.
param int
$numberOfSteps (default value 1)Unsets cookie with the given name. You can set additional cookie params like domain
, path
in array passed as last argument.
param
$cookie
param array
$params
Checks that the current page contains the given string (case insensitive).
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()
.
param string
$textparam array|string
$selector optionalChecks that the specified checkbox is checked.
<?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]'); ?>
param
$checkboxChecks that a cookie with the given name is set. You can set additional cookie params like domain
, path
as array passed in last argument.
<?php $I->seeCookie('PHPSESSID'); ?>
param
$cookieparam array
$paramsChecks that the current URL is equal to the given string. Unlike seeInCurrentUrl
, this only matches the full URL.
<?php // to match root url $I->seeCurrentUrlEquals('/'); ?>
param string
$uriChecks that the current URL matches the given regular expression.
<?php // to match root url $I->seeCurrentUrlMatches('~^/users/(\d+)~'); ?>
param string
$uriChecks that the given element exists on the page and is visible. 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']); ?>
param
$selectorparam array
$attributes @returnChecks that an email is sent.
<?php // check that at least 1 email was sent $I->seeEmailIsSent(); // check that only 3 emails were sent $I->seeEmailIsSent(3);
param int
$num @throws ModuleException[Part]
emailChecks that current URI contains the given string.
<?php // to match: /home/dashboard $I->seeInCurrentUrl('home'); // to match: /users/1 $I->seeInCurrentUrl('/users/'); ?>
param string
$uriChecks that the given input field or textarea equals (i.e. not just contains) the given value. 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'); ?>
param
$fieldparam
$valueChecks if the array of form parameters (name => value) are set on the form matched with the passed selector.
<?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); ?>
param
$formSelectorparam
$paramsChecks that the current page contains the given string in its raw source code.
<?php $I->seeInSource('<h1>Green eggs & ham</h1>');
param
$rawChecks that the page title contains the given string.
<?php $I->seeInTitle('Blog - Post #1'); ?>
param
$titleChecks that there’s a link with the specified text. 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> ?>
param string
$textparam string
$url optionalChecks that there are a certain number of elements matched by the given locator on the page.
<?php $I->seeNumberOfElements('tr', 10); $I->seeNumberOfElements('tr', [0,10]); // between 0 and 10 elements ?>
param
$selectorparam mixed
$expected int or int[]Checks that the given option is selected.
<?php $I->seeOptionIsSelected('#form input[name=payment]', 'Visa'); ?>
param
$selectorparam
$optionTextAsserts that current page has 404 response status code.
Checks that a record exists in the database.
$I->seeRecord('app\models\User', array('name' => 'davert'));
param
$modelparam array
$attributes[Part]
ormChecks that response code is equal to value provided.
<?php $I->seeResponseCodeIs(200); // recommended \Codeception\Util\HttpCode $I->seeResponseCodeIs(\Codeception\Util\HttpCode::OK);
param
$codeChecks that response code is between a certain range. Between actually means [from <= CODE <= to]
param
$fromparam
$toChecks that the response code is 4xx
Checks that the response code 3xx
Checks that the response code is 5xx
Checks that the response code 2xx
Selects an option in a select tag or in radio button group.
<?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' ?>
param
$selectparam
$optionSends an ajax GET request with the passed parameters. See sendAjaxPostRequest()
param
$uriparam
$paramsSends an ajax POST request with the passed parameters. 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', ]]);
param string
$uriparam array
$paramsSends an ajax request, using the passed HTTP method. See sendAjaxPostRequest()
Example:
<?php $I->sendAjaxRequest('PUT', '/posts/7', ['title' => 'new title']);
param
$methodparam
$uriparam
$paramsSets a cookie and, if validation is enabled, signs it.
param string
$name The name of the cookieparam string
$value The value of the cookieparam array
$params Additional cookie params like domain
, path
, expires
and secure
.Sets SERVER parameters valid for all next requests. this will remove old ones.
$I->setServerParameters([]);
param array
$paramsSubmits the given form on the page, with the given form values. Pass the form field’s values as an array in the second parameter.
Although this function can be used as a short-hand version of fillField()
, selectOption()
, click()
etc. it has some important differences:
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 action="/sign_up"> 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/> 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.
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', ] ]);
param
$selectorparam
$paramsparam
$buttonSwitch to iframe or frame on the page.
Example:
<iframe name="another_frame" src="http://example.com">
<?php # switch to iframe $I->switchToIframe("another_frame");
param string
$nameUnticks a checkbox.
<?php $I->uncheckOption('#notify'); ?>
param
$option
© 2011 Michael Bodnarchuk and contributors
Licensed under the MIT License.
https://codeception.com/docs/modules/Yii2