Skip to content

Commit

Permalink
Escrevendo testes finais
Browse files Browse the repository at this point in the history
  • Loading branch information
Danilo Silva committed Nov 5, 2022
1 parent 4e2fde0 commit 8c13b67
Show file tree
Hide file tree
Showing 19 changed files with 367 additions and 51 deletions.
127 changes: 113 additions & 14 deletions README.md
Original file line number Diff line number Diff line change
@@ -1,27 +1,126 @@
# CursoAngularTestesUnitarios
# Projeto do curso de Testes Unitários com Angular / Jasmine e Karma.

This project was generated with [Angular CLI](https://github.com/angular/angular-cli) version 14.2.7.
## Grade curricular

## Development server
## Seção 1
### Introdução ao curso
- Introdução.
- Apresentação do curso.
- Como aproveitar aproveitar o máximo do curso.

## Seção 2
### Testes unitários no Angular.
- A importancia do Teste de Software.
- O que é Jasmine e Karma.
- O que testar em uma aplicação Angular
- Teste de integração x Teste de Unidade.
- Cobertura de Testes (code coverage).

## Seção 3
### Conceito de uma suíte de testes no Angular
- Suíte de testes - describe.
- Especificações de estes - it.
- Antes de cada teste - beforeEach.
- Após cada teste - afterEach.
- Antes de todos - beforeAll.
- Configurando os módulos dos testes- TestBeb

Run `ng serve` for a dev server. Navigate to `http://localhost:4200/`. The application will automatically reload if you change any of the source files.
## Seção 4
### Criando o projeto com Angular CLI
- Instalação do Nodejs.
- Instalando o Angular CLI.
- Instalando o Visual Studio Code.
- Criando o projeto com Angular CLI.
- Rodando a aplicação no navegador.
- Executando os testes.

## Code scaffolding
## Seção 5
### Resolvendo problemas comuns em uma aplicação
- Erro ao trabalhar com requisições - No provider for HttpClient!
- Erro modal Angular material - No provider for MatDialog!
- Erro ao trabalhar com formularios - No provider for FormBuilder!
- Erro ao trabalhar com ngModel - No provider for NgControl found in NodeInjector.

Run `ng generate component component-name` to generate a new component. You can also use `ng generate directive|pipe|service|class|guard|interface|enum|module`.
## Seção 6
### Debugando os testes
- Focando em um único teste - fdescribe.
- Focando em uma única especificação - fit.
- Rodando os testes de um único arquivo - ng test --include.
- Adicionando breakpoints.
- Utilizando debugger.
- Contexto de Debugger do Jasmine.

## Build
## Seção 7
### Testando expectativas - Jasmine Matchers
- Verificando se os valores são iguais - toEqual.
- Verificando se os valores são iguais e do mesmo objeto - toBe.
- Testando se um valor é truthy - toBeTruthy.
- Testando se um valor é falsy - toBeFalsy.
- Verificando se um valor é true - toBeTrue.
- Verificando se um valor é falso - toBeFalse.
- Testando se um valor não é true - not.
- Verificando se um valor esta contido em um array ou string - toContain.
- Verificando se um valor foi definido - toBeDefined.
- Verificando se um valor não foi definido - toBeUndefined.
- Testando se um valor é nulo - toBeNull.
- Testando se um valor é NaN - toBeNaN.
- Verificando se um valor é maior do que outro - toBeGreatherThan.
- Testando se um valor é menor do que outro - toBeLessThan.
- Verificando se um numero está próximo a outro - toBeCloseTo.
- Testando se um valor é igual com base em uma expressão regular - toMatch.
- Verificando se uma funcão lançou um erro - toThrow.

Run `ng build` to build the project. The build artifacts will be stored in the `dist/` directory.
## Seção 8
### Mockando métodos de componentes e serviços
- Mockando métodos de serviço com Mocks.
- Mockando métodos de serviços com Stubs.
- Espionando métodos de componentes com spyOn.
- Espionando métodos de serviços com spyOn.
- Criando objetos com createSpy.
- Mockando métodos com createSpyObj.

## Running unit tests
## Seção 9
### Testando chamadas HTTP
- Testando requisição GET por ID.
- Testando requisição GET.
- Testando erro na requisição.
- Testando requisição POST.
- Testando requisição PUT.
- Testando requisição DELETE.
- Testando se headers foram passados na requisição.

Run `ng test` to execute the unit tests via [Karma](https://karma-runner.github.io).
## Seção 10
### Testando código Assíncrono
- Testando subscribe.
- Testando promises.
- Utilizando done função.
- Async e WhenStable.
- FakeAsync e Tick.

## Running end-to-end tests
## Seção 11
### Testando componentes
- Acessando a DOM com debugElement.query() e nativeElement.querySelector().
- Detecção de alterações manual - fixture.detectChanges().
- Detecção automática de alterações.
- Disparando click no botão com triggerEventHandler.
- Preenchendo formulários disparando evento Input.
- Testando Entradas e Saídas - @Input e @Output.

Run `ng e2e` to execute the end-to-end tests via a platform of your choice. To use this command, you need to first add a package that implements end-to-end testing capabilities.
## Seção 12
### Testando Pipes, Guardas de Rotas, Rotas e Directivas
- Testando pipes.
- Testando guarda de rota.
- Testando rotas.
- Testando diretivas.

## Further help
## Seção 13
### Bônus - Testando formulários
- Testando se formulário é inválido.
- Testando se formulário é válido.
- Testando se o botão está desabilitado quando formulário for inválido.
- Testando se um botão está habilitado quando formulário for válido.
- Criando método para retornar um campo do formulário.
- Criando método para criar dados (payload) para submeter pro servidor.
- Submetendo dados do formulário.

To get more help on the Angular CLI use `ng help` or go check out the [Angular CLI Overview and Command Reference](https://angular.io/cli) page.
Este curso pode ser adquirido clicando [aqui](https://www.udemy.com/course/draft/4951302/?instructorPreviewMode=guest).
1 change: 1 addition & 0 deletions karma.conf.js
Original file line number Diff line number Diff line change
Expand Up @@ -35,6 +35,7 @@ module.exports = function (config) {
reporters: ['progress', 'kjhtml'],
port: 9876,
colors: true,

logLevel: config.LOG_INFO,
autoWatch: true,
browsers: ['Chrome'],
Expand Down
3 changes: 2 additions & 1 deletion package.json
Original file line number Diff line number Diff line change
Expand Up @@ -29,6 +29,7 @@
"@angular/cli": "~14.2.7",
"@angular/compiler-cli": "^14.2.0",
"@types/jasmine": "~4.0.0",

"jasmine-core": "~4.3.0",
"karma": "~6.4.0",
"karma-chrome-launcher": "~3.1.0",
Expand All @@ -37,4 +38,4 @@
"karma-jasmine-html-reporter": "~2.0.0",
"typescript": "~4.7.2"
}
}
}
10 changes: 7 additions & 3 deletions src/app/app.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -37,14 +37,18 @@
<!-- <app-testing-pipes-directive-route></app-testing-pipes-directive-route> -->

<!-- <h1>Testando Gurda de rotas</h1> -->
<!-- <button (click)="goTo()">Acessar home</button> -->
<!-- <button (click)="goTo('dashboard')">Acessar home</button> -->

<!-- <router-outlet></router-outlet> -->

<!-- <app-testing-directive></app-testing-directive> -->

<!-- <app-form-login></app-form-login> -->

<app-testing-route></app-testing-route>
<!-- <app-testing-route></app-testing-route> -->

<router-outlet></router-outlet>
<!-- <router-outlet></router-outlet> -->

<!-- <app-integration-unit-testing></app-integration-unit-testing> -->

<h1>Curso de Testes Unitários com Angular / Jasmine e Karma</h1>
31 changes: 30 additions & 1 deletion src/app/app.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,8 +1,12 @@
import { TestBed } from '@angular/core/testing';
import { ComponentFixture, TestBed } from '@angular/core/testing';
import { Router } from '@angular/router';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';

describe('AppComponent', () => {
let router: Router;
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
Expand All @@ -12,11 +16,36 @@ describe('AppComponent', () => {
AppComponent
],
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
router = TestBed.inject(Router)
});

it('should create the app', () => {
const fixture = TestBed.createComponent(AppComponent);
const app = fixture.componentInstance;
expect(app).toBeTruthy();
});

it('Deve navegar para url passada', () => {
let route = 'dashboad'
spyOn(router, 'navigate')

component.goTo(route)

expect(router.navigate).toHaveBeenCalledWith(['/dashboad'])
})

it('Deve definir valor para user', () => {
component.ngOnInit()

expect(component.user).toBeDefined();
})

it("Deve listar usuario por id getUsersById", () => {
let spiedComponent = spyOn(component, 'getUserMessage').and.callThrough()
component.getUserMessage('Enviando mensagem')

expect(spiedComponent).toHaveBeenCalledTimes(1)
})
});
5 changes: 3 additions & 2 deletions src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -21,8 +21,9 @@ export class AppComponent implements OnInit {
console.log('Mensagem do filho: ', event)
}

goTo() {
this.router.navigate(['/dashboard'])
goTo(route: string) {
this.router.navigate([`/${route}`])
}


}
6 changes: 3 additions & 3 deletions src/app/app.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,6 @@ import { FixProblemsComponent } from './fix-problems/fix-problems.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations'

import {MatDialogModule} from '@angular/material/dialog';
import { FixedPipe } from './fixed.pipe';
import { HttpPipe } from './http.pipe';
import { TestingPipesDirectiveRouteComponent } from './testing-pipes-directive-route/testing-pipes-directive-route.component';
import { DashboardComponent } from './dashboard/dashboard.component';
Expand All @@ -38,6 +37,7 @@ import { HoverFocusDirective } from './hover-focus.directive';
import { FormLoginComponent } from './form-login/form-login.component';
import { TestingRouteComponent } from './testing-route/testing-route.component';
import { ExtratoComponent } from './extrato/extrato.component';
import { IntegrationUnitTestingComponent } from './integration-unit-testing/integration-unit-testing.component';

@NgModule({
declarations: [
Expand All @@ -59,7 +59,6 @@ import { ExtratoComponent } from './extrato/extrato.component';
HomeComponent,
SpyonComponent,
FixProblemsComponent,
FixedPipe,
HttpPipe,
TestingPipesDirectiveRouteComponent,
DashboardComponent,
Expand All @@ -68,7 +67,8 @@ import { ExtratoComponent } from './extrato/extrato.component';
HoverFocusDirective,
FormLoginComponent,
TestingRouteComponent,
ExtratoComponent
ExtratoComponent,
IntegrationUnitTestingComponent
],
imports: [
BrowserModule,
Expand Down
9 changes: 9 additions & 0 deletions src/app/fill-form/fill-form.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,4 +33,13 @@ describe('FillFormComponent', () => {
expect(input.value).toBe('Danilo')
})

it('Deve preencher formulário', () => {
component.name = 'Danilo'
component.fillForm()

fixture.detectChanges();

expect(component.form.controls['name'].value).toBeDefined();
})

});
8 changes: 0 additions & 8 deletions src/app/fixed.pipe.spec.ts

This file was deleted.

16 changes: 0 additions & 16 deletions src/app/fixed.pipe.ts

This file was deleted.

Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
<p>integration-unit-testing works!</p>
Empty file.
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
import { ComponentFixture, TestBed } from '@angular/core/testing';

import { IntegrationUnitTestingComponent } from './integration-unit-testing.component';

describe('IntegrationUnitTestingComponent', () => {
let component: IntegrationUnitTestingComponent;
let fixture: ComponentFixture<IntegrationUnitTestingComponent>;

beforeEach(async () => {
await TestBed.configureTestingModule({
declarations: [ IntegrationUnitTestingComponent ]
})
.compileComponents();

fixture = TestBed.createComponent(IntegrationUnitTestingComponent);
component = fixture.componentInstance;
fixture.detectChanges();
});

it('should create', () => {
expect(component).toBeTruthy();
});
});
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
import { Component, OnInit } from '@angular/core';

@Component({
selector: 'app-integration-unit-testing',
templateUrl: './integration-unit-testing.component.html',
styleUrls: ['./integration-unit-testing.component.scss']
})
export class IntegrationUnitTestingComponent implements OnInit {

constructor() { }

ngOnInit(): void {
}

getUsers() {

}

}
7 changes: 7 additions & 0 deletions src/app/mock-service/mock-service.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -24,4 +24,11 @@ describe('MockServiceComponent', () => {
it('should create', () => {
expect(component).toBeTruthy();
});

it("Deve chamar getUsers", () => {
let spiedComponent = spyOn(component, 'getUsers').and.callThrough()
component.getUsers()

expect(spiedComponent).toHaveBeenCalledTimes(1)
})
});
Loading

0 comments on commit 8c13b67

Please sign in to comment.