Let’s assume you have an Angular component called UserComponent with a constructor that initializes some properties or dependencies.

UserComponent (user.component.ts)

import { Component, OnInit } from '@angular/core';
import { UserService } from './user.service';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit {
  userName: string;

  constructor(private userService: UserService) {
    this.userName = this.userService.getUserName();
  }

  ngOnInit(): void {
    // Other initialization logic
  }
}

UserService (user.service.ts)

import { Injectable } from '@angular/core';

@Injectable({
  providedIn: 'root'
})
export class UserService {
  getUserName(): string {
	return 'JohnDoe';
  }
}

Writing the Test:

Now, let’s write a test to verify that the constructor initializes the userName property correctly.

import { TestBed } from '@angular/core/testing';
import { UserComponent } from './user.component';
import { UserService } from './user.service';

describe('UserComponent', () => {
  let component: UserComponent;
  let userService: jasmine.SpyObj;

  beforeEach(() => {
	// Create a spy object for UserService
	userService = jasmine.createSpyObj('UserService', ['getUserName']);
    
	// Configure the TestBed to provide the UserService
	TestBed.configureTestingModule({
  	declarations: [UserComponent],
  	providers: [
    	   { provide: UserService, useValue: userService }
  	  ]
	});

	// Create an instance of the component
	component = TestBed.createComponent(UserComponent).componentInstance;
  });

  it('should initialize userName with the value from UserService', () => {
	// Arrange: Set up the spy to return a specific value
	userService.getUserName.and.returnValue('JohnDoe');

	// Act: Trigger the constructor by creating the component
      const fixture = TestBed.createComponent(UserComponent);
      component = fixture.componentInstance;
      fixture.detectChanges()

	// Assert: Check if the userName is initialized correctly
	expect(component.userName).toBe('JohnDoe');
	expect(userService.getUserName).toHaveBeenCalled();
  });
});

Explanation:

  1. TestBed Configuration: We configure the TestBed to provide the UserService using a spy object. This allows us to control the behaviour of getUserName during the test.
  2. Spy Object: We create a spy object for UserService and mock the getUserName method to return a specific value (‘JohnDoe’).
  3. Component Initialization: We create an instance of the UserComponent using TestBed.createComponent. This triggers the constructor, which initializes the userName property.
  4. Assertions: We assert that the userName property is correctly initialized with the value returned by UserService. We also verify that the getUserName method was called.

Running the Test:

To run the test, use the following command in your terminal:
ng test
This will execute all the tests in your Angular project, including the one we just wrote for the UserComponent.

Conclusion:

By following these steps, we can effectively test the constructor of an Angular component. This ensures that your component is initialized correctly and that any dependencies are properly injected and utilized.

Need Help With Angular Development?

Work with our skilled Angular developers to accelerate your project and boost its performance.

Hire Angular Developers

Support On Demand!

Related Q&A