Angular
  • Angular learning
  • Angular
    • Change Detection
      • Angular Change Detection Strategies
      • Understanding Change Detection Strategy in Angular
    • Angular Components Overview
      • Lifecycle hooks
      • View encapsulation
    • Text interpolation
    • Pipes
    • ARIA
    • Event binding
    • Directives
    • Dependency injection in Angular
    • Difference between Template-Driven and Reactive Forms
    • Guards
    • Resolvers
      • Resolver example
  • Memory management in Angular applications
  • Renderer2
  • Angular test
    • Testing
      • The different types of tests
      • Some testing best practices
      • Angular Service Testing in Depth
        • About Jasmine
        • Jasmine - Test suites
        • Implementation of First Jasmine Specfication
        • spyOn() & jasmine.createSpyObj()
        • beforeEach()
        • Testing services
        • Disabled and Focused Tests
        • flush
        • HttpTestingController
        • Sample code
      • Angular Component Testing in Depth
        • Intro to Angular Component testing
        • DOM interaction
        • Trigger Change Detection
        • Test Card List Test Suite Conclusion
        • Window.requestAnimationFrame()
        • Asynchronous Work (Jasmine)
        • Cooperative asynchronous JavaScript: Timeouts and intervals
        • FakeAsync - Asynchronous Work (Jasmine) part 2
        • tick()
        • Sample codes
      • Testing Promised-based code-intro Microtasks
        • Microtasks
        • Micro-tasks within an event loop (Summary)
        • Macro-tasks within an event loop (Summary)
        • Test promised Microtasks (code)
      • Using fakeAsync to test Async Observables
      • Cypress.io
        • Create our first e2e test
      • Angular CLI code coverage and deployment in prod mode.
      • Travis CI
  • Angular best practices
    • Angular best practices
      • Security
      • Accessibility in Angular
      • Keeping your Angular projects up-to-date
    • Bootstrapping an Angular Application
      • Understanding the File Structure
      • Bootstrapping Providers
    • Components in Angular
      • Creating Components
      • Application Structure with Components
        • Accessing Child Components from Template
        • Using Two-Way Data Binding
        • Responding to Component Events
        • Passing Data into a Component
      • Projection
      • Structuring Applications with Components
      • Using Other Components
  • Reactive extensions
    • RxJS
      • RxJS Operators
      • of
      • Observable
      • async pipe (Angular)
      • Interval
      • fromEvent
      • Pipe
      • Map
      • Tap
      • ShareReplay
      • Concat
      • ConcatMap
      • Merge
      • MergeMap
      • ExhaustMap
      • fromEvent
      • DebounceTime
        • Type Ahead
      • Distinct Until Changed
      • SwitchMap
      • CatchError
      • Finalize
      • RetryWhen
      • DelayWhen
      • ForkJoin
      • First
      • Interview Questions
      • Zip
  • NgRx
    • What's NgRx
      • Actions
      • Reducers
      • Selectors
      • 🙅‍♂️Authentication guard with NgRX
      • @ngrx/effects
        • Side-Effect refresh survivor
  • Interview Q&A
    • Angular Unit Testing Interview Questions
    • Angular Questions And Answers
  • Angular Advanced
    • Setting up our environment
      • Understanding Accessors (TS)
      • The host & ::ng-deep Pseudo Selector
Powered by GitBook
On this page
  • Introduction
  • Angular Unit Testing
  • Angular End-to-end Testing
  • Conclusion

Was this helpful?

  1. Angular test

Testing

Introduction

Testing is an integral part of any Angular app. Apart from the peace of mind it brings, ensuring that your Angular app is tested gives you the following benefits:

  • Fewer bugs in production

  • Fewer code regressions

  • More maintainable code

  • Faster refactoring and upgrades

  • Less dead code

In this guide, you will get a closer look into the two types of testing that the Angular framework facilitates: unit and end-to-end testing. You will learn how you can use these two types of testing in order to take advantage of all of the benefits mentioned above.

Angular Unit Testing

Your Angular unit tests comprise the foundation of your app's testing story. The purpose of unit tests is to test your codebase function by function. Angular makes it easy for you to write unit tests for all of your Angular entities, from components to pipes and everything in between. By default, unit tests are generated for you when you use the Angular CLI's generate command to add a new entity. You can run ng generate component dog-breed to create a new component with a companion unit test along with it.

Let's say you have the following unit test for your DogBreedComponent:

import { TestBed, async, ComponentFixture } from '@angular/core/testing';
import { DogBreedComponent } from './dog-breed.component';

describe('DogBreedComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        DogBreedComponent
      ],
    }).compileComponents();
  }));

  it('gets instantiated', () => {
    const fixture = TestBed.createComponent(DogBreedComponent);
    const comp = fixture.componentInstance;
    expect(comp).toBeTruthy();
  });

  it(`should contain a breed description`, () => {
    const description = 'This is a breed description',
              fixture = TestBed.createComponent(DogBreedComponent),
                 comp = fixture.componentInstance,
          baseElement = fixture.nativeElement;

    comp.description = description;
    fixture.detectChanges(); // Force our changes to run through Angular's change detection mechanim

    expect(baseElement.querySelector('.breed-description').textContent).toEqual(description);
  });

});

The above unit test file tests that the DogBreedComponent properly instantiates and displays the description within its template. Notice how you are able to test this component in isolation. The purpose of unit tests is to test each individual piece of functionality of your app. This buys you granular guarantees about your app and ensures that your code will be more maintainable and easier to refactor when the time comes.

Angular End-to-end Testing

Unlike unit tests, end-to-end tests focus on the big picture. The purpose of end-to-end tests is to ensure that your app functions properly from the perspective of the user. Whereas unit tests focus on testing individual pieces of your app in isolation, end-to-end tests run against a running instance of your app.

Normally, end-to-end tests are created for every page within your app. Here is an example of an end-to-end test suite for the dog breed app's home page:

import { browser, by, element } from 'protractor';

describe('Dog Breed Home Page', () => {
  it('should display the app title', () => {
    browser.get('/');

    expect(
        element(by.id('home-page-title').getText()
    ).toEqual('Welcome to Breed-topia!');
  });
});

See the difference between end-to-end tests and unit tests? The simple test suite above actually navigates to your app inside of a browser (typically headless Chrome) and tests that it looks and functions properly. Inside of end-to-end tests, it is your job to pretend to be the user as you navigate your app. End-to-end tests ensure that your app is free from regression bugs that might be introduced by new features or refactoring. They are integral in order to ensure your production build is functioning properly from the perspective of the user.

Conclusion

Through easy unit and end-to-end testing integration, Angular provides you many benefits. By writing unit tests, you can guard your code against regressions and provide a strong foundation that facilitates maintainability and ease of growth for your app. In the same way, end-to-end tests that run against your Angular app will ensure that your app functions as expected. This will ward off pesky bugs that can be introduced into production and will help facilitate the creation and/or extension of continuous integration and deployment pipelines for your app.

PreviousRenderer2NextThe different types of tests

Last updated 4 years ago

Was this helpful?

Testing is absolutely necessary to ensure your Angular app is maintainable. Check out the for more information.

documentation for testing Angular apps