App & Browser Testing Made Easy

Give your users a seamless experience by testing on 3000+ real devices and browsers. Don't compromise with emulators and simulators

Get Started free
Home Guide Cypress E2E Angular Testing: Advanced Tutorial

Cypress E2E Angular Testing: Advanced Tutorial

By Hamid Akhtar, Community Contributor -

One of the most important things you need to know as an Angular developer is how to test. You should test your app before putting it out there to ensure it works well. But the truth is that you always miss some bugs, even when you test.

End-to-end Angular testing is all about verifying the anticipated behavior of your Angular code. Errors in production can be expensive and difficult to correct, so it’s crucial to perform extensive testing before releasing the code. By creating tests, you can find bugs before they become significant issues.

Benefits of using Cypress E2E Angular Testing

Angular is an open-source framework for creating sturdy and robust web apps. Angular, as a Google product, is well-known for end-to-end application creation. All major names use this framework in web development, including Google, Forbes, WhatsApp, and the top Forbes 500 companies.

Cypress is an open-source JavaScript library that makes creating a wide range of automatic application tests simple. Previously, each sort of test necessitated the use of multiple libraries. With a single library, you can now run any tests you want. Furthermore, it is user-friendly and has comprehensive documentation, so the learning curve is short.

Since Cypress does not use WebDriver, it features a unique architecture. A Node.js application initiates the browser upon the launch of Cypress. The browser is not remotely controlled; rather, the tests are executed directly within the browser with the assistance of a browser plugin. The test runner offers a robust user interface for inspecting and debugging tests directly in the browser.

Accordingly, Cypress is advocated as the tool of choice for testing Angular apps as it is well-documented and well-cared-for. The end-to-end testing framework Cypress makes it easy to create useful tests.

Cypress Architecture and Directory Structure

To incorporate Cypress into a current Angular CLI project, simply use the Cypress Angular Schematic.

Launch this shell program in the folder containing your Angular project:

ng add @cypress/schematic

Important tasks accomplished by this command include:

  • To package.json, add Cypress and auxiliary npm packages.
  • Put the Cypress configuration file cypress.config.ts.
  • Update the angular.json configuration file to include the ng run commands.
  • A scaffold for your tests should be created in a subdirectory called cypress.
  • The installer prompts you to launch Cypress using the ng e2e program.
  •  It is safe to answer “Yes” if you are starting a fresh project without end-to-end tests.
  • Before version 12, ng e2e was used to launch Protractor in the Angular CLI. 
  • If you have any legacy Protractor tests in the project and want to continue running them with ng e2e, respond “No” to the question.

Writing the First Test

There is a subdirectory named cypress in the project directory. It includes

  • All TypeScript files specifically in this directory’s tsconfig.json configuration,
  • the end-to-end tests’ directory,
  • a support directory of test-related resources such as custom commands,
  • a fixtures directory for test data.

