I am testing the call function below in angular 4.
import { Component, OnInit } from '@angular/core';
import { AppService } from './app.service';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'jasmine-error-test';
constructor(private appService: AppService) { }
ngOnInit(): void {
this.call();
}
call() {
return this.appService.load().subscribe((res) => {
this.title = res;
}, (err) => {
throw new Error('Failed');
});
}
}
To test the part where an error is thrown from the subscribe i am doing the following.
describe('when call is called', () => {
describe('when the service returns an error', () => {
let app;
beforeEach(async(() => {
const fixture = TestBed.createComponent(AppComponent);
app = fixture.componentInstance;
(service.load as jasmine.Spy).and.returnValue(Observable.throw({
status: 406,
error: {
message: 'Test 406 error'
}
}));
}));
it('it should throw a matching error', async(() => {
expect(() => { app.call(); }).toThrowError('Failed');
}));
});
});
But the test fails with and error
Expected function to throw an Error.
If i use the debugger window it show the line where the error is being thrown is being hit , but still i don't get the test to pass. Can somebody let me know what is going on.