Angular2服务测试:使用beforeEach注入依赖项

时间:2017-04-20 12:58:11

标签: unit-testing angular jasmine

我正在测试具有Http依赖关系的服务。每个测试都是这样的:

import { TestBed, async, inject } from '@angular/core/testing';
import { ValidationService } from './validation.service';
import { HttpModule, Http, Response, ResponseOptions, RequestOptions, Headers, XHRBackend } from '@angular/http';
import { MockBackend, MockConnection } from '@angular/http/testing';

describe('DashboardService', () => {
  beforeEach(() => {
    TestBed.configureTestingModule({
      imports: [HttpModule],
      providers: [
        ValidationService,
        { provide: XHRBackend, useClass: MockBackend }
      ]
    });
  });

  it('should ...',
    inject([ValidationService, XHRBackend],
      (service: ValidationService, mockBackEnd: MockBackend) => {
        mockBackEnd.connections.subscribe((connection: MockConnection) => {
          connection.mockRespond(new Response(new ResponseOptions({
            body: JSON.stringify('content')
          })));
        });
      }));
      // assertions ...
});

正如你所看到的,我需要在每一次注入BackEnd mock。

是否可以在每次测试之前使用beforeEach注入依赖项?

1 个答案:

答案 0 :(得分:35)

  

是否可以在每次测试之前使用beforeEach注入依赖项?

当然可以。

 public enum PropertyInQuestionType {
    C,
    D,
    PC,
    PD,
    M,
    G,
    PM,
    PG,
    U,
    KP,
}

虽然你也可以从let service; beforeEach(inject([Service], (svc) => { service = svc; })) 获得服务,这也是一个注射器

TestBed
相关问题