The e2e directory contains the test files. Each test is a TypeScript file with the extension .cy.ts.

  • To use the npx cypress run, npx cypress open, and ng run $project-name$:cypress-open commands, you must first initiate the Angular development server with ng serve in a separate shell. 
  • If the server is not accessible, Cypress will let you know by connecting to the baseUrl (http://localhost:4200).
  • The ng run $project-name$:cypress-run command launches the development server, begins the tests, and shuts down the server after the tests have finished.
  • Running “npx cypress open” will launch the test runner. In your situation, “E2E testing” should be selected as the testing method of choice.

Difference between E2E testing and Component testingThen, after picking a browser, hit the “Start E2E Testing” button. This brings up Cypress’s main user interface, the test runner, in your browser.

Understanding E2E Testing in Angular Applications

Keeping the front-end code in alignment with the actual API endpoints and responses from the back end is significantly more difficult. Even if the front-end and the back-end share data transfer type information, inconsistencies may occur.

End-to-end testing aims to identify flaws that cannot be detected by other automated tests. 

  • End-to-end testing begins with the launch of a browser, followed by visits to the application’s URL, and content reading, and makes keyboard and pointer input. 
  • A common scenario involves the test subject completing and submitting an online form.

You can classify end-to-end testing frameworks as either using or not using WebDriver. Until Angular 12, Protractor was the usual framework for end-to-end testing. When developing Protractor, WebDriver served as the foundation. In Angular 12+, Protractor is no longer supported. 

In freshly initiated CLI applications, no end-to-end testing infrastructure is set up by default. A mature end-to-end testing framework that does not rely on WebDriver is Cypress.

E2E testing vs Other Types of Testing

Unit tests and integration tests are quick and reliable but do not guarantee a fully functional application. End-to-end tests are sluggish and frequently fail erroneously, but they evaluate the application’s fitness.

Common E2E testing scenarios for Angular applications

Consider the scenario where evaluators must verify the availability of a Gmail account. It’s important to look at the following features:

  • Type this address into your browser’s address bar to go directly to the Gmail sign-in screen.
  • Log in with your real information.
  • Proceed to email. Look at the emails you have perused and the ones you haven’t.
  • Create a brand new message and send it off.
  • Give feedback and forward an email.
  • The Sent Items folder should be deleted. There, double-check your emails.
  • Navigate to the Spam folder. There, double-check your emails.
  • Choose “logout” to leave Gmail.

A testing environment closely matches the production environment is necessary for end-to-end tests. The entire application must be deployed, including the necessary front-end and back-end components. 

Testing on real device-browser-OS combinations is crucial instead of emulators and simulators for accurate results. Utilize 3000+ browser-device combinations on the BrowserStack Real Device Cloud and evaluate end-to-end under actual user scenarios.

Automate Cypress Testing on Cloud

Writing E2E tests in Cypress for Angular Applications

You are simulating a user’s activity when you conduct end-to-end tests. You can therefore distinguish between two parts when creating tests:

  • Interaction / Navigation: This part instructs Cypress on how to browse and use your application.
  • Assertion: Whenever you create a test, include this section. It outlines the prerequisites for a test to pass. The evaluation will succeed if the conditions are satisfied. Numerous methods exist for making an assertion, and this page lists them all.

Cypress by default, displays each test created in /cypress/integration. Inside that folder, make a fresh sample.spec.ts file.

In sample.spec.ts, put the following:

describe('The Home Page', () => { // (2)

it('Successfully loads', () => { // (2)

// NAVIGATION

// cypress will load '<http://localhost:4200>'. (3)

cy.visit('/');

// ASSERTION

cy.get('.highlight-card')

.children('span')

.should('have.text', 'testingApp app is running!');

});

});

There are two basic building blocks to be aware of, as is typical when writing tests:

  • describe(‘Name of block’, () => ); block: Constructs a block that compiles several linked tests into one unit.
  • it(“Descriptive term of the test,” ()=> {}”); block: The test itself. 
  • Since you speak in natural language, the test’s name should make logic about the topic at hand. Using the following code as an example: it(“should open dropdown when you click on open button,” () => {} ); Use a moniker that non-developers can understand.

Previously specified “baseUrl” to be “http://localhost:4200” in cypress.json. That path will be the default for all commands that call for a URL.

They represent Cypress instructions and mean:

  • get: Retrieving one or more DOM elements using the selector.
  • children: obtain each DOM element’s offspring from a group of DOM elements.
  • should: make an assertion. The assertion is automatically attempted again until it succeeds or expires.

Note: You must first serve your application in order to try it. Launch a fresh terminal, go to the project folder, and type ng serve.

Run npx Cypress Open if you haven’t already.Capture2Your test is on the left, and the usual Angular project is on the right. You’ve examined the welcome remark. You will see the result in green if the test is effective.

Setting up the environment for E2E testing

Install Angular CLI first if you haven’t already:

npm install -g @angular/cli

Next, build a fresh app with the CLI:

ng new my-awesome-app

When prompted, choose every default option.

Access the directory:

cd my-awesome-app

Additionally, a functional version of this tutorial can be downloaded from a Git repository here.

Let’s now include Cypress in the app:

npm install cypress -D

Open Cypress:

npx cypress open

You can follow the instructions on the Cypress Launchpad to configure your project.

Writing E2E tests in Cypress for Angular components

When you launch Cypress for the first time, the app will ask you whether you want to set up component testing or E2E testing. 

  • To launch the configuration wizard, click “Component Testing”.
  • Your framework—Angular in your case—is immediately detected by the Project Setup screen. To proceed, select “Next Action”.
  • Similarly, you must adhere to the instructions provided here to test your first component. 

Cypress renders your component in a real browser. You can use all of the techniques/tools that you would typically use during development, such as interacting with the component in the test runner and inspecting and debugging both your tests and the component’s code.

Writing E2E tests in Cypress for Angular forms

The heart of big web applications is the form. Forms are used primarily for enterprise applications to input and edit data. Therefore, the Angular framework’s ability to create complex forms is key to web application testing.

  • Massive web apps can’t function without forms. Data entry and editing via forms is central to many types of software, but especially enterprise apps. 
  • Therefore, a crucial part of the Angular framework is its ability to create complex forms.
  • Front-end forms typically require users to input text, select items, etc., before being submitted. The submission of information triggers a server response. 
  • Learning to use Cypress locators to locate HTML Elements is the first step towards completing and submitting forms with Cypress.

Synchronous validators are available for many form elements. Angular offers built-in concurrent validators like required, email, maxLength, pattern, etc.

Commence configuring your first testing module here.

Advanced Cypress E2E Angular Testing

1. Testing Angular services

Angular Services can be tested independently to ensure they’re performing as expected. Unit testing of services is commonly the easiest.

2. Testing Angular routing

It is the job of the Angular routing component to initiate the application’s navigation. It may be a component with a navigation bar, one or more RouterLink directives, or a component that directly invokes Router#navigate or Router#navigatebyUrl.

Sets up the router to be used for testing.

3. Testing Angular Http requests

Testing an HTTP request entails investigating the service or declaration that sent it. To achieve this, you must maintain the object’s current state and simulate its dependencies. The final crucial stage is to switch out HttpClientModule for HttpClientTestingModule so that HttpTestingController can be used to fake requests. 

Best Practices for Cypress E2E Angular Testing

  • Don’t try to interact with the view. When you test an app, you see its rendered form of it. Avoid engaging with it. Not even to log in. Cypress has to do these tests.
  • Avoid using [cy.exec()](<https://docs.cypress.io/api/commands/exec>)  or [cy.task()] (<https://docs.cypress.io/api/commands/task>) in Cypress to launch a web server. Before launching Cypress, launch the web server.
  • Avoid writing “single-assertion” or “tiny” tests. These tests are not unit tests; rather, they mimic the actions of an actual user. We should try to include as many assertions as possible that mimic a user’s actual journey or the steps required to complete a specific job in our tests.
  • Make sure tests are not dependent on others. Tests must always be able to be performed independently of one another and still pass. Create as many sections as you require.
  • Avoid storing the values returned by Cypress commands in variables.
cy.get('button').then(($btn) => {
// store the button's text
const txt = $btn.text()
})

You’ll need to use then() in the same manner that you use promises.

  • Don’t go to or attempt to communicate with servers you don’t manage. If you need to communicate with a third party via their API, you should always use [cy.request()](https://docs.cypress.io/api/commands/request>).

Closing Notes

In concluding this Cypress Angular tutorial, setting up Cypress is simple. You don’t have to do any setup. The essential aspect is how quickly the test can be run and how the results can be interpreted through the user-friendly interface.

Tags
Automation Testing Cypress

Featured Articles

Angular Visual Regression Testing: Tutorial

How to handle Cypress Asynchronous Behavior?

App & Browser Testing Made Easy

Seamlessly test across 20,000+ real devices with BrowserStack