这两个测试似乎有效(至少在我的情况下)
这两种方法之间是否存在一些具体差异?以及如何决定我应该使用哪个(使用 Http 测试服务的最佳实践)?
1. 使用 MockBackend 方法
beforeEach(() => {
TestBed.configureTestingModule({
providers: [
MyService,
MockBackend,
BaseRequestOptions,
{
provide: Http,
deps: [MockBackend, BaseRequestOptions],
useFactory: (backend: XHRBackend, defaultOptions: BaseRequestOptions) => new Http(backend, defaultOptions)
}
],
imports: [HttpModule]
}).compileComponents();
});
it('#getResources should get an items list',
async(inject([MyService], (service: MyService) => {
TestBed.get(MockBackend).connections.subscribe(
(connection: MockConnection) => connection.mockRespond(new Response(
new ResponseOptions({
body: {
items: ['foo','bar']
}
})
))
);
service.getResources('/foobar').subscribe(items => {
expect(items).toEqual(['foo','bar']);
});
}))
);
2. 使用 spyOn().and.returnValue() 方法
let backend: XHRBackend;
let defaultOptions: BaseRequestOptions;
let http = new Http(backend, defaultOptions);
it('#getResources should get an items list', async(() => {
const spy = spyOn(http, 'get')
.and.returnValue(
Observable.of(new Response(new ResponseOptions({
body: {items: ['foo','bar']}
}))
));
let service = new MyService(http);
service.getResources('/foobar').subscribe(items => {
expect(items).toEqual(['foo','bar']);
});
}));