答案 0 :(得分:0)
您可以使用MockBackend模拟http响应 参考:https://angular.io/api/http/testing/MockBackend
您可以轻松定义自己的响应并测试所有if / else
// before each test
beforeEach(() => {
this.injector = ReflectiveInjector.resolveAndCreate([
{provide: ConnectionBackend, useClass: MockBackend},
{provide: RequestOptions, useClass: BaseRequestOptions},
Http,
// other dependencies like Router / AppConfig
]);
this.authenticationService = this.injector.get(AuthenticationService);
this.backend = this.injector.get(ConnectionBackend) as MockBackend;
this.backend.connections.subscribe((connection: any) => this.lastConnection = connection);
});
// in your test
const mockErrorResponse = {status: 200};
this.lastConnection.mockRespond(new Response(new ResponseOptions({body: JSON.stringify(mockErrorResponse)})));
tick();