如何使用Angular 4 Jasmine单元测试用例

时间:2017-12-11 10:07:24

标签: angular jasmine karma-jasmine angular4-router angular4-httpclient

帮助我介绍IF / Else覆盖率和返回HTTP响应的方法以及构造函数,以涵盖 Jasmine Unit测试用例的路由器和Appconfig服务的分支覆盖

enter image description here

1 个答案:

答案 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();