or run

npx @tessl/cli init
Log in

Version

Tile

Overview

Evals

Files

docs

angular-modules.mdbackend-implementation.mdconfiguration-options.mdheaders-parameters.mdhttp-services.mdindex.mdrequest-response.mdtesting.md
tile.json

testing.mddocs/

HTTP Testing

Testing utilities for Angular HTTP with mock backends and connection objects. Provides comprehensive test support for HTTP services with connection monitoring, request/response mocking, and verification utilities for Angular applications.

Capabilities

MockBackend

A mock backend for testing HTTP services. Can be injected in tests to override real backends and provides complete control over HTTP responses.

/**
 * A mock backend for testing HTTP services
 * Provides connection monitoring and response control for testing
 */
class MockBackend implements ConnectionBackend {
  /** EventEmitter of MockConnection instances for monitoring requests */
  connections: Subject<MockConnection>;
  
  /** Array representation of all connections created by this backend */
  connectionsArray: MockConnection[];
  
  /** EventEmitter of pending connections that haven't been resolved */
  pendingConnections: Subject<MockConnection>;
  
  constructor();
  
  /** Creates a new MockConnection for the given request */
  createConnection(request: Request): MockConnection;
  
  /** Verifies no pending connections exist, throws if any are unresolved */
  verifyNoPendingRequests(): void;
  
  /** Resolves all pending connections by setting readyState to Done */
  resolveAllConnections(): void;
}

Usage Examples:

import { MockBackend, MockConnection } from '@angular/http/testing';
import { Http, BaseRequestOptions, Response, ResponseOptions } from '@angular/http';
import { Injector } from '@angular/core';

// Setup mock backend in tests
const injector = Injector.create([
  { provide: ConnectionBackend, useClass: MockBackend },
  { provide: RequestOptions, useClass: BaseRequestOptions },
  Http
]);

const backend = injector.get(ConnectionBackend) as MockBackend;
const http = injector.get(Http);

// Monitor connections
let lastConnection: MockConnection;
backend.connections.subscribe(c => lastConnection = c);

// Make request and mock response
http.get('/api/data').subscribe(response => {
  console.log(response.json());
});

lastConnection.mockRespond(new Response(new ResponseOptions({
  body: JSON.stringify({ data: 'mocked' }),
  status: 200
})));

MockConnection

Represents a mock HTTP connection for testing. Provides methods to simulate responses and errors.

/**
 * Mock connection to represent a Connection for tests
 * Allows mocking responses and errors for HTTP requests
 */
class MockConnection implements Connection {
  /** Connection state based on XMLHttpRequest.readyState with additional states */
  readyState: ReadyState;
  
  /** Request instance used to create the connection */
  request: Request;
  
  /** Observable that emits the mocked response */
  response: ReplaySubject<Response>;
  
  constructor(request: Request);
  
  /** 
   * Sends a mock response to the connection
   * Emits the response to subscribers and completes the observable
   */
  mockRespond(response: Response): void;
  
  /** 
   * Emits an error to the response observable
   * Sets readyState to Done and emits error to subscribers
   */
  mockError(error?: Error): void;
  
  /** 
   * Not yet implemented - for future download progress simulation
   * Intended to send download progress responses
   */
  mockDownload(response: Response): void;
}

Usage Examples:

import { MockConnection } from '@angular/http/testing';
import { Request, Response, ResponseOptions, RequestMethod } from '@angular/http';

// Create mock connection
const request = new Request({
  method: RequestMethod.Get,
  url: '/api/users'
});
const connection = new MockConnection(request);

// Mock successful response
connection.response.subscribe(response => {
  console.log('Status:', response.status);
  console.log('Data:', response.json());
});

connection.mockRespond(new Response(new ResponseOptions({
  body: JSON.stringify([{ id: 1, name: 'John' }]),
  status: 200,
  statusText: 'OK'
})));

// Mock error response
connection.mockError(new Error('Network error'));

Testing Best Practices

import { async, fakeAsync, tick } from '@angular/core/testing';
import { MockBackend, MockConnection } from '@angular/http/testing';

describe('HTTP Service Tests', () => {
  let backend: MockBackend;
  let http: Http;
  let lastConnection: MockConnection;

  beforeEach(() => {
    const injector = Injector.create([
      { provide: ConnectionBackend, useClass: MockBackend },
      { provide: RequestOptions, useClass: BaseRequestOptions },
      Http
    ]);
    
    backend = injector.get(ConnectionBackend) as MockBackend;
    http = injector.get(Http);
    backend.connections.subscribe(c => lastConnection = c);
  });

  afterEach(() => {
    // Ensure no pending requests
    backend.verifyNoPendingRequests();
  });

  it('should make GET request', () => {
    http.get('/api/data').subscribe();
    expect(lastConnection.request.method).toBe(RequestMethod.Get);
    expect(lastConnection.request.url).toBe('/api/data');
  });

  it('should handle response', fakeAsync(() => {
    let result: any;
    http.get('/api/data').subscribe(response => result = response.json());
    
    lastConnection.mockRespond(new Response(new ResponseOptions({
      body: JSON.stringify({ success: true })
    })));
    
    tick();
    expect(result.success).toBe(true);
  }));

  it('should handle errors', fakeAsync(() => {
    let error: any;
    http.get('/api/data').subscribe(
      response => {},
      err => error = err
    );
    
    lastConnection.mockError(new Error('Server error'));
    tick();
    expect(error).toBeDefined();
  }));
});

Imports

import { MockBackend, MockConnection } from '@angular/http/testing';

For Angular testing integration:

import { TestBed } from '@angular/core/testing';
import { HttpModule } from '@angular/http';
import { MockBackend } from '@angular/http/testing';
import { BaseRequestOptions, Http } from '@angular/http';

TestBed.configureTestingModule({
  imports: [HttpModule],
  providers: [
    MockBackend,
    BaseRequestOptions,
    {
      provide: Http,
      useFactory: (backend: MockBackend, options: BaseRequestOptions) => {
        return new Http(backend, options);
      },
      deps: [MockBackend, BaseRequestOptions]
    }
  ]
});