我正在测试具有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
注入依赖项?
答案 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