Avoid adding empty line after each statement
Avoid adding empty line after each command. There should be logical separation
between the code statements.
Here is an example of a test case named "Test to add and delete an article".
Incorrect method
Correct method
Here we have introduced a new line to separate code blocks having different test
logic, and have combined cypress commands pertaining to the same test logic.
Avoid writing comments in the code unless it is really needed. The code should
be self explanatory.
Importing external files before internal files
Always keep import statements for external libraries before importing internal
files.
Avoiding Repetitive Code
There are different ways we can avoid repetitive code. Consider using following
ways to avoid repetitive code:
- Custom commands e.g. cy.login() for most of the application's functionalities
login is the first step
- Utility functions
- Loops (If the same assertion logic is used for multiple elements)
Maintaining API paths
We can create a separate file for storing all the routes and import them
whenever required. For storing them, we can create routes.js
file under the constants folder.
Add files that we don't want to commit or track in .gitignore
We would want to ignore some files that are created along with time or during the installation of Cypress like node_modules,
videos,
screenshots_ etc. These files are important but can be ignored while committing our changes to the repository. Such files can be added in
.gitignore`.
Use webpack aliases
webpack.config.js
file, which describes how the cypress files and assets
should be transformed and what kind of output should be generated.
Importing fakers from fixtures
Often we need to use some random data to perform integration testing. And there
comes a npm package,faker
which helps us to generate random data very easily.
Instead of directly importing faker
into the test file, we can create a
fake.js
file in the fixtures folder and import the fake data into our tests.
Use within()
for narrowing the scope of cypress
Whenever multiple elements with the same selector are present, we can select the desired element using within()
to narrow the scope. e.g. Let's say, there is a table of canned responses list. Each row has an edit, and delete button. So, to select one of them, we first need to get the element with the name and then use
within()
to narrow down the scope. Each row contains only one edit button, so
the correct edit button is selected.
Group variables based on the context
Let's say we have a test to create and edit an article. So we need one article's details for creating an article and another article's details for editing. So, we can group them based on the context.
In the above snippet, if we use title1
, and title2
in the same test, it will be difficult to understand which article's details are being used. But, if we use article.title
and updatedArticle.title
, it will make the test case more readable.