We are going to use a special tag data-test
for the purpose of integration testing, especially for the business purpose.
What is this tag?
Let’s see with an example:
<button data-test="logout">Logout<button>
The usage is pretty simple, just apply data-test
tag to any DOM element you want.
Why do we need another tag? Do we have id
, class
, role
, and more?
Business semantic
I was told by our testing engineer the tag is introduced for the semantic purpose, however in the end of the conversation, I’m pretty sure his semantics is not perfectly align with what I understand as the DOM semantics. Let’s hear out his version.
As long as there’s a logout button on the screen, attaching a logout
key should provide us a way to consistently to locate it. Moreover, if the developer decides to use a div
instead:
<div data-test="logout">Logout</div>
We should still be able to locate it, since the test were coded with the data-test
tag instead of the element type. Of course, this tag data-test
is agreed upon by the team; because we can also use id
or class
for this example.
Can we uniquely define an element with data-test
? The answer is no. Not only we can’t, but also that’s not the goal. Let’s take a look at the table to better understand this tag:
<table data-test="personList">
<tr data-test="person">
<td data-test="firstName">
...
</td>
</tr>
</table>
To find the first person’s first name in the table, we will find the “personList”, and then look at the first “person”, and then the first column “firstName” is the one we are looking for.
Notice the sentence doesn’t involve element words such as table`, tr
and td
; and doesn’t involve table semantic words such as row
and column
; instead it used person
and firstName
as well as the personList
.
Find the person list, get the first person, and find his first name.
It’s pretty obvious now, the data-test
isn’t created for uniqueness, but more like what a role
is.
Now comes the benefits, in case we change the table implementation into a list:
<ul data-test="personList">
<li data-test="item">
<span data-test="firstName">
...
</span>
</li>
</li>
The test can run without much modification if any. Because we still want to “find the personal list, get the first person, and find his first name”. I guess I can conclude this as what he meant by business semantics.
Summary
A data-test
tag is introduced for testing the business semantics. This could potentially make testing more productive especially when the project grows bigger.