Reputation: 11
Using Angular 11 I can't test the error in the get request to obtain 100% coverage enter image description here
from the oninit of the AppComponent I call the "loadNotifications" method which makes an asynchronous get call which controls both the correct and incorrect output
app.component.ts
...
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.scss']
})
export class AppComponent {
...
private cargarNotificaciones(): void {
this._http.get<any>(environment.API_BASE_PATH + environment.endPointNotification).subscribe(
(data: any[]) => {
cosole.log(data);
},
(error) => {
this._ir.interpretarRespuesta(error);
}
);
}
The problem is that from the tests, I am not able to go through the error and be able to have 100% coverage
app.component.spec.ts
...
describe('AppComponent', () => {
let fixture: ComponentFixture<any>;
let injector: TestBed;
let httpClientSpy: { get: jasmine.Spy };
beforeEach(async () => {
await TestBed.configureTestingModule({
imports: [
...
],
declarations: [
AppComponent
],
providers: [
...
],
schemas: [CUSTOM_ELEMENTS_SCHEMA]
}).compileComponents();
fixture = TestBed.createComponent(AppComponent);
injector = getTestBed();
httpClientSpy = jasmine.createSpyObj('HttpClient', ['get']);
});
it('Debería funcionar el método getNotificaciones con error', waitForAsync(() => {
const app = fixture.componentInstance;
spyOn(app._http, 'get').and.returnValue(new Error('error 404'));
fixture.detectChanges();
const resultado = app.cargarNotificaciones();
expect(resultado).toBe(undefined);
}));
});
Upvotes: 1
Views: 246
Reputation: 5600
_http.get
should return an observable instead of just an Error object. You can use throwError
or of
from rxjs. try to do something like this:
it('Debería funcionar el método getNotificaciones con error', waitForAsync(() => {
const app = fixture.componentInstance;
spyOn(app._http, 'get').and.returnValue(throwError('error 404'));
fixture.detectChanges();
const resultado = app.cargarNotificaciones();
expect(resultado).toBe(undefined);
}));
or
it('Debería funcionar el método getNotificaciones con error', waitForAsync(() => {
const app = fixture.componentInstance;
spyOn(app._http, 'get').and.returnValue(of(new Error('error 404')));
fixture.detectChanges();
const resultado = app.cargarNotificaciones();
expect(resultado).toBe(undefined);
}));
Upvotes: 1