Turn your manual testers into automation experts Request a DemoStart testRigor Free

Angular Testing

Angular is an open-source framework based on TypeScript. It also has a lot of similarities with its predecessor AngularJS, since the same team created it. The main difference between them is that AngularJS is JavaScript-based. Angular is a popular choice for building dynamic modern web and mobile applications, as well as native desktop applications. It’s actually more of a platform now than just a framework, providing development teams with design patterns and templates.

Websites built with Angular are meant to be thoroughly tested with some of the tools provided by the Angular team. This article gives you a good overview of the tools you ought to use to optimize your testing strategy.

We can group our testing efforts into three main types:
  • Unit testing
  • Integration testing
  • End-to-end testing

Angular Unit Testing

Per the testing pyramid, unit testing forms the base and acts as the first layer of verification. You should try to cover every single unit of code, like methods, functions, and some classes.

Using the Angular CLI, you get access to a host of frameworks that are shipped with Angular. Additionally, your project can be tested by just running a single command. Jasmine and Karma are available out of the box to you for writing and executing unit tests, respectively. However, you can use other frameworks as well to do the same. If the unit tests are being run in the build pipeline, then they undergo headless execution, else Karma opens the browser window for test runs. All test cases are saved with the .spec.ts file extensions.

In Angular, you can test components and services using TestBed, pipes, and attribute directives.

You can further read up on the setup and configuration of the test environment and CI setup over here.

Angular Integration Testing

After testing every unit of code, you need to check if two or more units can work together. This is what integration testing is meant to assess. With integration testing, your focus should be on checking if all external or third-party applications are getting invoked or written properly. You can create integration tests using Angular’s built-in testing tools.

Some ways of writing integration tests are:
  1. Components can be tested by invoking them from templates. They can also be tested by mocking data. Angular TestBed class facilitates this kind of testing.
  2. Services can be tested by mocking HTTP calls.
  3. You can write DOM tests to test pipes.

Below is an example of an integration test that verifies that the component displays the correct list acquired through a mocked API call:

import { async, TestBed } from '@angular/core/testing';
import { UsersComponent } from './users.component';
import { HttpClientTestingModule, HttpTestingController } from '@angular/common/http/testing';
import { UserService } from '../services/user.service';

const testUsers = [
  { name: 'User1', email: '[email protected]' },
  { name: 'User2', email: '[email protected]' },
  { name: 'User3', email: '[email protected]' }
];

describe('Integration: UsersComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      imports: [HttpClientTestingModule],
      declarations: [UsersComponent],
      providers: [UserService]
    }).compileComponents();
  }));
  
  it('creates the component', () => {
    const fixture = TestBed.createComponent(UsersComponent);

    expect(fixture.componentInstance).toBeTruthy();
  });
  
  it('loads the users and displays them if user clicks on button', () => {
    // acquire services and set up spies
    const fixture = TestBed.createComponent(UsersComponent);
    const userService: UserService = TestBed.get(UserService);
    
    spyOn(userService, 'get').and.callThrough();
    
    const httpController: HttpTestingController = TestBed.get(HttpTestingController);
    
    // tap on Load button
    const button = fixture.nativeElement.querySelector('#load');
    button.click();
    
    // validate outgoing request to API and provide test data
    expect(userService.get).toHaveBeenCalled();

    expect(fixture.componentInstance.users$).toBeTruthy();
    
    fixture.detectChanges();
    
    const testRequest = httpController.expectOne('https://placeholder.test.com/users');
    expect(testRequest.request.method).toEqual('GET');
    testRequest.flush(testUsers);
    
    // validate presentational changes
    fixture.detectChanges();
    
    const listItems = fixture.nativeElement.querySelectorAll('li');
    expect(listItems.length).toEqual(testUsers.length);
  });
});

Angular End-to-End Testing

End-to-end testing is the tip of the testing iceberg, covering the entire user paths. End-to-end tests are the most representative of all; however, they can be costly to build and slower to execute – therefore, they are done after unit and integration tests. End-to-end tests are extremely important to have, however, since they can easily point out any issues within your application.

You can build Angular e2e tests using the following tools:
  • Protractor
  • Selenium-based tools
  • testRigor

Protractor end-to-end testing

Protractor can be used for both Angular and AngularJS for executing your end-to-end tests. It is a wrapper around the Selenium WebDriver and is written in NodeJS. The test scripts can be written using Jasmine or another tool of your choice. Protractor acts as an interpreter of these scripts and sends necessary commands to the Selenium server.

To install Protractor, use npm:
npm install -g protractor

Then run protractor -version to verify that it’s working, along with webdriver-manager update and webdriver-manager start to start a server. Once that is done, you will have your Selenium server up and running, and can see status informatioŃ‚ at localhost:4444/wd/hub

All end-to-end test cases are saved in an e2e folder in .spec files. When executing these tests using the Angular CLI, you can execute the e2e folder from the command prompt. You can also choose to run specific cases if you wish to do so. However, with Protractor being in sunset mode, there are other options out there that can help smoothen end-to-end testing.

Selenium-based tools for end-to-end testing

There are a lot of Selenium-based tools on the market, which might be your preferred choice if you’re looking strictly for an open-source framework. The downsides are slow execution speed, complex test creation, and hefty test maintenance. You can look into the official documentation here, and the main downsides you might encounter here.

testRigor end-to-end testing

testRigor is a powerful tool created to make functional end-to-end testing accessible to virtually anyone. The biggest advantages are the ease of creating even lengthy cross-platform tests and virtually non-existent test maintenance. You can easily cover web and mobile scenarios in one test, which is something very few tools can perform well. testRigor is also an excellent choice for BDD environments since it incorporates BDD principles without additional coding and syntax complications.

Some salient features of testRigor that can come in handy when testing Angular-based applications are:
  1. No-code tests mean anyone on the team is able to contribute to test creation.
  2. Cross-browser and cross-platform tests
  3. Proven way to create tests 15x faster and with 95% less test maintenance
  4. Out of the box support for many additional features, such as 2FA testing for Gmail, text messages, and Google authenticator.
  5. No reliance on the implementation details. Tests are built purely from an end-user’s perspective
  6. Its AI-powered engine can interpret the relative position of the element from the mentioned command. Thus any changes in the locator value of the element do not break the test.
  7. No need to set up additional infrastructure to execute test cases.
  8. Has provision to support 2FA testing support for Gmail, text messages, and Google authenticator.
  9. … and many more. You can see the full list here
Here’s how an example test case looks like:

click on "QUICK VIEW" if exists
check that table "options" at row "12" and column "Name" contains "David"
check checkbox within the context of row "12" is checked
click on "Delete" within the context of "section2"
check that page contains stored value from "successDeleteMsg"

From the above test script you can see that identifying elements on the UI is as easy as mentioning their relative position, as seen on the screen.

Conclusion

Angular is a popular framework used extensively to create web pages. Just like any other application, testing Angular projects is essential. With the above mentioned testing tools, you can ensure that your application is in tip top shape and competent in the market.

Join the next wave of functional testing now.
A testRigor specialist will walk you through our platform with a custom demo.