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

18 unit-testing jasmine angular

我正在测试具有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 ...
});
Run Code Online (Sandbox Code Playgroud)

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

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

Pau*_*tha 42

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

当然可以.

let service;

beforeEach(inject([Service], (svc) => {
  service = svc;
}))
Run Code Online (Sandbox Code Playgroud)

虽然你也可以从中获得服务TestBed,这也是一个注入器

let service;

beforeEach(() => {
  TestBed.configureTestingModule({
    ...
  })

  service = TestBed.get(Service);
})
Run Code Online (Sandbox Code Playgroud)