Testomatio - Test Management for Codeception
This module uses Symfonyâs DomCrawler and HttpKernel Component to emulate requests and test response.
$I->grabService(...)
$I->seeInRepository(...)
- see Doctrine Module$I->seeEmailIsSent()
https://github.com/Codeception/symfony-module-tests
app_path
: âsrcâ - Specify custom path to your app dir, where the kernel interface is located.environment
: âlocalâ - Environment used for load kernelkernel_class
: âApp\Kernelâ - Kernel class nameem_service
: âdoctrine.orm.entity_managerâ - Use the stated EntityManager to pair with Doctrine Module.debug
: true - Turn on/off debug modecache_router
: âfalseâ - Enable router caching between tests in order to increase performancerebootable_client
: âtrueâ - Reboot clientâs kernel before each requestguard
: âfalseâ - Enable custom authentication system with guard (only for Symfony 5.4)bootstrap
: âfalseâ - Enable the test environment setup with the tests/bootstrap.php file if it exists or with Symfony DotEnv otherwise. If false, it does nothing.authenticator
: âfalseâ - Reboot clientâs kernel before each request (only for Symfony 6.0 or higher)Functional.suite.yml
modules:
enabled:
- Symfony:
app_path: 'src'
environment: 'test'
services
: Includes methods related to the Symfony dependency injection container (DIC):
See WebDriver module for general information on how to load parts of a framework module.
Usage example:
If youâre using Symfony with Eloquent ORM (instead of Doctrine), you can load the ORM
part of Laravel module
in addition to Symfony module.
hidden API method, expected to be used from Helper classes
api
param mixed
$locatorreturn iterable
Locates element using available Codeception locator types:
Use it in Helpers or GroupObject or Extension classes:
WebDriver module returns Facebook\WebDriver\Remote\RemoteWebElement
instances
PhpBrowser and Framework modules return Symfony\Component\DomCrawler\Crawler
instances
hidden API method, expected to be used from Helper classes
api
throws ModuleException
return string
Returns content of the last response Use it in Helpers when you want to retrieve response of request performed by another module.
hidden API method, expected to be used from Helper classes
api
param string
$methodparam string
$uriparam array
$parametersparam array
$filesparam array
$serverparam ?string
$contentreturn void
Opens a page with arbitrary request parameters.
Useful for testing multi-step forms on a specific step.
hidden API method, expected to be used from Helper classes
api
see
_loadPage
param string
$methodparam string
$uriparam array
$parametersparam array
$filesparam array
$serverparam ?string
$contentthrows ExternalUrlException|ModuleException
return ?string
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.
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.
hidden API method, expected to be used from Helper classes
api
param string
$filenamereturn void
Saves page source of to a file
param string
$usernameparam string
$passwordreturn void
Authenticates user for HTTP_AUTH
param \Symfony\Component\Security\Core\User\UserInterface
$userparam string
$firewallNameparam ?string
$firewallContextreturn void
Login with the given user object.
The $user
object must have a persistent identifier.
If you have more than one firewall or firewall context, you can specify the desired one as a parameter.
param \Symfony\Component\Security\Core\Authentication\Token\TokenInterface
$tokenparam string
$firewallNameparam ?string
$firewallContextreturn void
param string
$actionparam array
$paramsreturn void
Opens web page by action name
param string
$pagereturn void
Opens the page for the given relative URI.
param string
$routeNameparam array
$paramsreturn void
Opens web page using route name and parameters.
param string
$headerNameparam string
$expectedValueparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that an email contains addresses with a header
$headerName
and its expected value $expectedValue
.
If the Email object is not specified, the last email sent is used instead.
param int
$countparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that an email has sent the specified number $count
of attachments.
If the Email object is not specified, the last email sent is used instead.
param string
$headerNameparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that an email has a header $headerName
.
If the Email object is not specified, the last email sent is used instead.
param string
$headerNameparam string
$expectedValueparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that the header
$headerName
of an email is not the expected one $expectedValue
.
If the Email object is not specified, the last email sent is used instead.
param string
$headerNameparam string
$expectedValueparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that the header
$headerName
of an email is the same as expected $expectedValue
.
If the Email object is not specified, the last email sent is used instead.
param string
$textparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that the HTML body of an email contains $text
.
If the Email object is not specified, the last email sent is used instead.
param string
$textparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that the HTML body of an email does not contain a text $text
.
If the Email object is not specified, the last email sent is used instead.
param string
$headerNameparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that an email does not have a header $headerName
.
If the Email object is not specified, the last email sent is used instead.
param string
$textparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify the text body of an email contains a $text
.
If the Email object is not specified, the last email sent is used instead.
param string
$textparam ?\Symfony\Component\Mime\Email
$emailreturn void
Verify that the text body of an email does not contain a $text
.
If the Email object is not specified, the last email sent is used instead.
param
$fieldparam string
$filenamereturn void
Attaches a file relative to the Codeception _data
directory to the given file upload field.
param
$optionreturn void
Ticks a checkbox. For radio buttons, use the selectOption
method instead.
param string|array
$linkparam
$contextreturn void
Perform 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.
@deprecated
param string
$namereturn void
param string
$textparam array|string
$selector optionalreturn void
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.
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()
.
return void
Check that user is not authenticated.
param
$checkboxreturn void
Check that the specified checkbox is unchecked.
param
$cookieparam
$paramsreturn mixed|void
Checks 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 string
$urireturn void
Checks that the current URL doesnât equal the given string.
Unlike dontSeeInCurrentUrl
, this only matches the full URL.
param string
$urireturn void
Checks that current url doesnât match the given regular expression.
param
$selectorparam array
$attributesreturn void
Checks that the given element is invisible or not present on the page.
You can also specify expected attributes of this element.
return void
Checks that no email was sent.
The check is based on \Symfony\Component\Mailer\EventListener\MessageLoggerListener
, which means:
If your app performs an HTTP redirect, you need to suppress it using stopFollowingRedirects() first; otherwise this check will always pass.
param string|string[]|null
$expectedreturn void
Verifies that there were no events during the test.
Both regular and orphan events are checked.
param class-string|class-string[]
$expectedparam string|string[]
$eventsreturn void
Verifies that one or more event listeners were not called during the test.
@deprecated
param object|string|string[]
$expectedreturn void
Verifies that one or more event listeners were not called during the test.
return void
Verifies that there are no errors bound to the submitted form.
param string
$urireturn void
Checks that the current URI doesnât contain the given string.
param string|array
$fieldparam
$valuereturn void
Checks 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.
param
$formSelectorparam array
$paramsreturn void
Checks if the array of form parameters (name => value) are not set on the form matched with the passed selector.
To check that an element hasnât been assigned any one of many values, an array can be passed as the value:
Additionally, checkbox values can be checked with a boolean.
param string
$attributeparam mixed
$valuereturn void
Assert that a session attribute does not exist, or is not equal to the passed value.
param string
$rawreturn void
Checks that the current page contains the given string in its raw source code.
param
$titlereturn mixed|void
Checks that the page title does not contain the given string.
param string
$textparam string
$urlreturn void
Checks 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.
param
$selectorparam
$optionTextreturn mixed|void
Checks that the given option is not selected.
param string|string[]
$expectedreturn void
Verifies that there were no orphan events during the test.
An orphan event is an event that was triggered by manually executing the
dispatch()
method
of the EventDispatcher but was not handled by any listener after it was dispatched.
return void
Check that user is not authenticated with the âremember meâ option.
param string
$templatereturn void
Asserts that a template was not rendered in the response.
param int
$codereturn void
Checks that response code is equal to value provided.
param mixed
$subjectparam ?string
$propertyPathparam ?string
$constraintreturn void
Asserts that the given subject fails validation.
This assertion does not concern the exact number of violations.
param
$fieldparam
$valuereturn void
Fills a text field or textarea with the given string.
return void
Follow pending redirect if there is one.
return void
Go to the configured logout url (by default: /logout
).
This method includes redirection to the destination page configured after logout.
See the Symfony documentation on âLogging Outâ.
param
$cssOrXpathparam string
$attributereturn mixed
Returns the value of the given attribute value from the given HTML element. For some attributes, the string true
is returned instead of their literal value (e.g. disabled="disabled"
or required="required"
).
Fails if the element is not found. Returns null
if the attribute is not present on the element.
param string
$cookieparam array
$paramsreturn mixed
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 ?string
$urireturn mixed
Executes the given regular expression against the current URI and returns the first capturing group.
If no parameters are provided, the full URI is returned.
return ?\Symfony\Component\Mime\Email
Returns the last sent email.
The function is based on \Symfony\Component\Mailer\EventListener\MessageLoggerListener
, which means:
If your app performs an HTTP redirect after sending the email, you need to suppress it using stopFollowingRedirects() first.
See also: grabSentEmails()
param
$cssOrXpathparam ?string
$attributereturn string[]
Grabs either the text content, or attribute values, of nodes matched by $cssOrXpath and returns them as an array.
param string
$entityClass The entity classparam array
$criteria Optional query criteriareturn int
Retrieves number of records from database âidâ is the default search parameter.
throws \Codeception\Exception\ModuleException
if no page was opened.return string
Current page source code.Grabs current page source code.
param string
$parameterNamereturn \UnitEnum|array|string|int|float|bool|null
Grabs a Symfony parameter
This only works for explicitly set parameters (just using bind
for Symfonyâs dependency injection is not enough).
param object|string
$mixedreturn ?\Doctrine\ORM\EntityRepository
Grab a Doctrine entity repository.
Works with objects, entities, repositories, and repository interfaces.
return \Symfony\Component\Mime\Email[]
Returns an array of all sent emails.
The function is based on \Symfony\Component\Mailer\EventListener\MessageLoggerListener
, which means:
If your app performs an HTTP redirect after sending the email, you need to suppress it using stopFollowingRedirects() first.
See also: grabLastSentEmail()
part
servicesparam string
$serviceIdreturn object
Grabs a service from the Symfony dependency injection container (DIC).
In âtestâ environment, Symfony uses a special test.service_container
.
See the âPublic Versus Private Servicesâ documentation.
Services that arenât injected somewhere into your app, need to be defined as public
to be accessible by Codeception.
param
$cssOrXPathOrRegexreturn mixed
Finds 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.
param
$fieldreturn mixed
Finds the value for the given form field.
If a fuzzy locator is used, the field is found by field name, CSS, and XPath.
param string
$name the name of the request headerparam string
$value the value to set it to for subsequent
requestsreturn void
Sets the HTTP header to the passed value - which is used on subsequent HTTP requests through PhpBrowser.
Example:
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â
param string
$nameparam string
$valuereturn void
Sets SERVER parameter valid for all next requests.
return void
Invalidate previously cached routes.
return void
Alias method for logoutProgrammatically()
return void
Invalidates the current userâs session and expires the session cookies.
This method does not include any redirects after logging out.
param ?string
$namereturn void
Use this method within an interactive pause to save the HTML source code of the current page.
param int
$numberOfSteps (default value 1)return void
Moves back in history.
part
servicesparam string
$serviceNamereturn void
Get service $serviceName and add it to the lists of persistent services, making that service persistent between tests.
part
servicesparam string
$serviceNamereturn void
Get service $serviceName and add it to the lists of persistent services.
return void
Reboot clientâs kernel.
Can be used to manually reboot kernel when ârebootable_clientâ => false
param
$cookieparam
$paramsreturn mixed|void
Unsets cookie with the given name.
You can set additional cookie params like domain
, path
in array passed as last argument.
param string
$command The console command to executeparam array
$parameters Parameters (arguments and options) to pass to the commandparam array
$consoleInputs Console inputs (e.g. used for interactive questions)param int
$expectedExitCode The expected exit code of the commandreturn string
Returns the console output of the commandRun Symfony console command, grab response and return as string.
Recommended to use for integration or functional testing.
param string
$textparam array|string
$selector optionalreturn void
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.
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()
.
return void
Checks that a user is authenticated.
param
$checkboxreturn void
Checks that the specified checkbox is checked.
param
$cookieparam
$paramsreturn mixed|void
Checks that a cookie with the given name is set.
You can set additional cookie params like domain
, path
as array passed in last argument.
param string
$actionreturn void
Checks that current page matches action
param string
$routeNameparam array
$paramsreturn void
Checks that current url matches route.
param string
$expectedTemplatereturn void
Asserts that the current template matches the expected template.
param string
$urireturn void
Checks that the current URL is equal to the given string.
Unlike seeInCurrentUrl
, this only matches the full URL.
param string
$urireturn void
Checks that the current URL matches the given regular expression.
param
$selectorparam array
$attributesreturn void
Checks that the given element exists on the page and is visible.
You can also specify expected attributes of this element.
Only works if <html>
tag is present.
param int
$expectedCount The expected number of emails sentreturn void
Checks if the given number of emails was sent (default $expectedCount
: 1).
The check is based on \Symfony\Component\Mailer\EventListener\MessageLoggerListener
, which means:
If your app performs an HTTP redirect after sending the email, you need to suppress it using stopFollowingRedirects() first.
param string|string[]
$expectedreturn void
Verifies that one or more events were dispatched during the test.
Both regular and orphan events are checked.
If you need to verify that expected event is not orphan,
add dontSeeOrphanEvent
call.
param class-string|class-string[]
$expectedparam string|string[]
$eventsreturn void
Verifies that one or more event listeners were called during the test.
@deprecated
param object|string|string[]
$expectedreturn void
Verifies that one or more event listeners were called during the test.
param string
$fieldparam string|null
$messagereturn void
Verifies that a form field has an error.
You can specify the expected error message as second parameter.
param string[]
$expectedErrorsreturn void
Verifies that multiple fields on a form have errors.
If you only specify the name of the fields, this method will verify that the field contains at least one error of any type:
If you want to specify the error messages, you can do so by sending an associative array instead, with the key being the name of the field and the error message the value.
This method will validate that the expected error message is contained in the actual error message, that is, you can specify either the entire error message or just a part of it:
If you donât want to specify the error message for some fields,
you can pass null
as value instead of the message string,
or you can directly omit the value of that field. If that is the case,
it will be validated that that field has at least one error of any type:
return void
Verifies that there are one or more errors bound to the submitted form.
param string
$routeNamereturn void
Checks that current url matches route.
Unlike seeCurrentRouteIs, this can matches without exact route parameters
param string
$urireturn void
Checks that current URI contains the given string.
param string|array
$fieldparam
$valuereturn void
Checks 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.
param
$formSelectorparam array
$paramsreturn void
Checks if the array of form parameters (name => value) are set on the form matched with the passed selector.
For multi-select elements, or to check values of multiple elements with the same name, an array may be passed:
Additionally, checkbox values can be checked with a boolean.
Pair this with submitForm for quick testing magic.
param string
$attributeparam mixed
$valuereturn void
Assert that a session attribute exists.
param string
$rawreturn void
Checks that the current page contains the given string in its raw source code.
param
$titlereturn mixed|void
Checks that the page title contains the given string.
param string
$textparam ?string
$urlreturn void
Checks that thereâs a link with the specified text.
Give a full URL as the second parameter to match links with that exact URL.
param int
$expectedNum Expected number of recordsparam string
$className A doctrine entityparam array
$criteria Optional query criteriareturn void
Checks that number of given records were found in database.
âidâ is the default search parameter.
param
$selectorparam int|int[]
$expectedreturn void
Checks that there are a certain number of elements matched by the given locator on the page.
param
$selectorparam
$optionTextreturn mixed|void
Checks that the given option is selected.
param string|string[]
$expectedreturn void
Verifies that one or more orphan events were dispatched during the test.
An orphan event is an event that was triggered by manually executing the
dispatch()
method
of the EventDispatcher but was not handled by any listener after it was dispatched.
param string|null
$urlreturn void
Verifies that a page is available.
By default, it checks the current page, specify the $url
parameter to change it.
return void
Asserts that current page has 404 response status code.
param string
$pageparam string
$redirectsToreturn void
Goes to a page and check that it redirects to another.
return void
Checks that a user is authenticated with the âremember meâ option.
param string
$templatereturn void
Asserts that a template was rendered in the response.
That includes templates built with inheritance.
param int|float
$expectedMilliseconds The expected time in millisecondsreturn void
Asserts that the time a request lasted is less than expected.
If the page performed an HTTP redirect, only the time of the last request will be taken into account. You can modify this behavior using stopFollowingRedirects() first.
Also, note that using code coverage can significantly increase the time it takes to resolve a request, which could lead to unreliable results when used together.
It is recommended to set rebootable_client
to true
(=default),
cause otherwise this assertion gives false results if you access multiple pages in a row, or if your app performs a redirect.
param int
$codereturn void
Checks that response code is equal to value provided.
param int
$fromparam int
$toreturn void
Checks that response code is between a certain range. Between actually means [from <= CODE <= to]
return void
Checks that the response code is 4xx
return void
Checks that the response code 3xx
return void
Checks that the response code is 5xx
return void
Checks that the response code 2xx
param array
$bindingsreturn void
Assert that the session has a given list of values.
param string
$rolereturn void
Check that the current user has a role
param string[]
$rolesreturn void
Verifies that the current user has multiple roles
param UserInterface|null
$userreturn void
Checks that the userâs password would not benefit from rehashing.
If the user is not provided it is taken from the current session.
You might use this function after performing tasks like registering a user or submitting a password update form.
param mixed
$subjectparam ?string
$propertyPathparam ?string
$constraintreturn void
Asserts that the given subject passes validation.
This assertion does not concern the exact number of violations.
param string
$expectedparam mixed
$subjectparam string
$propertyPathreturn void
Asserts that a constraint violation message or a part of it is present in the subjectâs violations.
param int
$expectedparam mixed
$subjectparam ?string
$propertyPathparam ?string
$constraintreturn void
Asserts the exact number of violations for the given subject.
param
$selectparam
$optionreturn void
Selects an option in a select tag or in radio button group.
Provide an array for the second argument to select multiple options:
Or provide an associative array for the second argument to specifically define which selection method should be used:
param string
$uriparam array
$paramsreturn void
Sends an ajax GET request with the passed parameters.
See sendAjaxPostRequest()
param string
$uriparam array
$paramsreturn void
Sends an ajax POST request with the passed parameters.
The appropriate HTTP header is added automatically:
X-Requested-With: XMLHttpRequest
Example:
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:
param string
$methodparam string
$uriparam array
$paramsreturn void
Sends an ajax request, using the passed HTTP method.
See sendAjaxPostRequest()
Example:
param
$nameparam
$valparam
$paramsreturn mixed|void
Sets a cookie with the given name and value.
You can set additional cookie params like domain
, path
, expires
, secure
in array passed as last argument.
param int
$maxRedirectsreturn void
Sets the maximum number of redirects that the Client can follow.
param array
$paramsreturn void
Sets SERVER parameters valid for all next requests.
this will remove old ones.
return void
Enables automatic redirects to be followed by the client.
return void
Prevents automatic redirects to be followed by the client.
param
$selectorparam array
$paramsparam ?string
$buttonreturn void
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.
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:
For example, given this sample âSign Upâ form:
You could write the following to submit it:
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.
This function works well when paired with seeInFormFields()
for quickly testing CRUD interfaces and form validation logic.
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.
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:
The solution is to pass an array value:
param string
$name The name
attribute of the <form>
(you cannot use an array as selector here)param string[]
$fieldsreturn void
Submit a form specifying the form name only once.
Use this function instead of $I->submitForm()
to avoid repeating the form name in the field selectors.
If you customized the names of the field selectors use $I->submitForm()
for full control.
param string
$namereturn void
Switch to iframe or frame on the page.
Example:
param
$optionreturn void
Unticks a checkbox.
part
servicesparam string
$serviceNamereturn void
Remove service $serviceName from the lists of persistent services.
param string
$name the name of the header to unset.return void
Unsets a HTTP header (that was originally added by haveHttpHeader()), so that subsequent requests will not send it anymore.
Example: