Angular testing patterns

From FerroxLabs/murage · View interactive version

Angular testing patterns is an AI agent skill from the GitHub repository FerroxLabs/murage. Guides expert-level angular testing patterns implementation: typescript and testing decision frameworks, production-ready patterns, and concrete templates for angular testing patterns workflows. Use when the user asks about angular testing patterns, angular testing patterns configuration, or typescr

How to use this skill

Skill file

Angular Testing Patterns

When to Use

Use this skill when:

Do NOT use this skill when:


Process

1. Classify the Code Under Test and Choose the Right Test Type

Before writing a single line of test code, identify exactly what you are testing and which test strategy applies. Angular has four distinct testing contexts that require fundamentally different setups.

Identify the classification before writing the describe block. Wrong classification is the #1 source of brittle, slow, or falsely-passing tests in Angular projects.

2. Configure TestBed with Minimal, Targeted Declarations

TestBed configuration directly controls test speed and isolation. Every unnecessary declaration adds compilation overhead.

3. Mock Dependencies at the Right Fidelity Level

Overmocking produces tests that pass but do not catch real regressions. Undermocking produces slow, brittle tests that couple to implementation.

4. Control Change Detection Deliberately

Uncontrolled change detection is the second leading cause of flaky Angular tests. Understanding when Angular's CD runs in tests versus production is critical.

5. Query the DOM Accurately and Resiliently

How you query the DOM determines whether your tests survive template refactors. Fragile selectors are a maintenance tax.

6. Test Asynchronous Code Patterns Correctly

Async testing is where most Angular test failures and flakiness originate. Each async pattern has a specific correct handling strategy.

```typescript

const req = httpMock.expectOne('/api/users');

expect(req.request.method).toBe('GET');

req.flush(mockUsers);

httpMock.verify(); // in afterEach

```

```typescript

fakeAsync(() => {

let result: User[];

service.getUsers().subscribe(data => result = data);

tick();

expect(result).toEqual(mockUsers);

})

```

7. Structure Tests for Readability and Maintainability

Test structure governs how quickly a developer can diagnose a failing test six months after writing it.

8. Measure, Enforce, and Optimize Coverage

Coverage is a metric that can mislead if not used carefully, but it is essential for production Angular projects.


Output Format

When helping a user implement or review Angular testing patterns, provide output in this structure:

## Angular Test Implementation Plan

### Test Classification
- Component/Service/Directive under test: [name]
- Test type: [Isolated Unit | Shallow Component | Deep Integration | TestBed Service]
- Async complexity: [None | Observable | HTTP | fakeAsync required | Signals]
- Dependencies to mock: [list with mock strategy for each]

### TestBed Configuration
\`\`\`typescript
TestBed.configureTestingModule({
  declarations: [],   // Only this component + any needed stubs
  imports: [],        // Targeted modules only
  providers: [],      // Typed spy objects or MockProvider
  schemas: []         // NO_ERRORS_SCHEMA if shallow
});
\`\`\`

### Dependency Mock Strategy

| Dependency | Mock Type | Rationale |
|------------|-----------|-----------|
| HttpClient | HttpClientTestingModule + HttpTestingController | Verifies request URL/method/body |
| UserService | jasmine.createSpyObj / jest.fn() | Returns controlled observables |
| Router | RouterTestingModule or plain stub | Depends on navigation assertion needs |
| NgRx Store | provideMockStore({ initialState }) | Avoids real reducer execution |

### Test Structure Template
\`\`\`typescript
describe('ComponentName', () => {
  let fixture: ComponentFixture<ComponentName>;
  let component: ComponentName;
  let dependencySpy: jasmine.SpyObj<DependencyService>;

  beforeEach(async () => {
    // Setup
  });

  describe('when [initial state / precondition]', () => {
    it('should [expected behavior]', () => {
      // Arrange
      // Act
      // Assert
    });
  });
});
\`\`\`

### Coverage Targets
- Statement coverage: [80%+ recommended]
- Branch coverage: [75%+ recommended, focus on ngIf/ternary/switch]
- Critical paths requiring 100%: [auth guards, form validation, error states]

### Known Edge Cases to Test
- [List 3-5 specific edge cases relevant to this component/service]

Rules

  1. NEVER import AppModule, SharedModule, or any barrel module into a TestBed configuration. These pull in the entire application dependency graph, inflate test compilation time by 10-50x, and create hidden coupling. Always import only the exact Angular modules your template actually uses.
  1. NEVER use NO_ERRORS_SCHEMA in deep integration tests. This schema silently suppresses errors for unknown elements AND unknown attribute bindings. Use it only for deliberately shallow tests where you want to ignore child components. For integration tests, declare stub components explicitly.
  1. ALWAYS call httpMock.verify() in afterEach when using HttpClientTestingModule. Omitting this call means unexpected or extra HTTP requests silently pass, hiding bugs where components make too many requests or request wrong endpoints.
  1. NEVER use setTimeout or real Promise chains in Angular tests without waitForAsync or fakeAsync. Real timers create race conditions in test execution and cause intermittent failures in CI environments with different CPU scheduling. Always use fakeAsync + tick() for deterministic time control.
  1. ALWAYS use NoopAnimationsModule instead of BrowserAnimationsModule in test modules. Real animation modules start timer-based animation callbacks that require fakeAsync tick management throughout unrelated tests and cause phantom failures when animations complete during teardown.
  1. NEVER assert on component internals (private properties, internal state) when you can assert on the rendered output instead. Testing component.isLoading === true is less valuable than testing that the loading spinner is in the DOM. Internal state can change while behavior remains correct -- only behavior assertions protect against real regressions.
  1. ALWAYS use TestBed.inject() instead of TestBed.get() for Angular 9+ projects. TestBed.get() is deprecated, untyped, and returns any. TestBed.inject(Token) is type-safe and provides compile-time verification that the token exists in the test module.
  1. NEVER share fixture or component instances across describe blocks using outer-scope variables that are only assigned in one beforeEach. This causes test order dependency. Each describe block must have its own beforeEach that creates a fresh fixture.
  1. ALWAYS tear down TestBed with { teardown: { destroyAfterEach: true } } in Angular 14+ projects. Without this, leaked component instances persist subscriptions, timers, and DOM mutations that corrupt subsequent tests. This is especially critical for components with ngOnDestroy lifecycle hooks.
  1. NEVER mock more than one layer deep from the unit under test. If your component uses UserService which internally calls HttpClient, mock UserService in the component test -- do not configure HttpClientTestingModule to mock the HTTP layer. Test the HTTP behavior in UserService's own spec file. Mocking too deep creates tests that are coupled to implementation details two levels removed.

Edge Cases

Testing Components with `OnPush` Change Detection

Components using ChangeDetectionStrategy.OnPush do not re-render on every detectChanges() call -- they only re-render when @Input references change, events fire, or the async pipe emits. This breaks naive tests that set component.someProperty = newValue and then call detectChanges().

Handling:

Testing Angular Router Guards

Route guards (CanActivate, CanDeactivate, CanLoad, CanMatch) are often tested incorrectly by instantiating them as isolated classes and passing raw objects as ActivatedRouteSnapshot. This misses DI-dependent guard logic.

Handling:

Testing Components with Complex RxJS Chains and `switchMap`/`combineLatest`

Components that combine multiple observables or use higher-order operators like switchMap, mergeMap, or combineLatest create intricate timing dependencies in tests.

Handling:

Testing NgRx Effects

Effects are the most complex testing surface in NgRx applications because they involve action streams, service calls, and dispatched output actions.

Handling:

Migrating from Karma/Jasmine to Jest

Teams migrating an existing Angular project from Karma to Jest encounter several sharp edges that are not covered in basic migration guides.

Handling:

Testing Standalone Components (Angular 14+)

Standalone components do not use NgModule, which changes how TestBed is configured and how dependencies are resolved.

Handling:

Diagnosing and Fixing Flaky Tests in CI

Tests that pass locally but fail in CI, or fail on every 5th run, indicate one of a small set of root causes in Angular.

Handling:


Example

Input: "I have an Angular 16 component called UserProfileComponent that loads user data via UserService.getUser(id) which returns an Observable<User>. It displays the user's name, shows a loading spinner while fetching, and shows an error message if the request fails. It uses OnPush change detection. How do I write comprehensive tests for this?"

Output:

Test Classification

Complete Test File

import { ComponentFixture, TestBed, fakeAsync, tick } from '@angular/core/testing';
import { By } from '@angular/platform-browser';
import { NO_ERRORS_SCHEMA } from '@angular/core';
import { ActivatedRoute } from '@angular/router';
import { of, throwError, Subject } from 'rxjs';

import { UserProfileComponent } from './user-profile.component';
import { UserService } from '../services/user.service';
import { User } from '../models/user.model';

const mockUser: User = {
  id: '42',
  name: 'Jane Smith',
  email: 'jane@example.com',
  role: 'admin'
};

describe('UserProfileComponent', () => {
  let fixture: ComponentFixture<UserProfileComponent>;
  let component: UserProfileComponent;
  let userServiceSpy: jasmine.SpyObj<UserService>;

  beforeEach(async () => {
    userServiceSpy = jasmine.createSpyObj<UserService>('UserService', ['getUser']);

    await TestBed.configureTestingModule({
      declarations: [UserProfileComponent],
      // NO_ERRORS_SCHEMA suppresses child component errors for shallow test
      schemas: [NO_ERRORS_SCHEMA],
      providers: [
        { provide: UserService, useValue: userServiceSpy },
        {
          provide: ActivatedRoute,
          useValue: { params: of({ id: '42' }) }
        }
      ]
    }, { teardown: { destroyAfterEach: true } }).compileComponents();

    // Do NOT call detectChanges here -- control it per test
  });

  // Factory helper to avoid duplicating setup logic
  function createComponent(): void {
    fixture = TestBed.createComponent(UserProfileComponent);
    component = fixture.componentInstance;
  }

  describe('initial render and loading state', () => {
    it('should show loading spinner before data arrives', () => {
      // Arrange: service returns a subject that has not emitted yet
      const userSubject = new Subject<User>();
      userServiceSpy.getUser.and.returnValue(userSubject.asObservable());
      createComponent();

      // Act: trigger ngOnInit via first detectChanges
      fixture.detectChanges();

      // Assert: loading spinner is in DOM
      const spinner = fixture.debugElement.query(By.css('[data-testid="loading-spinner"]'));
      expect(spinner).not.toBeNull();

      // Assert: user name is NOT rendered yet
      const nameEl = fixture.debugElement.query(By.css('[data-testid="user-name"]'));
      expect(nameEl).toBeNull();
    });

    it('should call getUser with the route param id on init', () => {
      // Arrange
      userServiceSpy.getUser.and.returnValue(of(mockUser));
      createComponent();

      // Act
      fixture.detectChanges();

      // Assert
      expect(userServiceSpy.getUser).toHaveBeenCalledOnceWith('42');
    });
  });

  describe('when user data loads successfully', () => {
    beforeEach(() => {
      userServiceSpy.getUser.and.returnValue(of(mockUser));
      createComponent();
      fixture.detectChanges(); // triggers ngOnInit, observable emits synchronously
    });

    it('should display the user name', () => {
      const nameEl = fixture.debugElement.query(By.css('[data-testid="user-name"]'));
      expect(nameEl.nativeElement.textContent.trim()).toBe('Jane Smith');
    });

    it('should display the user email', () => {
      const emailEl = fixture.debugElement.query(By.css('[data-testid="user-email"]'));
      expect(emailEl.nativeElement.textContent.trim()).toBe('jane@example.com');
    });

    it('should hide the loading spinner after data arrives', () => {
      const spinner = fixture.debugElement.query(By.css('[data-testid="loading-spinner"]'));
      expect(spinner).toBeNull();
    });

    it('should not display the error message', () => {
      const errorEl = fixture.debugElement.query(By.css('[data-testid="error-message"]'));
      expect(errorEl).toBeNull();
    });

    it('should display admin badge when user role is admin', () => {
      const badge = fixture.debugElement.query(By.css('[data-testid="admin-badge"]'));
      expect(badge).not.toBeNull();
    });
  });

  describe('when user data fails to load', () => {
    beforeEach(() => {
      userServiceSpy.getUser.and.returnValue(
        throwError(() => new Error('Network error'))
      );
      createComponent();
      fixture.detectChanges();
    });

    it('should display the error message', () => {
      const errorEl = fixture.debugElement.query(By.css('[data-testid="error-message"]'));
      expect(errorEl).not.toBeNull();
      expect(errorEl.nativeElement.textContent.trim()).toContain('Unable to load profile');
    });

    it('should hide the loading spinner on error', () => {
      const spinner = fixture.debugElement.query(By.css('[data-testid="loading-spinner"]'));
      expect(spinner).toBeNull();
    });

    it('should not display user data on error', () => {
      const nameEl = fixture.debugElement.query(By.css('[data-testid="user-name"]'));
      expect(nameEl).toBeNull();
    });
  });

  describe('OnPush change detection -- re-render on input change', () => {
    it('should reload user when userId input changes', fakeAsync(() => {
      // Arrange: initial load
      userServiceSpy.getUser.and.returnValue(of(mockUser));
      createComponent();
      fixture.detectChanges();

      // Arrange: new user for second call
      const updatedUser: User = { ...mockUser, id: '99', name: 'Bob Jones' };
      userServiceSpy.getUser.and.returnValue(of(updatedUser));

      // Act: use setInput to trigger OnPush re-evaluation
      fixture.componentRef.setInput('userId', '99');
      tick(); // allow observable to resolve
      fixture.detectChanges();

      // Assert
      const nameEl = fixture.debugElement.query(By.css('[data-testid="user-name"]'));
      expect(nameEl.nativeElement.textContent.trim()).toBe('Bob Jones');
      expect(userServiceSpy.getUser).toHaveBeenCalledWith('99');
    }));
  });

  describe('retry behavior', () => {
    it('should retry loading when retry button is clicked after error', fakeAsync(() => {
      // Arrange: first call fails, second call succeeds
      userServiceSpy.getUser.and.returnValues(
        throwError(() => new Error('timeout')),
        of(mockUser)
      );
      createComponent();
      fixture.detectChanges();

      // Assert error state
      const errorEl = fixture.debugElement.query(By.css('[data-testid="error-message"]'));
      expect(errorEl).not.toBeNull();

      // Act: click retry button
      const retryBtn = fixture.debugElement.query(By.css('[data-testid="retry-button"]'));
      retryBtn.nativeElement.click();
      tick();
      fixture.detectChanges();

      // Assert: user is now displayed
      const nameEl = fixture.debugElement.query(By.css('[data-testid="user-name"]'));
      expect(nameEl.nativeElement.textContent.trim()).toBe('Jane Smith');
      expect(userServiceSpy.getUser).toHaveBeenCalledTimes(2);
    }));
  });
});

Coverage Assessment for This Component

| Coverage Area | Tests Covering It | Branch Status |

|---|---|---|

| Loading state (true) | should show loading spinner before data arrives | Covered |

| Loading state (false -- success) | should hide the loading spinner after data arrives | Covered |

| Loading state (false -- error) | should hide the loading spinner on error | Covered |

| Success render (name, email) | should display the user name/email | Covered |

| Error render | should display the error message | Covered |

| Role-based badge (admin) | should display admin badge | Partially -- need non-admin test |

| Role-based badge (non-admin) | Not yet written -- add it('should not display admin badge for non-admin') | Missing branch |

| Retry logic | should retry loading when retry button is clicked | Covered |

| Route param extraction | should call getUser with the route param id | Covered |

| Input change re-fetch | should reload user when userId input changes | Covered |

What to Add Next

The non-admin role branch is the only missing branch coverage item. Add:

it('should not display admin badge when user role is viewer', () => {
  const viewerUser: User = { ...mockUser, role: 'viewer' };
  userServiceSpy.getUser.and.returnValue(of(viewerUser));
  createComponent();
  fixture.detectChanges();

  const badge = fixture.debugElement.query(By.css('[data-testid="admin-badge"]'));
  expect(badge).toBeNull();
});

This brings branch coverage to 100% for the role display conditional, which is a user-facing behavior difference warranting full branch coverage.

Use this skill with your AI agent: Open on Skill Issue to copy, download, or add to your library. Works with Claude, ChatGPT, Gemini, Cursor, Windsurf and more.