Pular para o conteúdo principal
ProdutosFerramentas de desktopTASTECADVisualização de desenhosTASTEFILESGerenciamento de arquivosTASTEFTPTransferência de arquivosTASTESSHEspaço de trabalho remotoTASTEZIPCompactação e extraçãoTASTEWINMGerenciamento de arquivosFerramentas para desenvolvedoresTASTECODEAmbiente de desenvolvimento integrado para RustTASTESTUDIOAmbiente integrado de desenvolvimento e testesTASTEETLIntegração de dados (ETL)ServidoresTASTEREMOTEServidor de área de trabalho remotaTASTEGEOServidor geoespacialTASTEMAILEspaço de trabalho de e-mailInvestimentosTASTESTOCKAplicativo desktop de negociação automática de açõesComeçarDownloadsDocumentaçãoComprarTodos os produtos
Marketplace
Notícias
TecnologiaNotíciasNotícias de desenvolvimento de hojeDocumentaçãoLinguagens de programaçãoRustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDartFrameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngularFrameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · ExpressFrameworks de apps e desktopTauriFlutterReact NativeElectronAlgoritmosFundamentos de algoritmosAlgoritmos essenciaisAlgoritmos avançadosAlgoritmos práticos
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrineGuia da comunidade
ColaboreTransferência técnicaConstrução de siteConstrução de app de desktopPipeline de lançamento e pagamentoParceiro de vendasContato
ServiçosÁrea de trabalho remotaPacotes de instalação sob medida
TASTEDEV
Produtos

Ferramentas de desktop

TASTECADDesenhos complexos, abertos com levezaTASTEFILESSó os arquivos de que você precisa, o mais rápido possívelTASTEFTPO caminho mais organizado para seus arquivosTASTESSHEntre você e o servidor, uma conexão mais sólidaTASTEZIPCompacte mais rápido, extraia com mais segurançaTASTEWINMUm gerenciador de arquivos de dois painéis feito para o teclado

Ferramentas para desenvolvedores

TASTECODEEdite, compile, depure e teste apps Rust em uma única janelaTASTESTUDIODa edição aos testes remotos e às correções com IA aprovadasTASTEETLMova dados de olho nos valores

Servidores

TASTEREMOTEUma área de trabalho remota rodando no seu próprio servidorTASTEGEOUm servidor geoespacial compatível com o GeoServer, reconstruído em RustTASTEMAILRetome o controle do seu e-mail

Investimentos

TASTESTOCKNegociação automática de ações pelas regras que você define: quando e o quê

Começar

DownloadsVersões mais recentes de cada produtoDocsComo usar cada produtoComprarAssinaturas e licenças perpétuasTodos os produtosTodos os produtos de relance
Todos os produtos
MarketplaceNotícias
Tecnologia

Notícias

Notícias de desenvolvimento de hojeAnúncios oficiais de linguagens, frameworks, GitHub e IADocumentaçãoGuias de linguagens, frameworks e algoritmos

Linguagens de programação

RustTypeScriptJavaScriptPythonGoC#JavaCC++KotlinDart

Frameworks

Frameworks de front-end webNext.jsReactVue.js · NuxtSvelteKitAngular
Frameworks de servidorSpring BootDjangoFastAPIASP.NET CoreNestJS · Express
Frameworks de apps e desktopTauriFlutterReact NativeElectron

Algoritmos

Fundamentos de algoritmosAnálise de complexidade · Ordenação · Busca · Estruturas de dados básicas · Árvores e heapsAlgoritmos essenciaisBusca em grafos · Caminho mínimo e árvore geradora mínima · Programação dinâmica · Algoritmos gulosos · Divisão e conquista · BacktrackingAlgoritmos avançadosAlgoritmos de strings · Matemática e teoria dos números · Manipulação de bits · Árvores de segmentos · Union-FindAlgoritmos práticosEstratégia para entrevistas de código · Cache LRU · Limitação de taxa · Hashing consistente
Toda a documentação de desenvolvimento
Comunidade
ProjetosDescubra criadores e trabalhosRegistros de desenvolvimentoDecisões e aprendizadosPromptsInstruções reutilizáveisProblemas de ferramentas de IAProblemas e contornos de Claude, Codex, GeminiVitrineResultados concluídosGuia da comunidadeComo construímos em aberto
Colabore
Transferência técnicaApps nativos em Rust e eguiConstrução de site10 idiomas, contas, documentação e downloadsConstrução de app de desktopRust e egui, sem WebViewPipeline de lançamento e pagamentoAssinatura, MSI, deb, rpm, AppImage, hashesParceiro de vendasRecomende e ganhe 30%ContatoDesenvolvimento, parcerias e investimento
Serviços
Área de trabalho remotaAcesse seu computador pelo navegadorPacotes de instalação sob medidaSó o necessário, configurações pré-carregadas
Comprar
PT
한국어EnglishDeutschEspañolFrançaisItalianoPortuguês (Brasil)日本語简体中文繁體中文
Entrar
Entrar
TASTEDEV

De pequenas ferramentas a um desenvolvimento melhor.

support@tastedev.netApoiar TASTEDEV
ProdutosLinha de produtosComprarDocsDownloadsMarketplaceSuporte
ComunidadeProjetosRegistros de desenvolvimentoPromptsProblemas de ferramentas de IAVitrine
PolíticasSobre nósPolítica de privacidadeTermos de usoTermos de assinaturaReembolsoDiretrizes da comunidade
ContaEntrarCriar conta
Visitantes
Hoje
Ontem
Visualizações totais
Empresa
GXSOFT
Representante
CHOI YOUNG GU
Número de registro comercial
853-44-00368
Endereço
9F V24, 351 Gyeongin-ro, Michuhol-gu, Incheon, Republic of Korea
Telefone
+82-10-4404-1523
E-mail
whitecalvin@tastedev.net
Responsável pela privacidade
CHOI YOUNG GU

© 2026 TASTEDEVAs informações dos produtos se baseiam em fontes de desenvolvimento verificadas.Lançado · em melhoria

Documentação de Angular
Angular
Getting Started with AngularProject StructureCore ConceptsData and StateTestingDeployment
Discussões

Guia de Angular · 5/6

Testing

Por enquanto, este capítulo está disponível apenas em 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:

Dúvidas sobre este capítulo?
Capítulo anteriorData and StatePróximo capítuloDeployment
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 comentários

Principais comentáriosMais recentes primeiro

Fazer login · Faça login para deixar um comentário.