Saltar al contenido principal
ProductosHerramientas de escritorioTASTECADRevisión de planosTASTEFILESGestión de archivosTASTEFTPTransferencia de archivosTASTESSHEspacio de trabajo remotoTASTEZIPCompresión y extracciónTASTEWINMGestión de archivosHerramientas para desarrolladoresTASTECODEEntorno de desarrollo integrado para RustTASTESTUDIOEntorno integrado de desarrollo y pruebasTASTEETLIntegración de datos (ETL)ServidoresTASTEREMOTEServidor de escritorio remotoTASTEGEOServidor geoespacialTASTEMAILEspacio de trabajo de correoInversiónTASTESTOCKAplicación de escritorio de trading automático de accionesEmpezarDescargasDocumentaciónComprarTodos los productos
Marketplace
Noticias
TecnologíaNoticiasNoticias de desarrollo de hoyDocumentaciónLenguajes de programaciónRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps y escritorioTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos esencialesAlgoritmos avanzadosAlgoritmos prácticos
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparateGuía de la comunidad
ColaboraTransferencia técnicaDesarrollo de sitio webDesarrollo de app de escritorioCanal de lanzamiento y pagosSocio de ventasContacto
ServiciosEscritorio remotoPaquetes de instalación a medida
TASTEDEV
Productos

Herramientas de escritorio

TASTECADAbre planos complejos con ligerezaTASTEFILESSolo los archivos que necesitas, lo más rápido posibleTASTEFTPEl camino más limpio para tus archivosTASTESSHEntre tu servidor y tú, una conexión más sólidaTASTEZIPComprime más rápido, descomprime más seguroTASTEWINMUn gestor de archivos de dos paneles pensado para el teclado

Herramientas para desarrolladores

TASTECODEEdita, compila, depura y prueba apps de Rust en una sola ventanaTASTESTUDIODe la edición a las pruebas remotas y las correcciones con IA aprobadasTASTEETLMueve datos viendo sus valores

Servidores

TASTEREMOTEUn escritorio remoto que funciona en tu propio servidorTASTEGEOUn servidor geoespacial compatible con GeoServer, reconstruido en RustTASTEMAILRecupera el control de tu correo

Inversión

TASTESTOCKTrading automático de acciones según las reglas que tú defines: cuándo y qué

Empezar

DescargasÚltimas versiones de cada productoDocsCómo usar cada productoComprarSuscripciones y licencias perpetuasTodos los productosTodos los productos de un vistazo
Todos los productos
MarketplaceNoticias
Tecnología

Noticias

Noticias de desarrollo de hoyAnuncios oficiales de lenguajes, frameworks, GitHub e IADocumentaciónGuías de lenguajes, frameworks y algoritmos

Lenguajes de programación

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks web frontendNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps y escritorioTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálisis de complejidad · Ordenamiento · Búsqueda · Estructuras de datos básicas · Árboles y montículosAlgoritmos esencialesRecorrido de grafos · Camino mínimo y árbol generador mínimo · Programación dinámica · Algoritmos voraces · Divide y vencerás · Backtracking (vuelta atrás)Algoritmos avanzadosAlgoritmos de cadenas · Matemáticas y teoría de números · Manipulación de bits · Árboles de segmentos · Union-FindAlgoritmos prácticosEstrategia para entrevistas de código · Caché LRU · Limitación de tasa · Hashing consistente
Toda la documentación de desarrollo
Comunidad
ProyectosDescubre creadores y su trabajoRegistros de desarrolloDecisiones y aprendizajesPromptsInstrucciones reutilizablesProblemas con herramientas de IAProblemas y alternativas de Claude, Codex, GeminiEscaparateResultados terminadosGuía de la comunidadCómo construimos en abierto
Colabora
Transferencia técnicaApps nativas con Rust y eguiDesarrollo de sitio web10 idiomas, cuentas, documentación y descargasDesarrollo de app de escritorioRust y egui, sin WebViewCanal de lanzamiento y pagosFirma, MSI, deb, rpm, AppImage, hashesSocio de ventasRecomiéndanos y gana el 30 %ContactoDesarrollo, alianzas e inversión
Servicios
Escritorio remotoAccede a tu ordenador desde el navegadorPaquetes de instalación a medidaSolo lo necesario, ajustes precargados
Comprar
ES
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Iniciar sesión
Iniciar sesión
TASTEDEV

De pequeñas herramientas a un mejor desarrollo.

support@tastedev.netApoyar a TASTEDEV
ProductosLínea de productosComprarDocsDescargasMarketplaceSoporte
ComunidadProyectosRegistros de desarrolloPromptsProblemas con herramientas de IAEscaparate
PolíticasQuiénes somosPolítica de privacidadTérminos de servicioCondiciones de suscripciónReembolsosNormas de la comunidad
CuentaIniciar sesiónRegistrarse
Visitantes
Hoy
Ayer
Vistas totales
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro mercantil
853-44-00368
Dirección
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Teléfono
+82-10-4404-1523
Correo electrónico
whitecalvin@tastedev.net
Responsable de privacidad
CHOI YOUNG GU

© 2026 TASTEDEVLa información de los productos se basa en fuentes de desarrollo verificadas.Publicado · en mejora

Documentación de Angular
Angular
Getting Started with AngularProject StructureCore ConceptsData and StateTestingDeployment
Debates

Guía de Angular · 5/6

Testing

Por ahora, este capítulo solo está disponible en inglés.

