在angular1中,当我在本地开发时,我能够使用$ httpBackend来存根/模拟http调用。它会有点像这样:
$httpBackend
.whenGET('/api/v1/accounts/ticker')
.respond({data: [1,2,3]})
如何在Angular2中为本地开发做类似的事情?
答案 0 :(得分:0)
<强>更新强>
describe('...', () => {
beforeEach(() => {
TestBed.configureTestingModule({
declarations: [TestComponent],
providers: [
MockBackend
{provide: XHRBackend, useExisting: MockBackend},
{provide: JSONPBackend, useExisting: MockBackend}
],
imports: [HttpModule]
});
});
it('...', () => {
const fixture = TestBed.createComponent(TestComponent);
});
});
<强>原始强>
bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})]);
然后注入MockBackend
并像
backend.connections.subscribe(c => connection = c);
http.request('data.json').subscribe((res) => {
expect(res.text()).toBe('awesome');
async.done();
});
connection.mockRespond(new Response('awesome'));
您可以将其注入组件或引导后(如
)bootstrap(AppComponent, [
HTTP_PROVIDERS,
provide(XHRBackend, {useClass: MockBackend}),
provide(JSONPBackend, {useClass: MockBackend})])
.then((componentRef: ComponentRef) => {
let injector = componentRef.injector;
let backend = injector.get(MockBackend);
backend.connections.subscribe(connection => {
if(connection.request ...) {
connection.mockRespond(new Response('awesome'));
}
});
});