This is the first test file where there is some refactoring possible. Here we
can observe the following improvements that can be made:
- Move hard-coded strings to texts.
- Use relative URLs instead of absolute URLs.
- Move sensitive credentials to env variables.
- Wrap the steps in proper test blocks.
We're already familiar with the first two action items. So let's implement
them.
Let's take a look at the third action item. We need to move the sensitive
credentials to environment variables as mentioned in this chapter.
Since our app is running in a development mode and these credentials won't
work in other environments, we will extract these to a .env
file which we
will check-in to our project. This will ensure that anyone with access to the
repository can easily run the tests in the development environment and also
enables the provisions in the code to override the login credentials with the
sensitive data when we deploy the application.
To achieve this, let's create a new directory called config
within the e2e
directory and create a new file called .env
within that.
Now let's extract the email and password to the .env
file.
As mentioned in the Environment variables chapter,
we need to use the dotenv package to
access the environment variables in Playwright. So let's install the package
now.
Now let's use the dotenv
package to initialize the ENV variables in the
Playwright configuration.
Now let's replace the hard-coded credentials in the login setup with the
environment variables.
Now we will encounter a TypeScript error in the places we used the ENV
variables with the following message.
The reason for this error is because ENV variables may or may not be defined.
They are only defined if we set them up properly in the environment in where
we intend to use them. So it is very important to make sure that all ENV
variables are properly defined when setting up a new project in a new
environment.
In our case though, we have defined the variables in a .env
file which has
been checked into git. So it is guaranteed that they won't be undefined.
So we will use the not-null assertion operator (!) in TypeScript to let it know
that the value will always be defined.
Let's look at the last action item which is to use proper step blocks in the
tests. We should also ensure to avoid redundant awaits while performing this
refactoring.
We have not wrapped the step where we define the storage state in a step block
because its not actually a part of the test. Its a setup that supports the
upcoming steps.