[英]Angular2 service testing : inject a dependency with beforeEach
I am testing services with an Http
dependency. 我正在测试具有Http
依赖性的服务。 Every test looks like this : 每个测试都是这样的:
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 ...
});
As you can see, I need to inject the BackEnd mock at every it. 正如你所看到的,我需要在每一次注入BackEnd mock。
Is it possible to use a beforeEach
to inject the dependency before every test ? 是否可以在每次测试之前使用beforeEach
注入依赖项?
Is it possible to use a beforeEach to inject the dependency before every test ? 是否可以在每次测试之前使用beforeEach注入依赖项?
Sure you could. 当然可以。
let service;
beforeEach(inject([Service], (svc) => {
service = svc;
}))
Though you could also just get the service from the TestBed
, which is also an injector 虽然你也可以从TestBed
获得服务, TestBed
也是一个注入器
let service;
beforeEach(() => {
TestBed.configureTestingModule({
...
})
service = TestBed.get(Service);
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.