DEV Community

Fran Saoco
Fran Saoco

Posted on • Edited on

1 1 1

Testing Angular Components with Services using Jest

Mock services in component tests to isolate behavior, control responses, and validate interactions without testing the service itself. This keeps tests fast, focused, and free from external dependencies.

another-component.ts

import { Component, inject } from '@angular/core';
import { MySuperService } from '../my-super.service';

@Component({
  selector: 'app-another',
  template: `<p class="message">My message: {{message}}<p>`,
})
export class AnotherComponent {
  mySuperService = inject(MySuperService);
  message = '';
  showMessage() {
    this.message = this.mySuperService.getMessage();
  }
}
Enter fullscreen mode Exit fullscreen mode

another-component.spec.ts

import { ComponentFixture, TestBed } from '@angular/core/testing';

import { AnotherComponent } from './another.component';
import { MySuperService } from '../my-super.service';
import { By } from '@angular/platform-browser';

describe('AnotherComponent', () => {
  let component: AnotherComponent;
  let fixture: ComponentFixture<AnotherComponent>;

  const mockMySuperServiceMock = {
        getMessage: jest.fn().mockReturnValue('Super message')
    };

  beforeEach(() => {
    TestBed.configureTestingModule({
      declarations: [AnotherComponent],
            providers: [
        { provide: MySuperService, useValue: mockMySuperService },
      ]

    });
    fixture = TestBed.createComponent(AnotherComponent);
    component = fixture.componentInstance;
    fixture.detectChanges();
  });

  it('should create', () => {
    expect(component).toBeTruthy();
  });

  describe ('.showMessage', () => {
    it('should show the message', () => {
      expect(mockMySuperService.getMessage).not.toHaveBeenCalled();
      expect(component.message).toBe('');
      component.showMessage();
expect(mockMySuperService.getMessage).toHaveBeenCalledTimes(1);
      expect(component.message).toBe('Super message');
    });

    it('should display message in template', () => {
      component.showMessage();
      fixture.detectChanges();

      const messageEl = fixture.debugElement.query(By.css('p.message'));
      expect(messageEl.nativeElement.textContent).toContain('Super message');
    });
  });

});
Enter fullscreen mode Exit fullscreen mode

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video →

Top comments (0)

Quickstart image

Django MongoDB Backend Quickstart! A Step-by-Step Tutorial

Get up and running with the new Django MongoDB Backend Python library! This tutorial covers creating a Django application, connecting it to MongoDB Atlas, performing CRUD operations, and configuring the Django admin for MongoDB.

Watch full video →

👋 Kindness is contagious

Explore a trove of insights in this engaging article, celebrated within our welcoming DEV Community. Developers from every background are invited to join and enhance our shared wisdom.

A genuine "thank you" can truly uplift someone’s day. Feel free to express your gratitude in the comments below!

On DEV, our collective exchange of knowledge lightens the road ahead and strengthens our community bonds. Found something valuable here? A small thank you to the author can make a big difference.

Okay