How to test Angular services

Angular services contain critical business logic and data operations that must be thoroughly tested to prevent bugs in production applications. With over 12 years of Angular development experience since 2014 and as the creator of CoreUI, I’ve written comprehensive test suites for countless enterprise services. Testing services is simpler than testing components because services have no template or DOM to manage, focusing purely on logic and method outputs. The approach uses TestBed to inject the service and Jasmine to assert that methods behave correctly with various inputs.

Use TestBed to inject services and Jasmine to test service methods and logic.

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

describe('UserService', () => {
  let service: UserService

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [UserService]
    })
    service = TestBed.inject(UserService)
  })

  it('should be created', () => {
    expect(service).toBeTruthy()
  })

  it('should validate email format', () => {
    expect(service.isValidEmail('[email protected]')).toBe(true)
    expect(service.isValidEmail('invalid-email')).toBe(false)
  })

  it('should calculate user age', () => {
    const birthDate = new Date('1990-01-01')
    const age = service.calculateAge(birthDate)
    expect(age).toBeGreaterThan(30)
  })

  it('should filter active users', () => {
    const users = [
      { id: 1, name: 'John', active: true },
      { id: 2, name: 'Jane', active: false }
    ]
    const activeUsers = service.getActiveUsers(users)
    expect(activeUsers.length).toBe(1)
    expect(activeUsers[0].name).toBe('John')
  })
})

Best Practice Note

For services with dependencies, provide mock implementations in the TestBed configuration to isolate the service under test. Use spies with spyOn to track method calls and return values. For services that make HTTP calls, use HttpClientTestingModule and HttpTestingController to mock requests. Test both success and error scenarios to ensure proper error handling. This is the same testing approach we use in CoreUI for Angular—every service method is tested with multiple scenarios to guarantee reliability across different application states.


Speed up your responsive apps and websites with fully-featured, ready-to-use open-source admin panel templates—free to use and built for efficiency.


About the Author

Subscribe to our newsletter
Get early information about new products, product updates and blog posts.

Answers by CoreUI Core Team