- [Instructor] Before we begin,
make sure you're on the 03_03b branch of the project
to follow along with this video.
Accessing elements within component
helps us test their existence within the components.
This is good and covers a lot of testing scenarios,
but what if we want to test behavior?
The Explore California login form
requires an email and password.
When we type this in, I click the login button,
we are navigated to the profile page.
But what if we leave the fields blank and try to log in?
This time, an error message is displayed
instructing us to enter the login credentials.
This behavior is one that can be tested
to be sure that users are not allowed
to log in without entering their credentials.
So let's go into our editor and write the test.
In order to test the login error functionality,
we need to access the login button
and trigger a click event on it.
To achieve this, we first need to import
the fire event object from the view testing library.
The fire event object helps us simulate user events
like click, mouse over, mouse in, and so on
in our test environment.
For this exercise, we'll be using the click method
of the fire event object.
Events fired on the elements using the fire event methods
are asynchronous processes and return a promise.
Thus, we need to add the async keyword
to our tests callback function.
Next, we get to reference to our login button
using the get by text method
to search for the button's label.
Now let's fire the click event on the login button
using the click method of the fire event object.
Because we did not fill in any of the login credentials,
the error message should be displayed
after firing the click event on the button.
Let's confirm that we have the message on the screen
by using the get by text method
to search for the error message.
Good, we can now save the file and run our test.
Everything goes fine and our tests pass as expected.
However, the practice of testing is all about
finding bugs in our application.
So let's see what happens if we do not fire the click event
but try to search for the error message.
Let's comment out the line that fires the event
and see what happens when we try to search
for the error message without clicking the button.
Save the file and add back to the command line
to run the test.
Just now, we post that the login error message
cannot be found, which is good, because the component
is currently not in the state
that causes the error to show up.
Understanding that testing is the practice of adding value
to an application by finding our moving bugs
helps us better understand the purpose of the exercise.
This enables us to write more tests
that try to break the system to expose bugs.