Web automation is a crucial skill for test automation engineers—but can be daunting for beginners. Using Cypress with TypeScript is a powerful way to successfully automate the project application under test. For those just starting out with test automation, this blog aims to show you how to approach test automation with the Cypress framework, combined with TypeScript. It will walk you through the basics, helping you build confidence and skill in no time.
Why should you choose Cypress with TypeScript over just Cypress?
Choosing Cypress with TypeScript over just Cypress provides various advantages, especially for larger projects or teams using large test suites. The main advantages are:
Better code quality
When it comes to maintaining high standards in test automation, the quality of your code is crucial. TypeScript enhances code reliability and readability, making it an essential tool for scalable and maintainable test suites.
- Type safety. TypeScript helps catch errors early during development thanks to its static type checking. For example, if we are passing the wrong type of argument to a function, like a number instead of a string, we will know immediately because TypeScript throws an error. In test automation, this is called type safety.
- Autocompletion. With TypeScript, IDEs like VS Code provide autocompletion, which is a way to reduce errors, while receiving code suggestions.
- Scalability. Typescript’s use of interfaces and type definitions makes it possible for team members to follow the same structure, ensuring consistency across the project and making it easier to scale the project.
Enhanced developer experience
Cypress is an intuitive, JavaScript-based testing framework designed for end-to-end testing. Its detailed documentation and user-friendly interface make it a great choice. And when combined with TypeScript, the benefits multiply, offering type safety, better readability, and maintainability. Keep in mind, however, that extensive knowledge of JavaScript is necessary to implement Typescript.
When I first started with test automation, I chose Cypress as a framework because it provided immediate feedback. You don’t need to install Drivers like with Selenium, and by using TypeScript, QA automation engineers can avoid errors that could fail their tests because of incorrect data types.
Setting up your first project
Setting up a project is the first obstacle for many beginners. It involves creating a base test environment for running tests with Cypress and TypeScript, ensuring that everything is properly configured to avoid common pitfalls. Taking the time to set up your project correctly can save you from a lot of frustration later on.
Here is what is usually required when setting up your first test automation project using Cypress and TypeScript:
- Install Node.js and npm. Both are essential for managing dependencies and running your project.
- Initialize a New Project, create a new directory for your project, and run the npm init command to set up a package.json file. This file will manage the project's dependencies.
- Install Cypress and Typescript by using the Terminal command: npm install cypress typescript --save-dev.
- Create initial tests. Beginners should start automating simple tests to get used to the code and understanding the logic.
Here’s how a simple LogIn test looks like, using TypeScript data types, with a few lines of descriptive code, reusable code in POM and readable even for non-technical stakeholders.
import {ALEKSANDAR_JOVANCHEV, customerLoginBtn, loginBtnSubmit, selectCustomer, welcomeUserText } from "../pages/login";
describe("Login as Aleksandar Jovanchev", () => {
it("Login as Aleksandar Jovanchev",()=> {
cy.visit("");
customerLoginBtn().click();
selectCustomer(ALEKSANDAR_JOVANCHEV)
loginBtnSubmit().should('be.visible');
loginBtnSubmit().click();
welcomeUserText().should('be.visible').and('have.text', ALEKSANDAR_JOVANCHEV);
})
})
export const ALEKSANDAR_JOVANCHEV : string = "Aleksandar Jovanchev";
As a beginner, you should start automating simpler tests, like the example above with verifying a login form. By focusing on functionalities like ensuring that the fields and buttons on the login page are visible and work as expected, you can gain confidence in writing test scripts for more complex test scenarios.
Common challenges beginners face
Getting started with Cypress and TypeScript can come with its fair share of hurdles. Understanding these common challenges and how to overcome them will help you build a solid foundation and become more confident in your test automation skills.
- Dynamic locators. Sometimes tests can fail because some web elements have IDs that change frequently, causing Cypress to throw an error. Usually on a real project developers create attributes like data-testid, that rarely change and are recommended to use. If there is no data-testid attribute, you should seek other reliable ones, in order to make sure your tests pass. Consistent locators ensure that code remains reliable and easily maintainable.
- Throwing TypeScript errors. TypeScript’s strict typing is a real headache at the beginning. By carefully reading error messages and consulting documentation, you can troubleshoot and learn faster. Over time, you will find that these errors contribute to achieving cleaner, more robust code. TypeScript always makes sure that data types are correct. As you can see below, when a function is declared, you should specify the parameters type.
selectLanguage() {
cy.get(".language > a").click(); // Switch the language
}
openLoginForm() {
cy.get("#openLoginLayer").click();
}
enterUsername(username: string) {
cy.get("#username").click().type(username);
}
enterPassword(password: string) {
cy.get("#password").click().type(password);
}
And this is how we implement it in tests:
mobilebiddingLoginPage.visit();
mobilebiddingLoginPage.clickLoginButton();
mobilebiddingLoginPage.typeUsername(user.username);
mobilebiddingLoginPage.typePassword(user.password);
mobilebiddingLoginPage.submitLoginBtn();
Please make note of how our function parameters are typed. If we call any arguments different than the string, TypeScript will throw an error. This is how TypeScript helps reduce the errors.
- Flaky tests. At first, some tests sometimes fail due to timing issues. For example, the Login form test is executed and completed so fast that when Cypress clicks the login button, the test fails because the Log in button is not yet loaded and clickable. There is a way to overcome these issues by using Cypress’ built-in features to handle retries and waiting. Therefore, properly using commands like cy.wait() or cy.retry() can make tests more stable.
cy.wait(1000);
userMenuPage.openUserMenu();
userMenuPage.selectAccount();
userMenuPage.clickEditButton();
userMenuPage.editJobTitle(user.jobTitle);
userMenuPage.submitEdit();
});
});
Building reusable test logic with Page Object Model
As you write more tests, you will notice more frequent and repetitive patterns. For example, the flow like logging into an application appears frequently. A good practice is to organize these actions into reusable functions in separate pages, where for each page we test, we create a class, and inside this class we create functions that we will import in our test and use. This is practically creating a Page Object Model pattern that not only saves time but also makes tests easier to maintain and debug. For instance, if a username ID is changed in DOM, we only have to change it inside the username function in the page. Using hardcoded values in multiple tests means that whenever a change is needed, test automation engineers have to manually update all the tests with those hardcoded values. This creates unnecessary and labor-intensive work, meaning it’s almost impossible to complete.
Here is how a simple POM pattern should look like:
export class UserMenuPage {
openUserMenu() {
cy.get("#userMenu").click();
}
selectAccount() {
cy.get(":nth-child(3) > .row > .col-12 > .dropdown-item").click();
}
clickEditButton() {
cy.get(".col-md-6 > .btn").click();
}
editJobTitle(jobTitle: string) {
cy.get('input[data-testid="input-TITLE"]').click().type(jobTitle);
}
submitEdit() {
cy.get('button[data-testid="submitButton"]').click({ force: true });
}
}
We can reuse these methods in numerous tests whenever we encounter these UI elements. And, of course, if a certain UI element is changed, we can change it here in the POM, instead of changing it in all of the tests.
Tips for success as a beginner
- Start small. Focus on one feature at a time to avoid confusion and being overwhelmed.
- Ask for assistance and help. Do not hesitate to reach out to teammates, watch online courses, or consult forums for help.
- Use documentation. Cypress and TypeScript have excellent documentation to guide you.
- Collaborate with developers. Having clear communication with developers can ease locator issues and improve test reliability.
- Seek feedback. Share your work with teammates to learn from their suggestions and improve.
Learning Cypress and TypeScript will teach you:
- The importance of persistence and patience.
- How to structure and maintain test scripts effectively.
- How to debug systematically and seek feedback to grow as an automation engineer.
It’s always recommended to do some reading at the beginning, especially the official Cypress documentation.
Here, you can find out everything you need to know about setting up a Cypress project, installing all the relevant dependencies, and how to implement TypeScript as well. Similarly, to deepen your knowledge of TypeScript, check out the official documentation.
Conclusion
Starting your journey in web automation can be hard work, but Cypress and TypeScript provide a solid foundation. With each test you write, your confidence and skills will grow as you continue automating more complex test scenarios and flows. Every expert was once a beginner. So keep practicing, stay curious, and watch your test automation skills improve.
Ready to simplify your web automation journey with expert guidance? Whether you're just starting out or looking to scale your testing efforts, we're here to help. Contact us to learn more about our software quality assurance services and how they can benefit your project.