Angular projects come with unit testing already configured, and the CLI can add an end-to-end (e2e) framework on request. This chapter covers running tests, testing components and services with TestBed, mocking HTTP, and browser-level e2e tests.

Running unit tests

Test files sit next to the code they test and end in .spec.ts. ng test runs them with the runner configured in the test target of angular.json:

ng test
ng test --watch=false
ng test --help

Which runner you get depends on when the project was created. Recent CLI versions set up Vitest for new projects, while projects created with older versions use Karma with the Jasmine framework in a real browser. Both use the same describe, it, beforeEach and expect structure, and Angular's TestBed works the same way in either, so the examples below run on both. Mocking helpers differ: Jasmine has jasmine.createSpy() and spyOn(), while Vitest has vi.fn() and vi.spyOn(). Options such as code coverage also depend on the runner; ng test --help lists what your project supports.

Testing a component

TestBed creates a small Angular environment for a test. Import the standalone component, create it, interact with the DOM and check the result. This test targets the Counter component from the core concepts chapter:

import { TestBed } from '@angular/core/testing';
import { Counter } from './counter';

describe('Counter', () => {
  beforeEach(async () => {
    await TestBed.configureTestingModule({ imports: [Counter] }).compileComponents();
  });

  it('starts at zero', () => {
    const fixture = TestBed.createComponent(Counter);
    fixture.detectChanges();
    expect(fixture.nativeElement.textContent).toContain('0 x 2 = 0');
  });

  it('increments when the button is clicked', () => {
    const fixture = TestBed.createComponent(Counter);
    fixture.detectChanges();

    const button: HTMLButtonElement = fixture.nativeElement.querySelector('button');
    button.click();
    fixture.detectChanges();

    expect(fixture.nativeElement.textContent).toContain('1 x 2 = 2');
  });
});

fixture.detectChanges() runs change detection so the DOM reflects the latest state. When a component waits for asynchronous work, await fixture.whenStable() waits until pending tasks have finished.

Replacing dependencies

To test a component in isolation, give it a fake version of a service through providers. Because inject() resolves through the same injector, the component receives the fake:

¿Tienes preguntas sobre este capítulo?
Capítulo anteriorData and StateCapítulo siguienteDeployment
import { TestBed } from '@angular/core/testing';
import { signal } from '@angular/core';
import { HeroList } from './hero-list';
import { HeroService } from './hero.service';

it('renders heroes from the service', async () => {
  const fakeService = { all: signal([{ id: 1, name: 'Test Hero' }]), add: () => {} };

  await TestBed.configureTestingModule({
    imports: [HeroList],
    providers: [{ provide: HeroService, useValue: fakeService }],
  }).compileComponents();

  const fixture = TestBed.createComponent(HeroList);
  fixture.detectChanges();
  expect(fixture.nativeElement.textContent).toContain('Test Hero');
});

Testing HTTP calls

provideHttpClientTesting() swaps the real backend for HttpTestingController, which lets a test inspect outgoing requests and answer them. Register it after provideHttpClient():

import { TestBed } from '@angular/core/testing';
import { provideHttpClient } from '@angular/common/http';
import { HttpTestingController, provideHttpClientTesting } from '@angular/common/http/testing';
import { Todo, TodoApi } from './todo-api';

describe('TodoApi', () => {
  let api: TodoApi;
  let http: HttpTestingController;

  beforeEach(() => {
    TestBed.configureTestingModule({
      providers: [provideHttpClient(), provideHttpClientTesting()],
    });
    api = TestBed.inject(TodoApi);
    http = TestBed.inject(HttpTestingController);
  });

  afterEach(() => http.verify());

  it('requests a limited list', () => {
    let result: Todo[] = [];
    api.list(2).subscribe((todos) => (result = todos));

    const req = http.expectOne((r) => r.url.endsWith('/todos'));
    expect(req.request.method).toBe('GET');
    expect(req.request.params.get('_limit')).toBe('2');
    req.flush([{ id: 1, title: 'Write tests', completed: false }]);

    expect(result.length).toBe(1);
  });
});

http.verify() fails the test if any request was made but never answered.

End-to-end tests

New projects do not include an e2e framework. Running ng e2e in a project without an e2e target offers to add one; the choices include Playwright, Cypress, WebdriverIO, Nightwatch and Puppeteer. You can also install a tool directly. With Playwright:

npm init playwright@latest
npx playwright test

Point Playwright at the dev server in playwright.config.ts so it starts the app before the tests:

import { defineConfig } from '@playwright/test';

export default defineConfig({
  use: { baseURL: 'http://localhost:4200' },
  webServer: {
    command: 'npm start',
    url: 'http://localhost:4200',
    reuseExistingServer: !process.env['CI'],
  },
});
import { expect, test } from '@playwright/test';

test('home page greets the user', async ({ page }) => {
  await page.goto('/');
  await expect(page.getByRole('heading', { level: 1 })).toContainText('Hello');
});

Summary

  • ng test runs .spec.ts files with the project's configured runner: Vitest in recent projects, Karma and Jasmine in older ones.
  • TestBed creates components and services; detectChanges() updates the DOM.
  • Swap dependencies with providers and test HTTP with provideHttpClientTesting().
  • Add an e2e tool such as Playwright or Cypress through ng e2e or by installing it directly.

0 comentarios

Comentarios destacadosMás recientes primero

Iniciar sesión · Inicia sesión para dejar un comentario.