Selecting elements visually is pretty cool and all. But once you start to build a serious workflow it is not enough.
You also need:
- Checking if elements are actually there
- Check for multiple elements to be there
- Check if either a element is there or another one is there
This is where expect(), and() and or() get on stage to shine.
But they are not always as intuitive to use as one might think.
That is why this blog post will go into detail about all the common pitfalls - we know of - you can run into and how to avoid them.
How to Use expect()
The usage of expect() seems "_simple_" and has the following structure for its syntax (Check the full API docs):
Pitfall 1 - Forgetting exists()/notExists() and/or exec()
Correct usage of expect() needs you to use exists() or notExists() and also conclude your instruction with exec() like this:
Something that happens often is that expect() is used but exists()/notExists() is missing. While this code compiles, the instruction does not lead to an execution that checks for the (non-)existence of an element:
But even if you do add an exists()|notExists() it still does not lead to an execution as the exec() is missing:
Because of this we implemented an ESLint rule to check for the correct usage of expect(), so you do not have to search for this two subtle bugs any more! The ESLint rule is available with version 1.3.0 of the npm-package @askui/eslint-plugin-askui (Check the README for more information). It is shipped by default when a new AskUI project with version 0.18.0 is initialized.
You can not use expect() with and() - What You Should Do Instead
Intuitively you would think you can check if multiple elements exist with one instruction by using and():
But this will always fail as you actually expect an element to have the text Log in and the element to also be a button with the text Sign Up which can never be true.
The solution to this problem is to use multiple expect() instructions:
How to Use expect() Together With or()
Checking if at least one of multiple elements is on the screen works with or(). In the following example we expect one of three buttons to be there:
Expect Fails but I Want to Continue the Workflow
Sometimes you want to continue your workflow or do something if an element is not there. But when an expect() fails it fails the whole workflow run by throwing an exception. You can work around this by using a try/catch. In the catch-block you define your recovery or alternative:
Conclusion
AskUIs expressive syntax that nearly reads like natural language looks simple enough to write at first. But like with everything the key to success lies in the nuances.
We hope you learned some of those regarding the expect() command with this blog post. If not, we are more than happy to help you out in our Community.