Boost Your Automated Test Workflow using TypeScript IntelliSense

Doug Hill
JavaScript in Plain English
3 min readFeb 26, 2021

--

In my previous article, I demonstrated how to maintain a unique set of ids. While that is extremely helpful, we can take it a step further and incorporate TypeScript IntelliSense to boost our test writing productivity and relieve some of the stress of error-prone copy and pasting.

Using “const assertions” in TypeScript

In TypeScript 3.4, “const assertions” were added as a dynamic new feature that allow us to define read-only string literals from an array.

Using this new TypeScript syntax (don’t forget the ‘as const’), we can export a String Literal Type derived from our array. What does that mean? In simpler terms, if we add Type “CyId” to a string parameter, the input parameter values are limited to only those in the id array we defined. When we use the CyId type, we can only use values “my-button” and “my-other-button” (or any other values we add to the array). In the next section, I will explain how helpful this can be.

Write Faster and With Less Errors — IntelliSense

In this code above, I made a simple function called ‘myExample’ that takes a CyId as a parameter. When I go to call the function, VSCode IntelliSense will know that CyId represents a string literal, and will suggest the values you can use. Now, you can use the IntelliSense to help you search for an id if you can’t remember the exact string you used.

If I try to call the function with a value that is not in the id array, TypeScript will flag it and tell me I have an invalid value. This way, we can be assured that we have entered a valid id. No more typos when entering in your test ids 👍.

Tying in Cypress

Now that we have our CyId Type established, let’s see how we can use this with Cypress.

Here I created a wrapper function, which allows us to restrict string inputs to those in the id array by using the CyId Type. This will also make our code cleaner by refactoring the boilerplate ‘[data-cy=${}]` out of all our tests.

Now, if we are in a test file, when we go to select our element with Cypress, we will have wonderful IntelliSense to guide us when we need to recall our test id. No more going back and forth between files and searching, TypeScript and VSCode tell you right there!

Conclusion

There is much more that can be done to make writing tests even cleaner and faster, but I did not want to overload readers in this post. As I continue to build out my own Cypress Test suite, I will continue to share my findings.

With all of the overhead that TypeScript can add to a project, it feels great to use it as it was intended and make it work for us! Happy coding!

Find more content at plainenglish.io

--

--

Full-Stack Web Developer with 10+ years of experience. Focus on Cloud Solutions with JavaScript, React and .Net