Skip to content

Commit

Permalink
Add tests for new & assign task
Browse files Browse the repository at this point in the history
  • Loading branch information
fdodino committed Jun 20, 2024
1 parent 1fe072c commit 2216d8f
Show file tree
Hide file tree
Showing 9 changed files with 292 additions and 74 deletions.
35 changes: 23 additions & 12 deletions src/app/asignar/asignar.component.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,17 +3,23 @@ import { ComponentFixture, TestBed } from '@angular/core/testing'
import { AsignarComponent } from './asignar.component'
import { ActivatedRoute, Router } from '@angular/router'
import { HttpClient } from '@angular/common/http'
import { httpClientSpy, tareaPrincipal, usuarioAsignatario } from 'services/httpClientSpy'
import {
getHttpClientSpy,
tareaPrincipal,
usuarioAsignatario
} from 'services/httpClientSpy'

const updatedTaskId = 1

describe('AsignarComponent', () => {
let component: AsignarComponent
let fixture: ComponentFixture<AsignarComponent>
let routerSpy: jasmine.SpyObj<Router>
let httpClientSpy: jasmine.SpyObj<HttpClient>

beforeEach(async () => {
routerSpy = jasmine.createSpyObj('Router', ['navigate'])
httpClientSpy = getHttpClientSpy()

await TestBed.configureTestingModule({
imports: [AsignarComponent],
Expand All @@ -23,15 +29,13 @@ describe('AsignarComponent', () => {
provide: ActivatedRoute,
useValue: {
snapshot: {
params: { 'id': updatedTaskId },
params: { id: updatedTaskId }
}
}
},
{ provide: Router, useValue: routerSpy },
{ provide: Router, useValue: routerSpy }
]

})
.compileComponents()
}).compileComponents()

fixture = TestBed.createComponent(AsignarComponent)
component = fixture.componentInstance
Expand All @@ -58,25 +62,33 @@ describe('AsignarComponent', () => {
it('task label', () => {
fixture.detectChanges()
const resultHtml = fixture.debugElement.nativeElement
expect(resultHtml.querySelector('[data-testid=tareaDescripcion]').textContent).toBe(tareaPrincipal.descripcion)
expect(
resultHtml.querySelector('[data-testid=tareaDescripcion]').textContent
).toBe(tareaPrincipal.descripcion)
})

it('assignment should take effect', () => {
const compiled = fixture.debugElement.nativeElement
const nuevoAsignatario = component.usuariosPosibles[0]
component.asignatario = nuevoAsignatario
compiled.querySelector('[data-testid="guardar"]').click()

// Queremos saber que en algún momento se haya pedido al backend que se asigne a otro usuarie
const tareaAsignada = { ...tareaPrincipal.toJSON(), asignadoA: nuevoAsignatario.nombre }
expect(httpClientSpy.put).toHaveBeenCalledWith(`http://localhost:9000/tareas/${tareaPrincipal.id}`, tareaAsignada)
const tareaAsignada = {
...tareaPrincipal.toJSON(),
asignadoA: nuevoAsignatario.nombre
}
expect(httpClientSpy.put).toHaveBeenCalledWith(
`http://localhost:9000/tareas/${tareaPrincipal.id}`,
tareaAsignada
)
})

it('should navigate back to home when form submitted', async () => {
const compiled = fixture.debugElement.nativeElement
compiled.querySelector('[data-testid="guardar"]').click()
await fixture.whenStable()

const [route] = routerSpy.navigate.calls.first().args[0]
expect(route).toBe('/tareas')
})
Expand All @@ -88,5 +100,4 @@ describe('AsignarComponent', () => {
const [route] = routerSpy.navigate.calls.first().args[0]
expect(route).toBe('/tareas')
})

})
2 changes: 1 addition & 1 deletion src/app/nueva-tarea/nueva-tarea.component.html
Original file line number Diff line number Diff line change
Expand Up @@ -51,7 +51,7 @@ <h4>Crear nueva tarea</h4>
<div class="form-group">
<label for="cumplimiento">Fecha</label>
<div class="fila">
<input type="date" autocomplete="off" data-testid="fecha" name="fecha" class="form-control" [(ngModel)]="fecha"
<input type="date" autocomplete="off" data-testid="fecha" name="fecha" class="form-control" [(ngModel)]="tarea.fecha"
name="fechaApuesta" data-testid="fecha" placeholder="Fecha de inicio de la tarea" required>
</div>
<validation-field [tarea]="tarea" [field]="'fecha'"></validation-field>
Expand Down
98 changes: 80 additions & 18 deletions src/app/nueva-tarea/nueva-tarea.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,85 @@
// import { ComponentFixture, TestBed } from '@angular/core/testing'
import { ComponentFixture, TestBed } from '@angular/core/testing'

// import { NuevaTareaComponent } from './nueva-tarea.component'
import { NuevaTareaComponent } from './nueva-tarea.component'
import { Router } from '@angular/router'
import { HttpClient } from '@angular/common/http'
import { getHttpClientSpy } from 'services/httpClientSpy'
import { Usuario } from 'domain/usuario'

// describe('NuevaTareaComponent', () => {
// let component: NuevaTareaComponent
// let fixture: ComponentFixture<NuevaTareaComponent>
describe('NuevaTareaComponent', () => {
let component: NuevaTareaComponent
let fixture: ComponentFixture<NuevaTareaComponent>
let routerSpy: jasmine.SpyObj<Router>
let httpClientSpy: jasmine.SpyObj<HttpClient>

// beforeEach(async () => {
// await TestBed.configureTestingModule({
// imports: [NuevaTareaComponent]
// })
// .compileComponents()
beforeEach(async () => {
routerSpy = jasmine.createSpyObj('Router', ['navigate', 'navigateByUrl'])
httpClientSpy = getHttpClientSpy()

// fixture = TestBed.createComponent(NuevaTareaComponent)
// component = fixture.componentInstance
// fixture.detectChanges()
// })
await TestBed.configureTestingModule({
imports: [NuevaTareaComponent],
providers: [
{ provide: HttpClient, useValue: httpClientSpy },
{ provide: Router, useValue: routerSpy }
]
}).compileComponents()

// it('should create', () => {
// expect(component).toBeTruthy()
// })
// })
fixture = TestBed.createComponent(NuevaTareaComponent)
component = fixture.componentInstance
fixture.detectChanges()
})

it('should create', () => {
expect(component).toBeTruthy()
})

it('should create a new task', async () => {
// Arrange
await sendInput('descripcion', 'Aprender Angular')
await sendInput('iteracion', 'Iteracion 1')
// TODO: lograr que funcione para input type date y drop down
component.tarea.fecha = new Date()
component.asignatario = new Usuario('Nahuel Palumbo')
await sendInput('porcentaje-cumplimiento', '20')

// Act
getByTestId('guardar').click()
fixture.detectChanges()
await fixture.whenStable()

// Assert
const route = routerSpy.navigateByUrl.calls.first().args[0]
expect(route).toBe('/')
})

it('an invalid task cannot be created', async () => {
await sendInput('porcentaje-cumplimiento', '101')
getByTestId('guardar').click()
fixture.detectChanges()
await fixture.whenStable()
expect(routerSpy.navigateByUrl).toHaveBeenCalledTimes(0)
expect(component.tarea.hasErrors).toBeTruthy()
expect(component.tarea.errors.length).toBe(4)
validateErrorField('descripcion')
validateErrorField('iteracion')
validateErrorField('fecha')
validateErrorField('porcentajeCumplimiento')
})

function getByTestId(testId: string) {
const resultHtml = fixture.debugElement.nativeElement
return resultHtml.querySelector(`[data-testid="${testId}"`)
}

async function sendInput(testId: string, text: string | Date) {
const inputElement = getByTestId(testId)
inputElement.value = text
inputElement.dispatchEvent(new Event('input'))
fixture.detectChanges()
return fixture.whenStable()
}

function validateErrorField(field: string) {
expect(getByTestId(`error-message-${field}`).innerHTML).toBeTruthy()
}
})
3 changes: 0 additions & 3 deletions src/app/nueva-tarea/nueva-tarea.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import { Usuario } from 'domain/usuario'
import { TareasService } from 'services/tareas.service'
import { UsuariosService } from 'services/usuarios.service'
import { mostrarError } from 'util/errorHandler'
import dayjs from 'dayjs'

@Component({
selector: 'app-nueva-tarea',
Expand All @@ -21,7 +20,6 @@ export class NuevaTareaComponent {
asignatario?: Usuario
usuariosPosibles: Usuario[] = []
errors: string[] = []
fecha = new Date()

constructor(private usuariosService: UsuariosService, private tareasService: TareasService, private router: Router) { }

Expand All @@ -42,7 +40,6 @@ export class NuevaTareaComponent {

async guardar() {
try {
this.tarea.fecha = dayjs(this.fecha)
this.tarea.validar()
if (this.tarea.invalid()) {
return
Expand Down
159 changes: 141 additions & 18 deletions src/app/tareas/tareas.component.spec.ts
Original file line number Diff line number Diff line change
@@ -1,23 +1,146 @@
// import { ComponentFixture, TestBed } from '@angular/core/testing'
import {
ComponentFixture,
TestBed,
fakeAsync,
flush,
tick
} from '@angular/core/testing'

// import { TareasComponent } from './tareas.component'
import { TareasComponent } from './tareas.component'
import { getHttpClientSpy } from 'services/httpClientSpy'
import { HttpClient } from '@angular/common/http'
import { Router } from '@angular/router'
import { registerLocaleData } from '@angular/common'
import localeEs from '@angular/common/locales/es'
import { throwError } from 'rxjs'

// describe('TareasComponent', () => {
// let component: TareasComponent
// let fixture: ComponentFixture<TareasComponent>
//
/** Registramos el locale ES para formatear números */
// Font Awesome para los íconos
//
// routing
// componentes propios

// beforeEach(async () => {
// await TestBed.configureTestingModule({
// imports: [TareasComponent]
// })
// .compileComponents()
registerLocaleData(localeEs)

// fixture = TestBed.createComponent(TareasComponent)
// component = fixture.componentInstance
// fixture.detectChanges()
// })
describe('TareasComponent', () => {
let component: TareasComponent
let fixture: ComponentFixture<TareasComponent>
let routerSpy: jasmine.SpyObj<Router>
let httpClientSpy: jasmine.SpyObj<HttpClient>

// it('should create', () => {
// expect(component).toBeTruthy()
// })
// })
beforeEach(async () => {
routerSpy = jasmine.createSpyObj('Router', ['navigate', 'navigateByUrl'])
httpClientSpy = getHttpClientSpy()

await TestBed.configureTestingModule({
imports: [TareasComponent],
providers: [
{ provide: HttpClient, useValue: httpClientSpy },
{ provide: Router, useValue: routerSpy }
]
}).compileComponents()

fixture = TestBed.createComponent(TareasComponent)
component = fixture.componentInstance
fixture.detectChanges()

await fixture.whenStable()
fixture.detectChanges()
})

it('should create', () => {
expect(component).toBeTruthy()
})

it('should initially show 2 pending tasks', fakeAsync(() => {
expect(2).toBe(component.tareas.length)
}))

it('first task can be marked as done', () => {
expect(getByTestId('cumplir_1')).toBeTruthy()
})

it('when a task is done, it has 100% of completion', () => {
getByTestId('cumplir_1').click()
fixture.detectChanges()
// Chequeamos que el objeto de dominio tarea responde correctamente,
// pero también el binding entre componente y vista
expect(getByTestId('porcentaje_1').textContent).toBe('100,00')
// https://daveceddia.com/jasmine-2-spy-cheat-sheet/
// Chequeamos que se haya enviado la información correctamente al backend
const tareaActualizada = httpClientSpy.put.calls.mostRecent().args[1]
expect(tareaActualizada.porcentajeCumplimiento).toBe(100)
})

it('unassign first task', async () => {
getByTestId('desasignar_1').click()
fixture.detectChanges()
expect(getByTestId('asignatario_1').textContent).toBe('')
})

it('searching for second task should have one tr in tasks list', () => {
component.tareaBuscada = 'e2e'
fixture.detectChanges()
const resultHtml = fixture.debugElement.nativeElement
expect(
resultHtml.querySelectorAll('[data-testid="fila-tarea"]').length
).toBe(1)
})

it('unassign - should catch error gracefully', fakeAsync(() => {
httpClientSpy.put.and.returnValue(throwError(() => new Error('Fake error')))

getByTestId('desasignar_1').click()
tick(1000)
fixture.detectChanges()

expect(getByTestId('error-message')?.innerHTML).toBeTruthy()
// Importante para que no falle con "Error: 1 timer(s) still in the queue"
// tick(2000)
// o mejor...
flush()

httpClientSpy.put.calls.reset()
}))

it('finish - should catch error gracefully', fakeAsync(() => {
httpClientSpy.put.and.returnValue(throwError(() => new Error('Fake error')))

getByTestId('cumplir_1').click()
tick(1000)
fixture.detectChanges()
expect(getByTestId('error-message')?.innerHTML).toBeTruthy()
flush()

httpClientSpy.put.calls.reset()
}))

it('create new task should navigate', async () => {
getByTestId('nueva-tarea').click()

fixture.detectChanges()

const route = routerSpy.navigateByUrl.calls.first().args[0]
expect(route).toBe('/nuevaTarea')
})

it('assign task should navigate', () => {
getByTestId('asignar_2').click()

fixture.detectChanges()

// const route = routerSpy.navigate.calls.first().args[0]
// expect(route).toEqual(['/asignarTarea', 2])

// Con destructuring
const [url, tareaId] = routerSpy.navigate.calls.first().args[0]
expect(url).toBe('/asignarTarea')
expect(tareaId).toBe(2)
})

function getByTestId(testId: string) {
const resultHtml = fixture.debugElement.nativeElement
return resultHtml.querySelector(`[data-testid="${testId}"]`)
}
})
Loading

0 comments on commit 2216d8f

Please sign in to comment.