Angular - Testing & Building a Project



In this chapter will discuss the following topics −

  • To test Angular Project
  • To build Angular Project

Testing Angular Project

During the project setup, the required packages for testing are already installed. There is a .spec.ts file created for every new component, service, directive, etc. We are going to use jasmine to write our test cases.

For any changes added to your component, services, directives or any other files created, you can include your test cases in the respective .spec.ts files. So most of the unit testing can be covered at the beginning itself.

To run the test cases, the command used is as follows−

ng test

Below is the app.spec.ts file for app.ts

app.spec.ts

import { TestBed } from '@angular/core/testing';
import { App } from './app';

describe('App', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({
      imports: [App],
    }).compileComponents();
  });

  it('should create the app', () => {
    const fixture = TestBed.createComponent(App);
    const app = fixture.componentInstance;
    expect(app).toBeTruthy();
  });

  it('should render title', async () => {
    const fixture = TestBed.createComponent(App);
    await fixture.whenStable();
    const compiled = fixture.nativeElement as HTMLElement;
    expect(compiled.querySelector('h1')?.textContent).toContain('Hello, angular-app');
  });
});

app.ts

import { Component, signal } from '@angular/core';
import { RouterOutlet } from '@angular/router';

@Component({
  selector: 'app-root',
  imports: [RouterOutlet],
  templateUrl: './app.html',
  styleUrl: './app.css'
})
export class App {
  protected readonly title = signal('angular-app');
}

Now let us run the command to see the test cases running.

ng test
Initial chunk files | Names         | Raw size
spec-app.js         | spec-app      | 47.95 kB |
chunk-EYSVNVHY.js   | -             |  4.55 kB |
init-testbed.js     | init-testbed  |  1.20 kB |
styles.css          | styles        | 56 bytes |

                    | Initial total | 53.76 kB

Application bundle generation complete. [1.229 seconds] - 2025-12-02T06:41:43.957Z

Watch mode enabled. Watching for file changes...

 DEV  v4.0.14 D:/Projects/angular-app

 ✓  angular-app  src/app/app.spec.ts (2 tests) 79ms
   ✓ App (2)
     ✓ should create the app 55ms
     ✓ should render title 23ms

 Test Files  1 passed (1)
      Tests  2 passed (2)
   Start at  12:11:44
   Duration  1.07s (transform 107ms, setup 238ms, import 112ms, tests 79ms, environment 495ms)

 PASS  Waiting for file changes...
       press h to show help, press q to quit

Incase of any failure, it will show the details as follows −

To do that, let us change the app.spec.ts as follows −

import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
   beforeEach(async(() => {
      TestBed.configureTestingModule({
         imports: [
            RouterTestingModule
         ],
         declarations: [
            AppComponent
         ],
      }).compileComponents();
   }));
   it('should create the app', () => {
      const fixture = TestBed.createComponent(AppComponent);
      const app = fixture.debugElement.componentInstance;
      expect(app).toBeTruthy();
   });
   it(`should have as title 'angular7-app'`, () => {
      const fixture = TestBed.createComponent(AppComponent);
      const app = fixture.debugElement.componentInstance;
      expect(app.title).toEqual('Angular 7'); // change the 
      title from angular7-app to Angular 7
   });
   it('should render title in a h1 tag', () => {
      const fixture = TestBed.createComponent(AppComponent);
      fixture.detectChanges();
      const compiled = fixture.debugElement.nativeElement;
      expect(compiled.querySelector('h1').textContent).toContain(
         'Welcome to angular7-app!');
   });
});

In the above file, the test case checks for the title, Angular 21. ng test will rerun and shows failure result as shown below −

 RERUN  rerun test x1

 ❯  angular-app  src/app/app.spec.ts (2 tests | 1 failed) 92ms
   ❯ App (2)
     ✓ should create the app 61ms
     × should render title 30ms

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯ Failed Tests 1 ⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯

 FAIL   angular-app  src/app/app.spec.ts > App > should render title
AssertionError: expected 'Hello, angular-app' to contain 'Hello, angular-app 21'

Expected: "Hello, angular-app 21"
Received: "Hello, angular-app"

 ❯ src/app/app.spec.ts:22:55
     20|     const compiled = fixture.nativeElement as HTMLElement;
     21|     // add 21 to title
     22|     expect(compiled.querySelector('h1')?.textContent).toContain('Hello, angular-app 21');
       |                                                       ^
     23|   });
     24| });

⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯⎯[1/1]⎯


 Test Files  1 failed (1)
      Tests  1 failed | 1 passed (2)
   Start at  12:16:23
   Duration  434ms

 FAIL  Tests failed. Watching for file changes...
       press h to show help, press q to quit

All the failed test-cases for your project will be displayed as shown above in command line.

Similarly, you can write test cases for your services, directives and the new components which will be added to your project.

Building Angular Project

Once you are done with the project in Angular, we need to build it so that it can be used in production or staging.

The configuration for build, i.e., production, staging, development, testing needs to be defined in your src/environments.

At present, we have the following environments defined in src/environment −

Environments

You can add files based on your build to src/environment, i.e., environment.staging.ts, enviornment.testing.ts, etc.

At present, we will try to build for production environment. The file environment.ts contains default environment settings and details of the file as follows −

export const environment = {
   production: false
};

To build the file for production, we need to make the production: true in environment.ts as follows −

export const environment = {
   production: true
};

The environment replacement from default to production which we are trying to do are defined inside angular.json fileReplacements section as follows −

"production": {
   "fileReplacements": [
      {
         "replace": "src/environments/environment.ts",
         "with": "src/environments/environment.prod.ts"
      }
   ],
}

When the command for build runs, the file gets replaced to src/environments/environment.prod.ts. The additional configuration like staging or testing can be added here as shown in the below example −

"configurations": {
   "production": { ... },
   "staging": {
      "fileReplacements": [
         {
            "replace": "src/environments/environment.ts",
            "with": "src/environments/environment.staging.ts"
         }
      ]
   }
}

So the command to run the build is as follows −

ng build --configuration = production // for production environment
ng build --configuration = staging // for stating environment

Now let us run the build command for production, the command will create a dist folder inside our project which will have the final files after build.

Ng Build

The final files are build inside dist/ folder which can be hosted on the production server at your end.

Dist
Advertisements