If you want to extend the
browser instance with your own set of commands, the browser method
addCommand is here for you.
You can write your command in a synchronous way (default), just as in your specs—or, you can write it in an asynchronous way (like when using WebdriverIO in standalone mode).
This example shows how to add a new command that returns the current URL and title as one result, using only synchronous commands:
Additionally, you can extend the element instance with your own set of commands, by passing
true as the final argument.
By default, element is expected to exist in
waitforTimeout milliseconds, or an exception will be thrown.
Custom commands give you the opportunity to bundle a specific sequence of commands you use frequently as a single call. You can define custom commands at any point in your test suite; just make sure that the command is defined before its first use. (The
before hook in your
wdio.conf.js is one good place to create them.)
Once defined, you can use them as follows:
If you need to control element existence in a custom command, it is possible either to:
- add the command to
browser, and pass a selector; OR
- add the command to
elementusing name that starts with one of the following:
Note: If you register a custom command to the
browser scope, the command won't be accessible for elements. Likewise, if you register a command to the element scope, it won't be accessible in the
Be careful to not overload the
browser scope with too many custom commands.
We recommend defining custom logic in page objects, so they are bound to a specific page.
If you use external libraries (e.g., to do database calls) that support promises, a nice approach to integrate them is to wrap certain API methods with a custom command.
When returning the promise, WebdriverIO ensures that it doesn't continue with the next command until the promise is resolved. If the promise gets rejected, the command will throw an error.
Then, just use it in your WDIO test specs synchronously:
Note: The result of your custom command is the result of the promise you return. Also, there is no support for synchronous commands in standalone mode; therefore, you must always handle asynchronous commands using promises.
You can also overwrite native commands with
It is not recommended to do this, because it may lead to unpredictable behavior of the framework!
The overall approach is similar to
addCommand, the only difference is that the first argument in the command function is the original function that you are about to overwrite. Please see some examples below.
NOTE: Examples below assume sync mode. If you are not using it, don't forget to add
Overwriting commands on element level is almost the same. Simply pass
true as the third argument to