Skip to content

Instantly share code, notes, and snippets.

@barbaraperim
Last active February 13, 2020 02:08
Show Gist options
  • Save barbaraperim/7e1b42522678ae1e03f1693fe8da1351 to your computer and use it in GitHub Desktop.
Save barbaraperim/7e1b42522678ae1e03f1693fe8da1351 to your computer and use it in GitHub Desktop.
Button click test - spec.ts
import { TestBed, async } from '@angular/core/testing';
import { RouterTestingModule } from '@angular/router/testing';
import { AppComponent } from './app.component';
import { TestService } from './test-service/test.service';
import { Router } from '@angular/router';
import { TestResponse } from './test-service/models/test.response';
import { HttpResponse } from '@angular/common/http';
import { Observable, of, throwError } from 'rxjs';
import { ComponentFixture } from '@angular/core/testing';
import { routes } from './app-routing.module';
class MockTestService {
callAPI(): Observable<HttpResponse<TestResponse>> { return null; }
}
describe('AppComponent', () => {
let component: AppComponent;
let fixture: ComponentFixture<AppComponent>;
let testService: TestService;
let router: Router;
beforeEach(async(() => {
TestBed.configureTestingModule({
imports: [
RouterTestingModule.withRoutes(routes)
],
declarations: [
AppComponent
],
providers: [
{ provide: TestService, useClass: MockTestService }
]
}).compileComponents()
.then(() => {
fixture = TestBed.createComponent(AppComponent);
component = fixture.componentInstance;
testService = TestBed.get(TestService);
router = TestBed.get(Router);
router.initialNavigation();
});
}));
it('should create the app', () => {
const app = fixture.debugElement.componentInstance;
expect(app).toBeTruthy();
});
it('Botão executar click sucesso', () => {
const mockResponse: TestResponse = {
message: 'Chamada realizada com sucesso'
};
const button = fixture.nativeElement.querySelector('.btn');
spyOn(router, 'navigate');
spyOn(testService, 'callAPI').and.returnValue(of(new HttpResponse({body: mockResponse})));
button.click();
fixture.detectChanges();
const success = fixture.nativeElement.querySelector('.success');
expect(router.navigate).toHaveBeenCalledWith(['/teste']);
expect(testService.callAPI).toHaveBeenCalledTimes(1);
expect(success.textContent).toContain(mockResponse.message);
});
it('Botão executar click falha', () => {
const errorResponse = {
status: 400,
message: 'Falha ao realizar chamada'
};
const button = fixture.nativeElement.querySelector('.btn');
spyOn(testService, 'callAPI').and.returnValue(throwError(errorResponse));
button.click();
fixture.detectChanges();
const error = fixture.nativeElement.querySelector('.error');
expect(testService.callAPI).toHaveBeenCalledTimes(1);
expect(error.textContent).toContain(errorResponse.message);
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment