DEV Community

Fran Saoco
Fran Saoco

Posted on • Edited on

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

AWS Security LIVE! Stream

Streaming live from AWS re:Inforce

Join AWS Security LIVE! at re:Inforce for real conversations with AWS Partners.

Learn More

Top comments (0)

ACI image

ACI.dev: Fully Open-source AI Agent Tool-Use Infra (Composio Alternative)

100% open-source tool-use platform (backend, dev portal, integration library, SDK/MCP) that connects your AI agents to 600+ tools with multi-tenant auth, granular permissions, and access through direct function calling or a unified MCP server.

Check out our GitHub!

👋 Kindness is contagious

Dive into this thoughtful piece, beloved in the supportive DEV Community. Coders of every background are invited to share and elevate our collective know-how.

A sincere "thank you" can brighten someone's day—leave your appreciation below!

On DEV, sharing knowledge smooths our journey and tightens our community bonds. Enjoyed this? A quick thank you to the author is hugely appreciated.

Okay