Testing Library offers simple and complete testing utilities that encourage good testing practices. It provides many convenient queries, such as ByRole and ByLabelText. Furthermore, it also allows us to create our own custom queries.
These queries can be utilized in three ways:
Creating custom queries like getByCustomQuery and findByCustomQuery can greatly enhance the testing experience while reducing repetitive testing code, just as the custom render method effectively includes all providers for us.
In this post, we will explore the reasons for creating custom queries for Testing Library and demonstrate how to do so effectively.
Note: For further details, you can also refer to the official documentation on Add custom queries, pending the merge of this PR.
Reason: The Thousand Separator for Numbers
Frontend developers often need to display prices with thousand separators:
In your tests, you might need to import the thousandSeparator function every time you want to test a number with a thousand separator:
While this works, the developer experience can be improved. Let's create a custom query for this purpose. It's easy with the buildQueries provided by Testing Library.
Implementing a Custom Query
Simply define two error handlers, getMultipleError and getMissingError.
That's it!
Making Custom Queries Global
Suppose we are re-exporting all custom queries in the custom-queries.
Testing our Custom Query
Having created the *ByThousandSeparatedNumber query and customized render, screen, and within, let's write some simple tests to verify them.
Conclusion
By structuring your code in this manner, the next time you need a new custom query, you can simply create one under the test-utils/custom-queries/ folder and start using it in your tests right away. This approach makes your testing process more efficient and streamlined.